From a91219bebcdf2a1a640095cd7efb0583298c725c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 19:12:33 +0200 Subject: [PATCH 001/110] The Darkstalkers subpixel check should be == 0. Fixes #14953 again --- GPU/Software/RasterizerRectangle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index 96e7a7f0fd..f25be97f64 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -286,7 +286,7 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b // We already have a fast path for clear in ClearRectangle. bool state_check = !state.pixelID.clearMode && !state.samplerID.hasAnyMips && NoClampOrWrap(state, v0.texturecoords) && NoClampOrWrap(state, v1.texturecoords); // This doesn't work well with offset drawing, see #15876. Through never has a subpixel offset. - bool subpixel_check = ((v0.screenpos.x | v0.screenpos.y | v1.screenpos.x | v1.screenpos.y) & 0xF) != 0; + bool subpixel_check = ((v0.screenpos.x | v0.screenpos.y | v1.screenpos.x | v1.screenpos.y) & 0xF) == 0; if ((coord_check || !state.enableTextures) && orient_check && state_check && subpixel_check) { binner.AddSprite(v0, v1); return true; From 06e9995ab63e5f2e3a8125844915eb5e152833bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 19:13:14 +0200 Subject: [PATCH 002/110] Remove reference to non-existent file from Common.vcxproj --- Common/Common.vcxproj | 3 --- Common/Common.vcxproj.filters | 5 ----- 2 files changed, 8 deletions(-) diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj index b176b3d040..2895cdc837 100644 --- a/Common/Common.vcxproj +++ b/Common/Common.vcxproj @@ -988,9 +988,6 @@ {f761046e-6c38-4428-a5f1-38391a37bb34} - - - diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters index 2261dddd4d..ff9fd9eaa6 100644 --- a/Common/Common.vcxproj.filters +++ b/Common/Common.vcxproj.filters @@ -901,9 +901,4 @@ ext\libpng17 - - - Math\lin - - \ No newline at end of file From 97ad3c21b41f3649dd78a8b31c154f1e987ad09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 19:21:04 +0200 Subject: [PATCH 003/110] libretro build fix, see #15968 --- libretro/Makefile.common | 1 - 1 file changed, 1 deletion(-) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index cb195694be..ab82fcca28 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -694,7 +694,6 @@ ifeq ($(WITH_DYNAREC),1) $(COREDIR)/MIPS/x86/RegCache.cpp \ $(COREDIR)/MIPS/x86/RegCacheFPU.cpp \ $(GPUDIR)/Common/VertexDecoderX86.cpp - SOURCES_C += $(COMMONDIR)/Math/fast/fast_matrix_sse.c endif endif #UDIS86 From 542e7aa5550d30bf9c9bad16849ea024919c1aab Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 10:38:38 -0700 Subject: [PATCH 004/110] GE Debugger: Add a table of register metadata. So far, not used, but indicates info about each GE register. --- CMakeLists.txt | 2 + GPU/Debugger/GECommandTable.cpp | 415 ++++++++++++++++++++++++++++ GPU/Debugger/GECommandTable.h | 79 ++++++ GPU/GPU.vcxproj | 2 + GPU/GPU.vcxproj.filters | 6 + GPU/GPUState.h | 2 +- UWP/GPU_UWP/GPU_UWP.vcxproj | 2 + UWP/GPU_UWP/GPU_UWP.vcxproj.filters | 2 + android/jni/Android.mk | 1 + libretro/Makefile.common | 1 + 10 files changed, 511 insertions(+), 1 deletion(-) create mode 100644 GPU/Debugger/GECommandTable.cpp create mode 100644 GPU/Debugger/GECommandTable.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 31b9bee36f..79928bc4bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1590,6 +1590,8 @@ set(GPU_SOURCES GPU/Debugger/Breakpoints.h GPU/Debugger/Debugger.cpp GPU/Debugger/Debugger.h + GPU/Debugger/GECommandTable.cpp + GPU/Debugger/GECommandTable.h GPU/Debugger/Playback.cpp GPU/Debugger/Playback.h GPU/Debugger/Record.cpp diff --git a/GPU/Debugger/GECommandTable.cpp b/GPU/Debugger/GECommandTable.cpp new file mode 100644 index 0000000000..95e77f1bb6 --- /dev/null +++ b/GPU/Debugger/GECommandTable.cpp @@ -0,0 +1,415 @@ +// Copyright (c) 2022- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include +#include "Common/Common.h" +#include "Common/Log.h" +#include "GPU/Debugger/GECommandTable.h" +#include "GPU/ge_constants.h" + +struct GECmdAlias { + GECommand reg; + const char *aliases[3]; +}; + +static constexpr GECmdInfo geCmdInfo[] = { + { GE_CMD_NOP, "nop", GECmdFormat::NONE }, + { GE_CMD_VADDR, "setvaddr", GECmdFormat::RELATIVE_ADDR }, + { GE_CMD_IADDR, "setiaddr", GECmdFormat::RELATIVE_ADDR }, + { GE_CMD_UNKNOWN_03, "unknown03", GECmdFormat::NONE }, + { GE_CMD_PRIM, "prim", GECmdFormat::PRIM }, + { GE_CMD_BEZIER, "bezier", GECmdFormat::BEZIER }, + { GE_CMD_SPLINE, "spline", GECmdFormat::SPLINE }, + { GE_CMD_BOUNDINGBOX, "btest", GECmdFormat::PRIM }, + { GE_CMD_JUMP, "jump", GECmdFormat::JUMP }, + { GE_CMD_BJUMP, "bjump", GECmdFormat::JUMP }, + { GE_CMD_CALL, "call", GECmdFormat::JUMP }, + { GE_CMD_RET, "ret", GECmdFormat::NONE }, + { GE_CMD_END, "end", GECmdFormat::DATA16 }, + { GE_CMD_UNKNOWN_0D, "unknown0d", GECmdFormat::NONE }, + { GE_CMD_SIGNAL, "signal", GECmdFormat::SIGNAL }, + { GE_CMD_FINISH, "finish", GECmdFormat::NONE }, + { GE_CMD_BASE, "base", GECmdFormat::HIGH_ADDR_ONLY }, + { GE_CMD_UNKNOWN_11, "unknown11", GECmdFormat::NONE }, + { GE_CMD_VERTEXTYPE, "vtype", GECmdFormat::VERTEX_TYPE }, + { GE_CMD_OFFSETADDR, "setoffset", GECmdFormat::OFFSET_ADDR }, + { GE_CMD_ORIGIN, "origin", GECmdFormat::NONE }, + { GE_CMD_REGION1, "regionrate", GECmdFormat::X10_Y10 }, + { GE_CMD_REGION2, "regionstop", GECmdFormat::X10_Y10 }, + { GE_CMD_LIGHTINGENABLE, "lighting_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE0, "light0_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE1, "light1_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE2, "light2_on", GECmdFormat::FLAG }, + { GE_CMD_LIGHTENABLE3, "light3_on", GECmdFormat::FLAG }, + { GE_CMD_DEPTHCLAMPENABLE, "zclamp_on", GECmdFormat::FLAG }, + { GE_CMD_CULLFACEENABLE, "cull_on", GECmdFormat::FLAG }, + { GE_CMD_TEXTUREMAPENABLE, "tex_on", GECmdFormat::FLAG }, + { GE_CMD_FOGENABLE, "fog_on", GECmdFormat::FLAG }, + { GE_CMD_DITHERENABLE, "dither_on", GECmdFormat::FLAG }, + { GE_CMD_ALPHABLENDENABLE, "ablend_on", GECmdFormat::FLAG }, + { GE_CMD_ALPHABLENDENABLE, "atest_on", GECmdFormat::FLAG }, + { GE_CMD_ZTESTENABLE, "ztest_on", GECmdFormat::FLAG }, + { GE_CMD_STENCILTESTENABLE, "stest_on", GECmdFormat::FLAG }, + { GE_CMD_ANTIALIASENABLE, "antialias_on", GECmdFormat::FLAG }, + { GE_CMD_PATCHCULLENABLE, "patchcull_on", GECmdFormat::FLAG }, + { GE_CMD_COLORTESTENABLE, "ctest_on", GECmdFormat::FLAG }, + { GE_CMD_LOGICOPENABLE, "logicop_on", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_29, "unknown29", GECmdFormat::NONE }, + { GE_CMD_BONEMATRIXNUMBER, "bonemtxnum", GECmdFormat::BONE_NUM }, + { GE_CMD_BONEMATRIXDATA, "bonemtxdata", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT0, "morph0", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT1, "morph1", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT2, "morph2", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT3, "morph3", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT4, "morph4", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT5, "morph5", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT6, "morph6", GECmdFormat::FLOAT }, + { GE_CMD_MORPHWEIGHT7, "morph7", GECmdFormat::FLOAT }, + { GE_CMD_UNKNOWN_34, "unknown34", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_35, "unknown35", GECmdFormat::NONE }, + { GE_CMD_PATCHDIVISION, "patchdivision", GECmdFormat::PATCH_DIVISION }, + { GE_CMD_PATCHPRIMITIVE, "patchprim", GECmdFormat::PATCH_PRIM }, + { GE_CMD_PATCHFACING, "patchreversenormals", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_39, "unknown39", GECmdFormat::NONE }, + { GE_CMD_WORLDMATRIXNUMBER, "worldmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_WORLDMATRIXDATA, "worldmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_VIEWMATRIXNUMBER, "viewmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_VIEWMATRIXDATA, "viewmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_PROJMATRIXNUMBER, "projmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_PROJMATRIXDATA, "projmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_TGENMATRIXNUMBER, "texgenmtxnum", GECmdFormat::MATRIX_NUM }, + { GE_CMD_TGENMATRIXDATA, "texgenmtxdata", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTXSCALE, "vpxscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTYSCALE, "vpyscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTZSCALE, "vpzscale", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTXCENTER, "vpxcenter", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTYCENTER, "vpycenter", GECmdFormat::FLOAT }, + { GE_CMD_VIEWPORTZCENTER, "vpzcenter", GECmdFormat::FLOAT }, + { GE_CMD_TEXSCALEU, "texscaleu", GECmdFormat::FLOAT }, + { GE_CMD_TEXSCALEV, "texscalev", GECmdFormat::FLOAT }, + { GE_CMD_TEXOFFSETU, "texoffsetu", GECmdFormat::FLOAT }, + { GE_CMD_TEXOFFSETV, "texoffsetv", GECmdFormat::FLOAT }, + { GE_CMD_OFFSETX, "offsetx", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_OFFSETY, "offsety", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_UNKNOWN_4E, "unknown4e", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_4F, "unknown4f", GECmdFormat::NONE }, + // Really shade mode, but using gouraud as the default so it can be 1/0. + { GE_CMD_SHADEMODE, "gouraud", GECmdFormat::FLAG }, + { GE_CMD_REVERSENORMAL, "reversenormals", GECmdFormat::FLAG }, + { GE_CMD_UNKNOWN_52, "unknown52", GECmdFormat::NONE }, + { GE_CMD_MATERIALUPDATE, "materialupdate", GECmdFormat::MATERIAL_UPDATE }, + { GE_CMD_MATERIALEMISSIVE, "materialemissive", GECmdFormat::RGB }, + { GE_CMD_MATERIALAMBIENT, "materialambient", GECmdFormat::RGB }, + { GE_CMD_MATERIALDIFFUSE, "materialdiffuse", GECmdFormat::RGB }, + { GE_CMD_MATERIALSPECULAR, "materialspecular", GECmdFormat::RGB }, + { GE_CMD_MATERIALALPHA, "materialambienta", GECmdFormat::DATA8 }, + { GE_CMD_UNKNOWN_59, "unknown59", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_5A, "unknown5a", GECmdFormat::NONE }, + { GE_CMD_MATERIALSPECULARCOEF, "specularcoef", GECmdFormat::FLOAT }, + { GE_CMD_AMBIENTCOLOR, "ambient", GECmdFormat::RGB }, + { GE_CMD_AMBIENTALPHA, "ambienta", GECmdFormat::DATA8 }, + { GE_CMD_LIGHTMODE, "lightseparate", GECmdFormat::FLAG }, + { GE_CMD_LIGHTTYPE0, "ltype0", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE1, "ltype1", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE2, "ltype2", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LIGHTTYPE3, "ltype3", GECmdFormat::LIGHT_TYPE }, + { GE_CMD_LX0, "light0posx", GECmdFormat::FLOAT }, + { GE_CMD_LY0, "light0posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ0, "light0posz", GECmdFormat::FLOAT }, + { GE_CMD_LX1, "light1posx", GECmdFormat::FLOAT }, + { GE_CMD_LY1, "light1posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ1, "light1posz", GECmdFormat::FLOAT }, + { GE_CMD_LX2, "light2posx", GECmdFormat::FLOAT }, + { GE_CMD_LY2, "light2posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ2, "light2posz", GECmdFormat::FLOAT }, + { GE_CMD_LX3, "light3posx", GECmdFormat::FLOAT }, + { GE_CMD_LY3, "light3posy", GECmdFormat::FLOAT }, + { GE_CMD_LZ3, "light3posz", GECmdFormat::FLOAT }, + { GE_CMD_LDX0, "light0dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY0, "light0diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ0, "light0dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX1, "light1dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY1, "light1diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ1, "light1dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX2, "light2dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY2, "light2diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ2, "light2dirz", GECmdFormat::FLOAT }, + { GE_CMD_LDX3, "light3dirx", GECmdFormat::FLOAT }, + { GE_CMD_LDY3, "light3diry", GECmdFormat::FLOAT }, + { GE_CMD_LDZ3, "light3dirz", GECmdFormat::FLOAT }, + { GE_CMD_LKA0, "light0attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB0, "light0attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC0, "light0attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA1, "light1attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB1, "light1attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC1, "light1attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA2, "light2attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB2, "light2attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC2, "light2attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKA3, "light3attpow0", GECmdFormat::FLOAT }, + { GE_CMD_LKB3, "light3attpow1", GECmdFormat::FLOAT }, + { GE_CMD_LKC3, "light3attpow2", GECmdFormat::FLOAT }, + { GE_CMD_LKS0, "light0spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS1, "light1spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS2, "light2spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKS3, "light3spotexp", GECmdFormat::FLOAT }, + { GE_CMD_LKO0, "light0spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO1, "light1spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO2, "light2spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LKO3, "light3spotcutoff", GECmdFormat::FLOAT }, + { GE_CMD_LAC0, "light0ambient", GECmdFormat::RGB }, + { GE_CMD_LDC0, "light0diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC0, "light0specular", GECmdFormat::RGB }, + { GE_CMD_LAC1, "light1ambient", GECmdFormat::RGB }, + { GE_CMD_LDC1, "light1diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC1, "light1specular", GECmdFormat::RGB }, + { GE_CMD_LAC2, "light2ambient", GECmdFormat::RGB }, + { GE_CMD_LDC2, "light2diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC2, "light2specular", GECmdFormat::RGB }, + { GE_CMD_LAC3, "light3ambient", GECmdFormat::RGB }, + { GE_CMD_LDC3, "light3diffuse", GECmdFormat::RGB }, + { GE_CMD_LSC3, "light3specular", GECmdFormat::RGB }, + { GE_CMD_CULL, "cullccw", GECmdFormat::FLAG }, + { GE_CMD_FRAMEBUFPTR, "fbptr", GECmdFormat::LOW_ADDR_ONLY }, + { GE_CMD_FRAMEBUFWIDTH, "fbstride", GECmdFormat::STRIDE }, + { GE_CMD_ZBUFPTR, "zbptr", GECmdFormat::LOW_ADDR_ONLY }, + { GE_CMD_ZBUFWIDTH, "zbstride", GECmdFormat::STRIDE }, + { GE_CMD_TEXADDR0, "texaddr0", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR1, "texaddr1", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR2, "texaddr2", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR3, "texaddr3", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR4, "texaddr4", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR5, "texaddr5", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR6, "texaddr6", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR7, "texaddr7", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXBUFWIDTH0, "texbufw0", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH1, "texbufw1", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH2, "texbufw2", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH3, "texbufw3", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH4, "texbufw4", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH5, "texbufw5", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH6, "texbufw6", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TEXBUFWIDTH7, "texbufw7", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_CLUTADDR, "clutaddr", GECmdFormat::LOW_ADDR }, + { GE_CMD_CLUTADDRUPPER, "clutaddrhigh", GECmdFormat::HIGH_ADDR }, + { GE_CMD_TRANSFERSRC, "transfersrc", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERSRCW, "transfersrcstride", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_TRANSFERDST, "transferdst", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERDSTW, "transferdststride", GECmdFormat::STRIDE_HIGH_ADDR }, + { GE_CMD_UNKNOWN_B6, "unknownb6", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_B7, "unknownb7", GECmdFormat::NONE }, + { GE_CMD_TEXSIZE0, "texsize0", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE1, "texsize1", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE2, "texsize2", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE3, "texsize3", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE4, "texsize4", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE5, "texsize5", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE6, "texsize6", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXSIZE7, "texsize7", GECmdFormat::TEX_SIZE }, + { GE_CMD_TEXMAPMODE, "texmapmode", GECmdFormat::TEX_MAP_MODE }, + { GE_CMD_TEXSHADELS, "texlightsrc", GECmdFormat::TEX_LIGHT_SRC }, + { GE_CMD_TEXMODE, "texmode", GECmdFormat::TEX_MODE }, + { GE_CMD_TEXFORMAT, "texformat", GECmdFormat::TEX_FORMAT }, + { GE_CMD_LOADCLUT, "loadclut", GECmdFormat::CLUT_BLOCKS }, + { GE_CMD_CLUTFORMAT, "clutformat", GECmdFormat::CLUT_FORMAT }, + { GE_CMD_TEXFILTER, "texfilter", GECmdFormat::TEX_FILTER }, + { GE_CMD_TEXWRAP, "texclamp", GECmdFormat::TEX_CLAMP }, + { GE_CMD_TEXLEVEL, "texlevelmode", GECmdFormat::TEX_LEVEL_MODE }, + { GE_CMD_TEXFUNC, "texfunc", GECmdFormat::TEX_FUNC }, + { GE_CMD_TEXENVCOLOR, "texenv", GECmdFormat::RGB }, + { GE_CMD_TEXFLUSH, "texflush", GECmdFormat::NONE }, + { GE_CMD_TEXSYNC, "texsync", GECmdFormat::NONE }, + { GE_CMD_FOG1, "fogend", GECmdFormat::FLOAT }, + { GE_CMD_FOG2, "fogslope", GECmdFormat::FLOAT }, + { GE_CMD_FOGCOLOR, "fogcolor", GECmdFormat::RGB }, + { GE_CMD_TEXLODSLOPE, "texlodslope", GECmdFormat::FLOAT }, + { GE_CMD_UNKNOWN_D1, "unknownd1", GECmdFormat::NONE }, + { GE_CMD_FRAMEBUFPIXFORMAT, "fbformat", GECmdFormat::TEX_FORMAT }, + { GE_CMD_CLEARMODE, "clearmode", GECmdFormat::CLEAR_MODE }, + { GE_CMD_SCISSOR1, "scissor1", GECmdFormat::X10_Y10 }, + { GE_CMD_SCISSOR2, "scissor2", GECmdFormat::X10_Y10 }, + { GE_CMD_MINZ, "minz", GECmdFormat::DATA16 }, + { GE_CMD_MAXZ, "maxz", GECmdFormat::DATA16 }, + { GE_CMD_COLORTEST, "ctestfunc", GECmdFormat::COLOR_TEST_FUNC }, + { GE_CMD_COLORREF, "ctestref", GECmdFormat::RGB }, + { GE_CMD_COLORTESTMASK, "ctestmask", GECmdFormat::RGB }, + { GE_CMD_ALPHATEST, "atest", GECmdFormat::ALPHA_TEST }, + { GE_CMD_STENCILTEST, "stest", GECmdFormat::ALPHA_TEST }, + { GE_CMD_STENCILOP, "stencilop", GECmdFormat::STENCIL_OP }, + { GE_CMD_ZTEST, "ztest", GECmdFormat::DEPTH_TEST_FUNC }, + { GE_CMD_BLENDMODE, "blendmode", GECmdFormat::BLEND_MODE }, + { GE_CMD_BLENDFIXEDA, "blendfixa", GECmdFormat::RGB }, + { GE_CMD_BLENDFIXEDB, "blendfixb", GECmdFormat::RGB }, + { GE_CMD_DITH0, "dither0", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH1, "dither1", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH2, "dither2", GECmdFormat::DITHER_ROW }, + { GE_CMD_DITH3, "dither3", GECmdFormat::DITHER_ROW }, + { GE_CMD_LOGICOP, "logicop", GECmdFormat::LOGIC_OP }, + { GE_CMD_ZWRITEDISABLE, "zwrite_off", GECmdFormat::FLAG }, + { GE_CMD_MASKRGB, "rgbmask_block", GECmdFormat::RGB }, + { GE_CMD_MASKALPHA, "swritemask_block", GECmdFormat::DATA8 }, + { GE_CMD_TRANSFERSTART, "transferstart_bpp", GECmdFormat::FLAG }, + { GE_CMD_TRANSFERSRCPOS, "transfersrcpos", GECmdFormat::X10_Y10 }, + { GE_CMD_TRANSFERDSTPOS, "transferdstpos", GECmdFormat::X10_Y10 }, + { GE_CMD_UNKNOWN_ED, "unknowned", GECmdFormat::NONE }, + { GE_CMD_TRANSFERSIZE, "transfersize", GECmdFormat::X10_Y10 }, + { GE_CMD_UNKNOWN_EF, "unknownef", GECmdFormat::NONE }, + { GE_CMD_VSCX, "immx", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_VSCY, "immy", GECmdFormat::SUBPIXEL_COORD }, + { GE_CMD_VSCZ, "immz", GECmdFormat::DATA16 }, + { GE_CMD_VTCS, "imms", GECmdFormat::FLOAT }, + { GE_CMD_VTCT, "immt", GECmdFormat::FLOAT }, + { GE_CMD_VTCQ, "immq", GECmdFormat::FLOAT }, + { GE_CMD_VCV, "immrgb", GECmdFormat::RGB }, + // TODO: Confirm if any other bits are used? + { GE_CMD_VAP, "imma_prim", GECmdFormat::ALPHA_PRIM }, + // TODO: Confirm it's 8 bit? + { GE_CMD_VFC, "immfog", GECmdFormat::DATA8 }, + { GE_CMD_VSCV, "immrgb1", GECmdFormat::RGB }, + { GE_CMD_UNKNOWN_FA, "unknownfa", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FB, "unknownfb", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FC, "unknownfc", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FD, "unknownfd", GECmdFormat::NONE }, + { GE_CMD_UNKNOWN_FE, "unknownfe", GECmdFormat::NONE }, + { GE_CMD_NOP_FF, "nopff", GECmdFormat::NONE }, +}; + +static constexpr GECmdAlias geCmdAliases[] = { + { GE_CMD_VADDR, { "vertexaddr" } }, + { GE_CMD_IADDR, { "indexaddr" } }, + { GE_CMD_BOUNDINGBOX, { "boundingbox", "boundtest" } }, + { GE_CMD_BJUMP, { "boundjump" } }, + { GE_CMD_BASE, { "baseaddr" } }, + { GE_CMD_VERTEXTYPE, { "vertextype" } }, + { GE_CMD_OFFSETADDR, { "offsetaddr" } }, + { GE_CMD_REGION2, { "region2" } }, + { GE_CMD_LIGHTINGENABLE, { "lightingenable", "lighting" } }, + { GE_CMD_LIGHTENABLE0, { "light0enable" } }, + { GE_CMD_LIGHTENABLE1, { "light1enable" } }, + { GE_CMD_LIGHTENABLE2, { "light2enable" } }, + { GE_CMD_LIGHTENABLE3, { "light3enable" } }, + { GE_CMD_DEPTHCLAMPENABLE, { "zclampenable", "depthclamp_on", "depthclampenable" } }, + { GE_CMD_CULLFACEENABLE, { "cullenable", "cullface_on", "cullfaceenable" } }, + { GE_CMD_TEXTUREMAPENABLE, { "texenable", "texture_on", "textureenable" } }, + { GE_CMD_FOGENABLE, { "fogenable" } }, + { GE_CMD_DITHERENABLE, { "ditherenable" } }, + { GE_CMD_ALPHABLENDENABLE, { "ablendenable", "alphablend_on", "alphablendenable" } }, + { GE_CMD_ALPHABLENDENABLE, { "atestenable", "alphatest_on", "alphatestenable" } }, + { GE_CMD_ZTESTENABLE, { "ztestenable", "depthtest_on", "depthtest_enable" } }, + { GE_CMD_STENCILTESTENABLE, { "stestenable", "stenciltest_on", "stenciltestenable" } }, + { GE_CMD_ANTIALIASENABLE, { "antialiasenable", "antialias" } }, + { GE_CMD_PATCHCULLENABLE, { "patchcullenable" } }, + { GE_CMD_COLORTESTENABLE, { "ctestenable", "colortest_on", "colortestenable" } }, + { GE_CMD_LOGICOPENABLE, { "logicopenable" } }, + { GE_CMD_BONEMATRIXNUMBER, { "bonematrixnum" } }, + { GE_CMD_BONEMATRIXDATA, { "bonematrixdata" } }, + { GE_CMD_MORPHWEIGHT0, { "morphweight0" } }, + { GE_CMD_MORPHWEIGHT1, { "morphweight1" } }, + { GE_CMD_MORPHWEIGHT2, { "morphweight2" } }, + { GE_CMD_MORPHWEIGHT3, { "morphweight3" } }, + { GE_CMD_MORPHWEIGHT4, { "morphweight4" } }, + { GE_CMD_MORPHWEIGHT5, { "morphweight5" } }, + { GE_CMD_MORPHWEIGHT6, { "morphweight6" } }, + { GE_CMD_MORPHWEIGHT7, { "morphweight7" } }, + { GE_CMD_PATCHDIVISION, { "patchdiv" } }, + { GE_CMD_PATCHFACING, { "patchreversenormal" } }, + { GE_CMD_WORLDMATRIXNUMBER, { "worldmatrixnum" } }, + { GE_CMD_WORLDMATRIXDATA, { "worldmatrixdata" } }, + { GE_CMD_VIEWMATRIXNUMBER, { "viewmatrixnum" } }, + { GE_CMD_VIEWMATRIXDATA, { "viewmatrixdata" } }, + { GE_CMD_PROJMATRIXNUMBER, { "projmatrixnum" } }, + { GE_CMD_PROJMATRIXDATA, { "projmatrixdata" } }, + { GE_CMD_TGENMATRIXNUMBER, { "texgenmatrixnum", "tgenmtxnum", "tgenmatrixnum" } }, + { GE_CMD_TGENMATRIXDATA, { "texgenmatrixdata", "tgenmtxdata", "tgenmatrixdata" } }, + { GE_CMD_VIEWPORTXSCALE, { "viewportxscale" } }, + { GE_CMD_VIEWPORTYSCALE, { "viewportyscale" } }, + { GE_CMD_VIEWPORTZSCALE, { "viewportzscale" } }, + { GE_CMD_VIEWPORTXCENTER, { "viewportxcenter" } }, + { GE_CMD_VIEWPORTYCENTER, { "viewportycenter" } }, + { GE_CMD_VIEWPORTZCENTER, { "viewportzcenter" } }, + { GE_CMD_SHADEMODE, { "shademode", "shading" } }, + { GE_CMD_REVERSENORMAL, { "reversenormal" } }, + { GE_CMD_MATERIALAMBIENT, { "materialambientrgb" } }, + { GE_CMD_MATERIALALPHA, { "materialambientalpha" } }, + { GE_CMD_MATERIALSPECULARCOEF, { "materialspecularcoef" } }, + { GE_CMD_AMBIENTCOLOR, { "ambientrgb" } }, + { GE_CMD_AMBIENTALPHA, { "ambientalpha" } }, + { GE_CMD_LIGHTMODE, { "lmode", "secondarycolor" } }, + { GE_CMD_LIGHTTYPE0, { "lighttype0" } }, + { GE_CMD_LIGHTTYPE1, { "lighttype1" } }, + { GE_CMD_LIGHTTYPE2, { "lighttype2" } }, + { GE_CMD_LIGHTTYPE3, { "lighttype3" } }, + { GE_CMD_FRAMEBUFPTR, { "framebufptr" } }, + { GE_CMD_FRAMEBUFWIDTH, { "fbwidth", "framebufstride", "framebufwidth" } }, + { GE_CMD_ZBUFPTR, { "depthbufptr" } }, + { GE_CMD_ZBUFWIDTH, { "zbwidth", "depthbufstride", "depthbufwidth" } }, + { GE_CMD_TEXBUFWIDTH0, { "texbufwidth0", "texstride0" } }, + { GE_CMD_TEXBUFWIDTH1, { "texbufwidth1", "texstride1" } }, + { GE_CMD_TEXBUFWIDTH2, { "texbufwidth2", "texstride2" } }, + { GE_CMD_TEXBUFWIDTH3, { "texbufwidth3", "texstride3" } }, + { GE_CMD_TEXBUFWIDTH4, { "texbufwidth4", "texstride4" } }, + { GE_CMD_TEXBUFWIDTH5, { "texbufwidth5", "texstride5" } }, + { GE_CMD_TEXBUFWIDTH6, { "texbufwidth6", "texstride6" } }, + { GE_CMD_TEXBUFWIDTH7, { "texbufwidth7", "texstride7" } }, + { GE_CMD_CLUTADDRUPPER, { "clutaddrupper" } }, + { GE_CMD_TEXSHADELS, { "texshadels" } }, + { GE_CMD_TEXWRAP, { "texwrap" } }, + { GE_CMD_FOGCOLOR, { "fogrgb" } }, + { GE_CMD_FRAMEBUFPIXFORMAT, { "framebufformat" } }, + { GE_CMD_CLEARMODE, { "clear" } }, + { GE_CMD_SCISSOR1, { "scissortl" } }, + { GE_CMD_SCISSOR2, { "scissorbr" } }, + { GE_CMD_COLORTEST, { "colortestfunc" } }, + { GE_CMD_COLORREF, { "colortestref" } }, + { GE_CMD_COLORTESTMASK, { "colortestmask" } }, + { GE_CMD_ALPHATEST, { "alphatest" } }, + { GE_CMD_STENCILTEST, { "stenciltest" } }, + { GE_CMD_ZTEST, { "depthtest" } }, + { GE_CMD_BLENDFIXEDA, { "blendfixsrc" } }, + { GE_CMD_BLENDFIXEDB, { "blendfixdst" } }, + { GE_CMD_ZWRITEDISABLE, { "depthwrite_off", "zwritedisable", "depthwritedisable" } }, + { GE_CMD_MASKRGB, { "rgbmask" } }, + { GE_CMD_MASKALPHA, { "swritemask", "amask", "amask_block" } }, + { GE_CMD_TRANSFERSTART, { "transferstart" } }, + { GE_CMD_VCV, { "immrgb0" } }, + { GE_CMD_VSCV, { "immsecondaryrgb" } }, +}; + +bool GECmdInfoByName(const char *name, GECmdInfo &result) { + for (const GECmdInfo &info : geCmdInfo) { + if (strcasecmp(info.name, name) == 0) { + result = info; + return true; + } + } + + for (const GECmdAlias &entry : geCmdAliases) { + for (const char *alias : entry.aliases) { + if (alias && strcasecmp(alias, name) == 0) { + result = GECmdInfoByCmd(entry.reg); + return true; + } + } + } + + return false; +} + +GECmdInfo GECmdInfoByCmd(GECommand reg) { + _assert_msg_((reg & 0xFF) == reg, "Invalid reg"); + return geCmdInfo[reg & 0xFF]; +} diff --git a/GPU/Debugger/GECommandTable.h b/GPU/Debugger/GECommandTable.h new file mode 100644 index 0000000000..9abe0f7c6d --- /dev/null +++ b/GPU/Debugger/GECommandTable.h @@ -0,0 +1,79 @@ +// Copyright (c) 2022- PPSSPP Project. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, version 2.0 or later versions. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "GPU/ge_constants.h" + +enum class GECmdFormat { + DATA, // Just regular data. + DATA16, // Data, but only 16 bits of it used. + DATA8, // 8 bits value (alpha, etc.) + NONE, // Should have no arguments or value. + RELATIVE_ADDR, // 24 bits added to base + offset. + PRIM, // 16 bits count, 3 bits type. + BEZIER, // 8 bits ucount, 8 bits vcount. + SPLINE, // 8 bits ucount, 8 bits vcount, 2 bits utype, 2 bits vtype. + JUMP, // Like RELATIVE_ADDR, but lower 2 bits ignored. + SIGNAL, // 16 bits data, 8 bits signal type. + HIGH_ADDR_ONLY, // 16 bits ignored, 8 bits for a high address. + LOW_ADDR_ONLY, // 24 bits low address. + LOW_ADDR, // 24 bits low address. + HIGH_ADDR, // 16 bits ignored, 8 bits for a high address. + VERTEX_TYPE, // 24-bits of vtype flags (complex.) + OFFSET_ADDR, // 24 bits become the high bits of offset. + X10_Y10, // 10 bits X, 10 bits Y. + FLAG, // 1 bit on/off. + BONE_NUM, // 7 bits number. + MATRIX_NUM, // 4 bits number. + FLOAT, // 24 bits float data. + PATCH_DIVISION, // 8 bits divisionu, 8 bits divisionv. + PATCH_PRIM, // 2 bits primitive type. + SUBPIXEL_COORD, // 4 bits subpixel, 12 bits integer value. + MATERIAL_UPDATE, // 3 bits colors to update. + RGB, // 24 bits RGB color. + LIGHT_TYPE, // 8 bits computation (2 bits), 2 bits type. + STRIDE, // 11 bits. + STRIDE_HIGH_ADDR, // 11 bits stride, 5 ignored, 8 bits high address. + TEX_SIZE, // 4 bits width power, 4 bits ignored, 4 bits height power. + TEX_MAP_MODE, // 8 bits mode (2 bits), 2 bits environment factor. + TEX_LIGHT_SRC, // 8 bits lightu (2 bits), 2 bits lightv. + TEX_MODE, // 8 bits swizzle (1 bit), 8 bits separate clut4 (1 bit), 3 bits max level. + TEX_FORMAT, // 4 bits format. + TEX_FILTER, // 3 bits minify mode, 5 bits ignored, 1 bit magnify mode. + TEX_CLAMP, // 1 bit clampu, 7 bits ignored, 1 bit clampv. + TEX_LEVEL_MODE, // 2 bits mode, 15 bits ignored, 4.4 (8 bits) bias. + TEX_FUNC, // 3 bits function, 5 bits ignored, 1 bit use alpha, 7 bits ignored, 1 bit double color. + CLUT_BLOCKS, // 6 bits block count. + CLUT_FORMAT, // 2 bits format, 5 bits shift, 1 bit ignored, 8 bits mask, 5 bits base. + CLEAR_MODE, // 1 bit on, 7 bits ignored, 3 bits aspect. + COLOR_TEST_FUNC, // 2 bits test function. + ALPHA_TEST, // 3 bits function, 5 bits ignored, 8 bits ref, 8 bits mask. + STENCIL_OP, // 8 bits sfail (3 bits), 8 bits zfail (3 bits), 8 bits zpass (3 bits.) + DEPTH_TEST_FUNC, // 3 bits function. + BLEND_MODE, // 4 bits srcfactor, 4 bits dstfactor, 3 bits equation. + DITHER_ROW, // 4 s.3.0 fixed point dither offsets. + LOGIC_OP, // 4 bits logic operation. + ALPHA_PRIM, // 8 bits alpha, 3 bits primitive type. +}; + +struct GECmdInfo { + GECommand reg; + const char *name; + GECmdFormat fmt; +}; + +bool GECmdInfoByName(const char *name, GECmdInfo &info); +GECmdInfo GECmdInfoByCmd(GECommand reg); diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 1f37652321..0480b490d7 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -370,6 +370,7 @@ + @@ -510,6 +511,7 @@ + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index d581cb4bad..bd28a45e97 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -258,6 +258,9 @@ Common + + Debugger + @@ -506,6 +509,9 @@ Common + + Debugger + diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 5b011374ac..f31d31e176 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -407,7 +407,7 @@ struct GPUgstate { float getViewportYCenter() const { return getFloat24(viewportycenter); } float getViewportZCenter() const { return getFloat24(viewportzcenter); } - // Fixed 16 point. + // Fixed 12.4 point. int getOffsetX16() const { return offsetx & 0xFFFF; } int getOffsetY16() const { return offsety & 0xFFFF; } float getOffsetX() const { return (float)getOffsetX16() / 16.0f; } diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj b/UWP/GPU_UWP/GPU_UWP.vcxproj index 277526509c..87aac4d38b 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj @@ -413,6 +413,7 @@ + @@ -475,6 +476,7 @@ + diff --git a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters index 2a797c0d2e..dbce632981 100644 --- a/UWP/GPU_UWP/GPU_UWP.vcxproj.filters +++ b/UWP/GPU_UWP/GPU_UWP.vcxproj.filters @@ -32,6 +32,7 @@ + @@ -89,6 +90,7 @@ + diff --git a/android/jni/Android.mk b/android/jni/Android.mk index f5d8ec375a..b47db9d5cc 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -351,6 +351,7 @@ EXEC_AND_LIB_FILES := \ $(SRC)/GPU/Common/VertexShaderGenerator.cpp \ $(SRC)/GPU/Debugger/Breakpoints.cpp \ $(SRC)/GPU/Debugger/Debugger.cpp \ + $(SRC)/GPU/Debugger/GECommandTable.cpp \ $(SRC)/GPU/Debugger/Playback.cpp \ $(SRC)/GPU/Debugger/Record.cpp \ $(SRC)/GPU/Debugger/Stepping.cpp \ diff --git a/libretro/Makefile.common b/libretro/Makefile.common index ab82fcca28..305c2e2fa6 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -335,6 +335,7 @@ SOURCES_CXX += \ $(COMMONDIR)/Data/Convert/ColorConv.cpp \ $(GPUDIR)/Debugger/Breakpoints.cpp \ $(GPUDIR)/Debugger/Debugger.cpp \ + $(GPUDIR)/Debugger/GECommandTable.cpp \ $(GPUDIR)/Debugger/Playback.cpp \ $(GPUDIR)/Debugger/Record.cpp \ $(GPUDIR)/Debugger/Stepping.cpp \ From 14ef12613713f3c7244849f8ed027b0450434c34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 22:14:24 +0200 Subject: [PATCH 005/110] Correct libretro buildfix (hopefully) --- libretro/Makefile.common | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index ab82fcca28..6f14483b08 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -161,9 +161,6 @@ ifeq ($(PLATFORM_EXT), android) $(EXTDIR)/libzip/zip_source_file_stdio_named.c \ $(EXTDIR)/libzip/zip_random_unix.c endif - - SOURCES_C +=\ - $(COMMONDIR)/Math/fast/fast_matrix.c endif SOURCES_C += $(LIBRETRODIR)/ext/glew/glew.c @@ -311,7 +308,8 @@ SOURCES_CXX += \ $(COMMONDIR)/TimeUtil.cpp SOURCES_C +=\ - $(COMMONDIR)/GPU/OpenGL/gl3stub.c + $(COMMONDIR)/GPU/OpenGL/gl3stub.c \ + $(COMMONDIR)/Math/fast/fast_matrix.c SOURCES_CXX += \ $(GPUCOMMONDIR)/Draw2D.cpp \ @@ -657,8 +655,7 @@ ifeq ($(WITH_DYNAREC),1) SOURCES_C += $(EXTDIR)/libpng17/arm/arm_init.c \ $(EXTDIR)/libpng17/arm/filter_neon_intrinsics.c - ASMFILES += $(COMMONDIR)/Math/fast/fast_matrix_neon.S \ - $(EXTDIR)/libpng17/arm/filter_neon.S + ASMFILES += $(EXTDIR)/libpng17/arm/filter_neon.S endif else ifneq (,$(findstring msvc,$(platform))) From 16212cae73084305969cf7ff126080bf98c2efbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 23:31:30 +0200 Subject: [PATCH 006/110] NFS speed effect: Improve framebuffer choice logging, tighten up stride checks. --- Common/Data/Collections/TinySet.h | 7 ++++ GPU/Common/TextureCacheCommon.cpp | 63 ++++++++++++++++++------------- GPU/Common/TextureCacheCommon.h | 1 + GPU/GPU.h | 2 +- 4 files changed, 45 insertions(+), 28 deletions(-) diff --git a/Common/Data/Collections/TinySet.h b/Common/Data/Collections/TinySet.h index 5c8c8e78e6..1b9933e186 100644 --- a/Common/Data/Collections/TinySet.h +++ b/Common/Data/Collections/TinySet.h @@ -99,6 +99,13 @@ struct TinySet { return slowLookup_->size() + MaxFastSize; } } + T &operator[] (size_t index) { + if (index < MaxFastSize) { + return fastLookup_[index]; + } else { + return (*slowLookup_)[index - MaxFastSize]; + } + } const T &operator[] (size_t index) const { if (index < MaxFastSize) { return fastLookup_[index]; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 87c866fa93..dec7302a9d 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -639,18 +639,7 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en return true; } - if (Reporting::ShouldLogNTimes("multifbcandidate", 5)) { - std::string cands; - for (size_t i = 0; i < candidates.size(); i++) { - cands += candidates[i].ToString() + "\n"; - } - - WARN_LOG(G3D, "GetFramebufferCandidates: Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", - (int)candidates.size(), - entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format), - cands.c_str() - ); - } + bool logging = Reporting::ShouldLogNTimes("multifbcandidate", 5); // OK, multiple possible candidates. Will need to figure out which one is the most relevant. int bestRelevancy = -1; @@ -660,7 +649,7 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en // We simply use the sequence counter as relevancy nowadays. for (size_t i = 0; i < candidates.size(); i++) { - const AttachCandidate &candidate = candidates[i]; + AttachCandidate &candidate = candidates[i]; int relevancy = candidate.channel == RASTER_COLOR ? candidate.fb->colorBindSeq : candidate.fb->depthBindSeq; // Add a small negative penalty if the texture is currently bound as a framebuffer, and offset is not zero. @@ -678,13 +667,36 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en continue; } + if (logging) { + candidate.relevancy = relevancy; + } + if (relevancy > bestRelevancy) { bestRelevancy = relevancy; bestIndex = i; } } + if (logging) { + std::string cands; + for (size_t i = 0; i < candidates.size(); i++) { + cands += candidates[i].ToString(); + if (i != candidates.size() - 1) + cands += "\n"; + } + + WARN_LOG(G3D, "GetFramebufferCandidates: Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s", + (int)candidates.size(), + entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format), + cands.c_str() + ); + logging = true; + } + if (bestIndex != -1) { + if (logging) { + WARN_LOG(G3D, "Chose candidate %d:\n%s\n", bestIndex, candidates[bestIndex].ToString().c_str()); + } *bestCandidate = candidates[bestIndex]; return true; } else { @@ -878,6 +890,9 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format); + uint32_t tex_stride_in_bytes = entry.bufw * textureBitsPerPixel[entry.format] / 8; // Note, we're looking up bits here so need to divide by 8. + u32 addr = fb_address & 0x3FFFFFFF; u32 texaddr = entry.addr + texaddrOffset; @@ -897,7 +912,7 @@ bool TextureCacheCommon::MatchFramebuffer( } const bool noOffset = texaddr == addr; - const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR; + const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes; const u32 w = 1 << ((entry.dim >> 0) & 0xf); const u32 h = 1 << ((entry.dim >> 8) & 0xf); @@ -906,9 +921,8 @@ bool TextureCacheCommon::MatchFramebuffer( // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { - // TODO: Better checks for compatible strides here. - if (fb_stride != entry.bufw) { - WARN_LOG_ONCE(diffStrides1, G3D, "Found matching framebuffer at %08x with different strides %d != %d", fb_address, entry.bufw, (int)fb_stride); + if (fb_stride_in_bytes != tex_stride_in_bytes && TextureFormatMatchesBufferFormat(entry.format, fb_format)) { + WARN_LOG_ONCE(diffStrides1, G3D, "Found exact-matching framebuffer at %08x with different byte strides %d != %d", fb_address, tex_stride_in_bytes, fb_stride_in_bytes); } // NOTE: This check is okay because the first texture formats are the same as the buffer formats. if (IsTextureFormatBufferCompatible(entry.format)) { @@ -957,15 +971,9 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } - if (fb_stride != entry.bufw) { - if (noOffset) { - WARN_LOG_ONCE(diffStrides2, G3D, "Matching framebuffer(matching_clut = %s) different strides %d != %d", matchingClutFormat ? "yes" : "no", entry.bufw, fb_stride); - // Continue on with other checks. - // Not actually sure why we even try here. There's no way it'll go well if the strides are different. - } else { - // Assume any render-to-tex with different bufw + offset is a render from ram. - return false; - } + if (fb_stride_in_bytes != tex_stride_in_bytes) { + // Probably irrelevant. + return false; } // Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.) @@ -2247,9 +2255,10 @@ void TextureCacheCommon::ClearNextFrame() { } std::string AttachCandidate::ToString() const { - return StringFromFormat("[%s seq:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]", + return StringFromFormat("[%s seq:%d rel:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]", this->channel == RASTER_COLOR ? "COLOR" : "DEPTH", this->channel == RASTER_COLOR ? this->fb->colorBindSeq : this->fb->depthBindSeq, + this->relevancy, this->fb->fb_address, this->fb->fb_stride, GeBufferFormatToString(this->fb->fb_format), this->fb->z_address, this->fb->z_stride, this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false"); diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 7cb79d44ce..82c79773a3 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -218,6 +218,7 @@ struct AttachCandidate { VirtualFramebuffer *fb; FramebufferMatchInfo match; RasterChannel channel; + int relevancy; std::string ToString() const; }; diff --git a/GPU/GPU.h b/GPU/GPU.h index 93f81fb67c..ddf9c36fc4 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -27,7 +27,7 @@ class GraphicsContext; // PSP rasterization has two outputs, color and depth. Stencil is packed // into the alpha channel of color (if exists), so possibly RASTER_COLOR // should be named RASTER_COLOR_STENCIL but it gets kinda hard to read. -enum RasterChannel { +enum RasterChannel : uint8_t { RASTER_COLOR = 0, RASTER_DEPTH = 1, }; From e69bb4f61652b21f5324b84e69994f330ce6b3c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 5 Sep 2022 23:40:43 +0200 Subject: [PATCH 007/110] Buildfix, warn fixes while at it --- GPU/Common/TextureCacheCommon.cpp | 11 ++++++++--- GPU/GPU.h | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index dec7302a9d..fda38c70f6 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -695,7 +695,7 @@ bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &en if (bestIndex != -1) { if (logging) { - WARN_LOG(G3D, "Chose candidate %d:\n%s\n", bestIndex, candidates[bestIndex].ToString().c_str()); + WARN_LOG(G3D, "Chose candidate %d:\n%s\n", (int)bestIndex, candidates[bestIndex].ToString().c_str()); } *bestCandidate = candidates[bestIndex]; return true; @@ -888,6 +888,7 @@ bool TextureCacheCommon::MatchFramebuffer( case GE_TFMT_DXT3: case GE_TFMT_DXT5: return false; + default: break; } uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format); @@ -1868,9 +1869,10 @@ static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferForma return true; } break; + default: + WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); + return false; } - WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); - return false; } else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) { // We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491). return true; @@ -1899,6 +1901,9 @@ static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebuffe return gstate.getClutIndexMask() == 0x1F; } break; + default: + // No uses for the other formats yet, add if needed. + break; } } return false; diff --git a/GPU/GPU.h b/GPU/GPU.h index ddf9c36fc4..5410fb43d5 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -19,6 +19,7 @@ #pragma once #include +#include class GPUInterface; class GPUDebugInterface; From 9a6c1d84c23ca7ecd7ab20976c477e3a393f7d2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 6 Sep 2022 00:39:10 +0200 Subject: [PATCH 008/110] Remove impossible check --- GPU/Common/TextureCacheCommon.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index fda38c70f6..85e2427423 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -922,9 +922,6 @@ bool TextureCacheCommon::MatchFramebuffer( // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { - if (fb_stride_in_bytes != tex_stride_in_bytes && TextureFormatMatchesBufferFormat(entry.format, fb_format)) { - WARN_LOG_ONCE(diffStrides1, G3D, "Found exact-matching framebuffer at %08x with different byte strides %d != %d", fb_address, tex_stride_in_bytes, fb_stride_in_bytes); - } // NOTE: This check is okay because the first texture formats are the same as the buffer formats. if (IsTextureFormatBufferCompatible(entry.format)) { if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) { From f595299fe535c266c08a34263a228ef7f83dfff8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 12:16:20 -0700 Subject: [PATCH 009/110] GE Debugger: Allow expressions for goto address. --- Common/Math/expression_parser.cpp | 3 +- GPU/Common/GPUDebugInterface.cpp | 229 ++++++++++++++++++++- GPU/Common/GPUDebugInterface.h | 7 +- Windows/GEDebugger/CtrlDisplayListView.cpp | 22 +- 4 files changed, 251 insertions(+), 10 deletions(-) diff --git a/Common/Math/expression_parser.cpp b/Common/Math/expression_parser.cpp index 1b9ed7ba90..970c9c4a20 100644 --- a/Common/Math/expression_parser.cpp +++ b/Common/Math/expression_parser.cpp @@ -580,8 +580,7 @@ bool parsePostfixExpression(PostfixExpression& exp, IExpressionFunctions* funcs, return true; } -bool parseExpression(char* exp, IExpressionFunctions* funcs, uint32_t& dest) -{ +bool parseExpression(const char *exp, IExpressionFunctions *funcs, uint32_t &dest) { PostfixExpression postfix; if (initPostfixExpression(exp,funcs,postfix) == false) return false; return parsePostfixExpression(postfix,funcs,dest); diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index e4ce10ea44..d1e0098e44 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -15,7 +15,234 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#include "GPUDebugInterface.h" +#include "Common/Log.h" +#include "Common/Math/expression_parser.h" +#include "Core/Debugger/SymbolMap.h" +#include "GPU/Common/GPUDebugInterface.h" +#include "GPU/Debugger/GECommandTable.h" +#include "GPU/GPUState.h" + +enum class GEReferenceIndex : uint32_t { + VADDR = 0x100, + IADDR, + OFFSET, + PC, + STALL, + BFLAG, + + BONE_MATRIX = 0x200, + WORLD_MATRIX = 0x260, + VIEW_MATRIX = 0x26C, + PROJ_MATRIX = 0x278, + TGEN_MATRIX = 0x288, + MATRIX_END = 0x294, +}; +ENUM_CLASS_BITOPS(GEReferenceIndex); + +struct ReferenceName { + GEReferenceIndex index; + const char *name; +}; + +static constexpr ReferenceName referenceNames[] = { + { GEReferenceIndex::VADDR, "vaddr" }, + { GEReferenceIndex::IADDR, "iaddr" }, + { GEReferenceIndex::OFFSET, "offset" }, + { GEReferenceIndex::PC, "pc" }, + { GEReferenceIndex::STALL, "stall" }, + { GEReferenceIndex::BFLAG, "bflag" }, + { GEReferenceIndex::BFLAG, "boundflag" }, +}; + +class GEExpressionFunctions : public IExpressionFunctions { +public: + GEExpressionFunctions(GPUDebugInterface *gpu) : gpu_(gpu) {} + + bool parseReference(char *str, uint32_t &referenceIndex) override; + bool parseSymbol(char *str, uint32_t &symbolValue) override; + uint32_t getReferenceValue(uint32_t referenceIndex) override; + ExpressionType getReferenceType(uint32_t referenceIndex) override; + bool getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) override; + +private: + GPUDebugInterface *gpu_; +}; + +bool GEExpressionFunctions::parseReference(char *str, uint32_t &referenceIndex) { + // TODO: Support formats and a form of fields (i.e. vtype.throughmode.) + // For now, let's just support the register bits directly. + GECmdInfo info; + if (GECmdInfoByName(str, info)) { + referenceIndex = info.reg; + return true; + } + + // Also allow non-register references. + for (const auto &entry : referenceNames) { + if (strcasecmp(str, entry.name) == 0) { + referenceIndex = (uint32_t)entry.index; + return true; + } + } + + // And matrix data. Maybe should allow column/row specification. + int subindex = -1; + int len = -1; + + if (sscanf(str, "bone%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 96) { + referenceIndex = (uint32_t)GEReferenceIndex::BONE_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "world%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::WORLD_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "view%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::VIEW_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "proj%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 16) { + referenceIndex = (uint32_t)GEReferenceIndex::PROJ_MATRIX + subindex; + return true; + } + } + if (sscanf(str, "tgen%i%n", &subindex, &len) == 1 || sscanf(str, "texgen%i%n", &subindex, &len) == 1) { + if (len == strlen(str) && subindex < 12) { + referenceIndex = (uint32_t)GEReferenceIndex::TGEN_MATRIX + subindex; + return true; + } + } + + return false; +} + +bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { + // Mainly useful for checking memory addresses. + return g_symbolMap->GetLabelValue(str, symbolValue); +} + +uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { + if (referenceIndex < 0x100) { + uint32_t value = gpu_->GetGState().cmdmem[referenceIndex]; + // TODO: Later, support float values and similar. + return value & 0x00FFFFFF; + } + + // We return the matrix value as float bits, which gets interpreted correctly in the parser. + if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) { + GPUgstate state = gpu_->GetGState(); + float value; + if (referenceIndex >= (uint32_t)GEReferenceIndex::TGEN_MATRIX) { + value = state.tgenMatrix[referenceIndex - (uint32_t)GEReferenceIndex::TGEN_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::PROJ_MATRIX) { + value = state.projMatrix[referenceIndex - (uint32_t)GEReferenceIndex::PROJ_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::VIEW_MATRIX) { + value = state.viewMatrix[referenceIndex - (uint32_t)GEReferenceIndex::VIEW_MATRIX]; + } else if (referenceIndex >= (uint32_t)GEReferenceIndex::WORLD_MATRIX) { + value = state.worldMatrix[referenceIndex - (uint32_t)GEReferenceIndex::WORLD_MATRIX]; + } else { + value = state.boneMatrix[referenceIndex - (uint32_t)GEReferenceIndex::BONE_MATRIX]; + } + + uint32_t result; + memcpy(&result, &value, sizeof(result)); + return result; + } + + GEReferenceIndex ref = (GEReferenceIndex)referenceIndex; + DisplayList list; + switch (ref) { + case GEReferenceIndex::VADDR: + return gpu_->GetVertexAddress(); + case GEReferenceIndex::IADDR: + return gpu_->GetIndexAddress(); + case GEReferenceIndex::OFFSET: + // TODO: Should use an interface method, probably. + return gstate_c.offsetAddr; + case GEReferenceIndex::PC: + if (gpu_->GetCurrentDisplayList(list)) { + return list.pc; + } + return 0; + case GEReferenceIndex::STALL: + if (gpu_->GetCurrentDisplayList(list)) { + return list.stall; + } + return 0; + case GEReferenceIndex::BFLAG: + if (gpu_->GetCurrentDisplayList(list)) { + return list.bboxResult ? 1 : 0; + } + return 0; + + case GEReferenceIndex::BONE_MATRIX: + case GEReferenceIndex::WORLD_MATRIX: + case GEReferenceIndex::VIEW_MATRIX: + case GEReferenceIndex::PROJ_MATRIX: + case GEReferenceIndex::TGEN_MATRIX: + case GEReferenceIndex::MATRIX_END: + // Shouldn't have gotten here. + break; + } + + _assert_msg_(false, "Invalid reference index"); + return 0; +} + +ExpressionType GEExpressionFunctions::getReferenceType(uint32_t referenceIndex) { + if (referenceIndex < 0x100) { + // TODO: Later, support float values and similar. + return EXPR_TYPE_UINT; + } + + if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) + return EXPR_TYPE_FLOAT; + return EXPR_TYPE_UINT; +} + +bool GEExpressionFunctions::getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) { + if (!Memory::IsValidRange(address, size)) { + sprintf(error, "Invalid address or size %08x + %d", address, size); + return false; + } + + switch (size) { + case 1: + dest = Memory::Read_U8(address); + return true; + case 2: + dest = Memory::Read_U16(address); + return true; + case 4: + dest = Memory::Read_U32(address); + return true; + } + + sprintf(error, "Unexpected memory access size %d", size); + return false; +} + +bool GPUDebugInitExpression(GPUDebugInterface *g, const char *str, PostfixExpression &exp) { + GEExpressionFunctions funcs(g); + return initPostfixExpression(str, &funcs, exp); +} + +bool GPUDebugExecExpression(GPUDebugInterface *g, PostfixExpression &exp, uint32_t &result) { + GEExpressionFunctions funcs(g); + return parsePostfixExpression(exp, &funcs, result); +} + +bool GPUDebugExecExpression(GPUDebugInterface *g, const char *str, uint32_t &result) { + GEExpressionFunctions funcs(g); + return parseExpression(str, &funcs, result); +} void GPUDebugBuffer::Allocate(u32 stride, u32 height, GEBufferFormat fmt, bool flipped, bool reversed) { GPUDebugBufferFormat actualFmt = GPUDebugBufferFormat(fmt); diff --git a/GPU/Common/GPUDebugInterface.h b/GPU/Common/GPUDebugInterface.h index 97e97c9ea3..09254ddf53 100644 --- a/GPU/Common/GPUDebugInterface.h +++ b/GPU/Common/GPUDebugInterface.h @@ -20,9 +20,10 @@ #include #include +#include "Common/Math/expression_parser.h" +#include "Core/MemMap.h" #include "GPU/GPU.h" #include "GPU/GPUInterface.h" -#include "Core/MemMap.h" struct GPUDebugOp { u32 pc; @@ -251,3 +252,7 @@ public: // get content of specific framebuffer / texture? // vertex / texture decoding? }; + +bool GPUDebugInitExpression(GPUDebugInterface *g, const char *str, PostfixExpression &exp); +bool GPUDebugExecExpression(GPUDebugInterface *g, PostfixExpression &exp, uint32_t &result); +bool GPUDebugExecExpression(GPUDebugInterface *g, const char *str, uint32_t &result); diff --git a/Windows/GEDebugger/CtrlDisplayListView.cpp b/Windows/GEDebugger/CtrlDisplayListView.cpp index 6b521c4996..1152e4f126 100644 --- a/Windows/GEDebugger/CtrlDisplayListView.cpp +++ b/Windows/GEDebugger/CtrlDisplayListView.cpp @@ -1,5 +1,7 @@ #include #include +#include "Common/Data/Encoding/Utf8.h" +#include "Common/StringUtils.h" #include "Common/System/Display.h" #include "Windows/GEDebugger/CtrlDisplayListView.h" #include "Windows/GEDebugger/GEDebugger.h" @@ -369,15 +371,23 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) break; case ID_GEDBG_GOTOADDR: { - u32 newAddress = curAddress; - if (!InputBox_GetHex(GetModuleHandle(NULL), wnd, L"Address", curAddress, newAddress)) { + std::string expression = StringFromFormat("%08x", curAddress); + if (!InputBox_GetString(GetModuleHandle(NULL), wnd, L"Address", expression, expression, true)) { break; } - if (Memory::IsValidAddress(newAddress)) { - setCurAddress(newAddress); - scrollAddressIntoView(); - redraw(); + uint32_t newAddress = curAddress; + if (!GPUDebugExecExpression(gpuDebug, expression.c_str(), newAddress)) { + MessageBox(wnd, ConvertUTF8ToWString(getExpressionError()).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); + break; } + if (!Memory::IsValidAddress(newAddress)) { + MessageBox(wnd, L"Address not in valid memory", L"Invalid address", MB_OK | MB_ICONEXCLAMATION); + break; + } + + setCurAddress(newAddress); + scrollAddressIntoView(); + redraw(); } break; } From 0b30b723bb0d30c61ad0fef24a9059f79aee6fe1 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 13:13:09 -0700 Subject: [PATCH 010/110] GE Debugger: Add address breakpoint conditions. --- GPU/Debugger/Breakpoints.cpp | 73 ++++++++++++++++++++-- GPU/Debugger/Breakpoints.h | 3 + Windows/GEDebugger/CtrlDisplayListView.cpp | 17 +++++ Windows/GEDebugger/CtrlDisplayListView.h | 2 + Windows/GEDebugger/GEDebugger.cpp | 10 ++- Windows/ppsspp.rc | 1 + Windows/resource.h | 3 +- 7 files changed, 102 insertions(+), 7 deletions(-) diff --git a/GPU/Debugger/Breakpoints.cpp b/GPU/Debugger/Breakpoints.cpp index 162ec6743a..d661c69043 100644 --- a/GPU/Debugger/Breakpoints.cpp +++ b/GPU/Debugger/Breakpoints.cpp @@ -16,19 +16,28 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include +#include #include #include #include #include "Common/CommonFuncs.h" +#include "Common/Math/expression_parser.h" +#include "GPU/Common/GPUDebugInterface.h" #include "GPU/Debugger/Breakpoints.h" #include "GPU/GPUState.h" namespace GPUBreakpoints { +struct BreakpointInfo { + bool isConditional; + PostfixExpression expression; + std::string expressionString; +}; + static std::mutex breaksLock; static bool breakCmds[256]; -static std::set breakPCs; +static std::map breakPCs; static std::set breakTextures; static std::set breakRenderTargets; // Small optimization to avoid a lock/lookup for the common case. @@ -158,8 +167,26 @@ bool IsRenderTargetCmdBreakpoint(u32 op) { return false; } +static bool HitAddressBreakpoint(u32 pc) { + if (breakPCsCount == 0) + return false; + + std::lock_guard guard(breaksLock); + auto entry = breakPCs.find(pc); + if (entry == breakPCs.end()) + return false; + + if (entry->second.isConditional) { + u32 result = 1; + if (!GPUDebugExecExpression(gpuDebug, breakPCs[pc].expression, result)) + return false; + return result != 0; + } + return true; +} + bool IsBreakpoint(u32 pc, u32 op) { - if (IsAddressBreakpoint(pc) || IsOpBreakpoint(op)) { + if (HitAddressBreakpoint(pc) || IsOpBreakpoint(op)) { return true; } @@ -275,13 +302,13 @@ void AddAddressBreakpoint(u32 addr, bool temp) { if (temp) { if (breakPCs.find(addr) == breakPCs.end()) { breakPCsTemp.insert(addr); - breakPCs.insert(addr); + breakPCs[addr].isConditional = false; } // Already normal breakpoint, let's not make it temporary. } else { // Remove the temporary marking. breakPCsTemp.erase(addr); - breakPCs.insert(addr); + breakPCs[addr].isConditional = false; } breakPCsCount = breakPCs.size(); @@ -398,6 +425,44 @@ void RemoveTextureChangeTempBreakpoint() { notifyBreakpoints(HasAnyBreakpoints()); } +static bool SetupCond(BreakpointInfo &bp, const std::string &expression, std::string *error) { + bool success = true; + if (expression.length() != 0) { + if (GPUDebugInitExpression(gpuDebug, expression.c_str(), bp.expression)) { + bp.isConditional = true; + bp.expressionString = expression; + } else { + bp.isConditional = false; + if (error) + *error = getExpressionError(); + success = false; + } + } else { + bp.isConditional = false; + } + return success; +} + +bool SetAddressBreakpointCond(u32 addr, const std::string &expression, std::string *error) { + // Must have one in the first place, make sure it's not temporary. + AddAddressBreakpoint(addr); + + std::lock_guard guard(breaksLock); + auto &bp = breakPCs[addr]; + return SetupCond(breakPCs[addr], expression, error); +} + +bool GetAddressBreakpointCond(u32 addr, std::string *expression) { + std::lock_guard guard(breaksLock); + auto entry = breakPCs.find(addr); + if (entry != breakPCs.end() && entry->second.isConditional) { + if (expression) + *expression = entry->second.expressionString; + return true; + } + return false; +} + void UpdateLastTexture(u32 addr) { lastTexture = addr; } diff --git a/GPU/Debugger/Breakpoints.h b/GPU/Debugger/Breakpoints.h index fd55476643..fbe4bd88fc 100644 --- a/GPU/Debugger/Breakpoints.h +++ b/GPU/Debugger/Breakpoints.h @@ -47,6 +47,9 @@ namespace GPUBreakpoints { void RemoveTextureChangeTempBreakpoint(); void RemoveRenderTargetBreakpoint(u32 addr); + bool SetAddressBreakpointCond(u32 addr, const std::string &expression, std::string *error); + bool GetAddressBreakpointCond(u32 addr, std::string *expression); + void UpdateLastTexture(u32 addr); void ClearAllBreakpoints(); diff --git a/Windows/GEDebugger/CtrlDisplayListView.cpp b/Windows/GEDebugger/CtrlDisplayListView.cpp index 1152e4f126..eaaa8577f8 100644 --- a/Windows/GEDebugger/CtrlDisplayListView.cpp +++ b/Windows/GEDebugger/CtrlDisplayListView.cpp @@ -267,6 +267,17 @@ void CtrlDisplayListView::toggleBreakpoint() SendMessage(GetParent(wnd),WM_GEDBG_TOGGLEPCBREAKPOINT,curAddress,0); } +void CtrlDisplayListView::PromptBreakpointCond() { + std::string expression; + GPUBreakpoints::GetAddressBreakpointCond(curAddress, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), wnd, L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetAddressBreakpointCond(curAddress, expression, &error)) + MessageBox(wnd, ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); +} + void CtrlDisplayListView::onMouseDown(WPARAM wParam, LPARAM lParam, int button) { int y = HIWORD(lParam); @@ -298,6 +309,9 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) { if (button == 2) { + HMENU menu = GetContextMenu(ContextMenuID::DISPLAYLISTVIEW); + EnableMenuItem(menu, ID_GEDBG_SETCOND, GPUBreakpoints::IsAddressBreakpoint(curAddress) ? MF_ENABLED : MF_GRAYED); + switch (TriggerContextMenu(ContextMenuID::DISPLAYLISTVIEW, wnd, ContextPoint::FromEvent(lParam))) { case ID_DISASM_GOTOINMEMORYVIEW: @@ -308,6 +322,9 @@ void CtrlDisplayListView::onMouseUp(WPARAM wParam, LPARAM lParam, int button) toggleBreakpoint(); redraw(); break; + case ID_GEDBG_SETCOND: + PromptBreakpointCond(); + break; case ID_DISASM_COPYINSTRUCTIONDISASM: { int space = 256 * (selectRangeEnd - selectRangeStart) / instructionSize; diff --git a/Windows/GEDebugger/CtrlDisplayListView.h b/Windows/GEDebugger/CtrlDisplayListView.h index fe605f799e..28adfdd371 100644 --- a/Windows/GEDebugger/CtrlDisplayListView.h +++ b/Windows/GEDebugger/CtrlDisplayListView.h @@ -30,6 +30,8 @@ class CtrlDisplayListView } pixelPositions; void toggleBreakpoint(); + void PromptBreakpointCond(); + public: CtrlDisplayListView(HWND _wnd); ~CtrlDisplayListView(); diff --git a/Windows/GEDebugger/GEDebugger.cpp b/Windows/GEDebugger/GEDebugger.cpp index 7c78dcf80e..62026e6f07 100644 --- a/Windows/GEDebugger/GEDebugger.cpp +++ b/Windows/GEDebugger/GEDebugger.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include "Common/CommonWindows.h" #include #include "Common/Data/Convert/ColorConv.h" @@ -1114,7 +1114,13 @@ BOOL CGEDebugger::DlgProc(UINT message, WPARAM wParam, LPARAM lParam) { bool temp; bool isBreak = IsAddressBreakpoint(pc, temp); if (isBreak && !temp) { - RemoveAddressBreakpoint(pc); + if (GetAddressBreakpointCond(pc, nullptr)) { + int ret = MessageBox(m_hDlg, L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + if (ret == IDYES) + RemoveAddressBreakpoint(pc); + } else { + RemoveAddressBreakpoint(pc); + } } else { AddAddressBreakpoint(pc); } diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 3bc7dfed34..d44f5556a3 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -763,6 +763,7 @@ BEGIN MENUITEM "Jump to Cursor", ID_DISASM_SETPCTOHERE MENUITEM "Set Stall", ID_GEDBG_SETSTALLADDR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND MENUITEM SEPARATOR MENUITEM "Go to Displaylist PC", ID_GEDBG_GOTOPC MENUITEM "Go to Address...", ID_GEDBG_GOTOADDR diff --git a/Windows/resource.h b/Windows/resource.h index 13104152e9..9ba6bc7946 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -332,6 +332,7 @@ #define ID_GEDBG_SHOWONRIGHT 40220 #define ID_GEDBG_SHOWONTOPRIGHT 40221 #define IDC_GEDBG_STEPVSYNC 40222 +#define ID_GEDBG_SETCOND 40223 // Dummy option to let the buffered rendering hotkey cycle through all the options. @@ -345,7 +346,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 256 -#define _APS_NEXT_COMMAND_VALUE 40223 +#define _APS_NEXT_COMMAND_VALUE 40224 #define _APS_NEXT_CONTROL_VALUE 1202 #define _APS_NEXT_SYMED_VALUE 101 #endif From f14e49a373dc07f65836d4da2adf56bf9645026f Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 16:46:16 -0700 Subject: [PATCH 011/110] GE Debugger: Add conditions to cmd breakpoints. --- GPU/Common/GPUDebugInterface.cpp | 15 ++++++++ GPU/Debugger/Breakpoints.cpp | 54 ++++++++++++++++++++++++---- GPU/Debugger/Breakpoints.h | 2 ++ Windows/GEDebugger/TabState.cpp | 45 ++++++++++++++++++++--- Windows/GEDebugger/TabState.h | 1 + Windows/GEDebugger/TabVertices.cpp | 58 +++++++++++++++++++++++------- Windows/GEDebugger/TabVertices.h | 1 + Windows/ppsspp.rc | 2 ++ 8 files changed, 155 insertions(+), 23 deletions(-) diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index d1e0098e44..d5d9c564db 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -29,6 +29,8 @@ enum class GEReferenceIndex : uint32_t { PC, STALL, BFLAG, + OP, + DATA, BONE_MATRIX = 0x200, WORLD_MATRIX = 0x260, @@ -52,6 +54,8 @@ static constexpr ReferenceName referenceNames[] = { { GEReferenceIndex::STALL, "stall" }, { GEReferenceIndex::BFLAG, "bflag" }, { GEReferenceIndex::BFLAG, "boundflag" }, + { GEReferenceIndex::OP, "op" }, + { GEReferenceIndex::DATA, "data" }, }; class GEExpressionFunctions : public IExpressionFunctions { @@ -181,6 +185,17 @@ uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { return list.bboxResult ? 1 : 0; } return 0; + case GEReferenceIndex::OP: + // TODO: Support fields under this as per the cmd format? + if (gpu_->GetCurrentDisplayList(list)) { + return Memory::Read_U32(list.pc); + } + return 0; + case GEReferenceIndex::DATA: + if (gpu_->GetCurrentDisplayList(list)) { + return Memory::Read_U32(list.pc) & 0x00FFFFFF; + } + return 0; case GEReferenceIndex::BONE_MATRIX: case GEReferenceIndex::WORLD_MATRIX: diff --git a/GPU/Debugger/Breakpoints.cpp b/GPU/Debugger/Breakpoints.cpp index d661c69043..8d76cbd5e7 100644 --- a/GPU/Debugger/Breakpoints.cpp +++ b/GPU/Debugger/Breakpoints.cpp @@ -16,9 +16,9 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include -#include #include #include +#include #include #include "Common/CommonFuncs.h" @@ -30,14 +30,15 @@ namespace GPUBreakpoints { struct BreakpointInfo { - bool isConditional; + bool isConditional = false; PostfixExpression expression; std::string expressionString; }; static std::mutex breaksLock; static bool breakCmds[256]; -static std::map breakPCs; +static BreakpointInfo breakCmdsInfo[256]; +static std::unordered_map breakPCs; static std::set breakTextures; static std::set breakRenderTargets; // Small optimization to avoid a lock/lookup for the common case. @@ -185,8 +186,24 @@ static bool HitAddressBreakpoint(u32 pc) { return true; } +static bool HitOpBreakpoint(u32 op) { + u8 cmd = op >> 24; + if (!IsCmdBreakpoint(cmd)) + return false; + + if (breakCmdsInfo[cmd].isConditional) { + std::lock_guard guard(breaksLock); + u32 result = 1; + if (!GPUDebugExecExpression(gpuDebug, breakCmdsInfo[cmd].expression, result)) + return false; + return result != 0; + } + + return true; +} + bool IsBreakpoint(u32 pc, u32 op) { - if (HitAddressBreakpoint(pc) || IsOpBreakpoint(op)) { + if (HitAddressBreakpoint(pc) || HitOpBreakpoint(op)) { return true; } @@ -308,7 +325,7 @@ void AddAddressBreakpoint(u32 addr, bool temp) { } else { // Remove the temporary marking. breakPCsTemp.erase(addr); - breakPCs[addr].isConditional = false; + breakPCs.insert(std::make_pair(addr, BreakpointInfo{})); } breakPCsCount = breakPCs.size(); @@ -320,12 +337,16 @@ void AddCmdBreakpoint(u8 cmd, bool temp) { if (!breakCmds[cmd]) { breakCmdsTemp[cmd] = true; breakCmds[cmd] = true; + breakCmdsInfo[cmd].isConditional = false; } // Ignore adding a temp breakpoint when a normal one exists. } else { // This is no longer temporary. breakCmdsTemp[cmd] = false; - breakCmds[cmd] = true; + if (!breakCmds[cmd]) { + breakCmds[cmd] = true; + breakCmdsInfo[cmd].isConditional = false; + } } notifyBreakpoints(true); } @@ -432,7 +453,7 @@ static bool SetupCond(BreakpointInfo &bp, const std::string &expression, std::st bp.isConditional = true; bp.expressionString = expression; } else { - bp.isConditional = false; + // Don't change if it failed. if (error) *error = getExpressionError(); success = false; @@ -463,6 +484,25 @@ bool GetAddressBreakpointCond(u32 addr, std::string *expression) { return false; } +bool SetCmdBreakpointCond(u8 cmd, const std::string &expression, std::string *error) { + // Must have one in the first place, make sure it's not temporary. + AddCmdBreakpoint(cmd); + + std::lock_guard guard(breaksLock); + return SetupCond(breakCmdsInfo[cmd], expression, error); +} + +bool GetCmdBreakpointCond(u8 cmd, std::string *expression) { + if (breakCmds[cmd] && breakCmdsInfo[cmd].isConditional) { + if (expression) { + std::lock_guard guard(breaksLock); + *expression = breakCmdsInfo[cmd].expressionString; + } + return true; + } + return false; +} + void UpdateLastTexture(u32 addr) { lastTexture = addr; } diff --git a/GPU/Debugger/Breakpoints.h b/GPU/Debugger/Breakpoints.h index fbe4bd88fc..0910a68e92 100644 --- a/GPU/Debugger/Breakpoints.h +++ b/GPU/Debugger/Breakpoints.h @@ -49,6 +49,8 @@ namespace GPUBreakpoints { bool SetAddressBreakpointCond(u32 addr, const std::string &expression, std::string *error); bool GetAddressBreakpointCond(u32 addr, std::string *expression); + bool SetCmdBreakpointCond(u8 cmd, const std::string &expression, std::string *error); + bool GetCmdBreakpointCond(u8 cmd, std::string *expression); void UpdateLastTexture(u32 addr); diff --git a/Windows/GEDebugger/TabState.cpp b/Windows/GEDebugger/TabState.cpp index 9d6735aabd..5ad864ed3f 100644 --- a/Windows/GEDebugger/TabState.cpp +++ b/Windows/GEDebugger/TabState.cpp @@ -18,8 +18,9 @@ #include #include "Common/CommonFuncs.h" #include "Common/CommonTypes.h" -#include "Common/Log.h" +#include "Common/Data/Encoding/Utf8.h" #include "Common/Data/Text/Parsers.h" +#include "Common/Log.h" #include "Common/StringUtils.h" #include "Windows/resource.h" #include "Windows/InputBox.h" @@ -900,7 +901,13 @@ void CtrlStateValues::OnDoubleClick(int row, int column) { const auto info = rows_[row]; if (column == STATEVALUES_COL_BREAKPOINT) { - SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + bool proceed = true; + if (IsCmdBreakpoint(info.cmd)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + proceed = ret == IDYES; + } + if (proceed) + SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); return; } @@ -960,6 +967,7 @@ void CtrlStateValues::OnRightClick(int row, int column, const POINT &point) { HMENU subMenu = GetContextMenu(ContextMenuID::GEDBG_STATE); SetMenuDefaultItem(subMenu, ID_REGLIST_CHANGE, FALSE); + EnableMenuItem(subMenu, ID_GEDBG_SETCOND, GPUBreakpoints::IsCmdBreakpoint(info.cmd) ? MF_ENABLED : MF_GRAYED); // Ehh, kinda ugly. if (!watchList.empty() && rows_ == &watchList[0]) { @@ -975,8 +983,19 @@ void CtrlStateValues::OnRightClick(int row, int column, const POINT &point) { switch (TriggerContextMenu(ContextMenuID::GEDBG_STATE, GetHandle(), ContextPoint::FromClient(point))) { - case ID_DISASM_TOGGLEBREAKPOINT: - SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + case ID_DISASM_TOGGLEBREAKPOINT: { + bool proceed = true; + if (IsCmdBreakpoint(info.cmd)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + proceed = ret == IDYES; + } + if (proceed) + SetItemState(row, ToggleBreakpoint(info) ? 1 : 0); + break; + } + + case ID_GEDBG_SETCOND: + PromptBreakpointCond(info); break; case ID_DISASM_COPYINSTRUCTIONHEX: { @@ -1043,6 +1062,24 @@ bool CtrlStateValues::RowValuesChanged(int row) { return false; } +void CtrlStateValues::PromptBreakpointCond(const TabStateRow &info) { + std::string expression; + GPUBreakpoints::GetCmdBreakpointCond(info.cmd, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), GetHandle(), L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetCmdBreakpointCond(info.cmd, expression, &error)) { + MessageBox(GetHandle(), ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); + } else { + if (info.otherCmd) + GPUBreakpoints::SetCmdBreakpointCond(info.otherCmd, expression, &error); + if (info.otherCmd2) + GPUBreakpoints::SetCmdBreakpointCond(info.otherCmd2, expression, &error); + } + +} + TabStateValues::TabStateValues(const TabStateRow *rows, int rowCount, LPCSTR dialogID, HINSTANCE _hInstance, HWND _hParent) : Dialog(dialogID, _hInstance, _hParent) { values = new CtrlStateValues(rows, rowCount, GetDlgItem(m_hDlg, IDC_GEDBG_VALUES)); diff --git a/Windows/GEDebugger/TabState.h b/Windows/GEDebugger/TabState.h index dbc1558fa0..6992af14be 100644 --- a/Windows/GEDebugger/TabState.h +++ b/Windows/GEDebugger/TabState.h @@ -47,6 +47,7 @@ protected: private: bool RowValuesChanged(int row); void SetCmdValue(u32 op); + void PromptBreakpointCond(const TabStateRow &info); const TabStateRow *rows_; int rowCount_; diff --git a/Windows/GEDebugger/TabVertices.cpp b/Windows/GEDebugger/TabVertices.cpp index 0576b96032..9606672840 100644 --- a/Windows/GEDebugger/TabVertices.cpp +++ b/Windows/GEDebugger/TabVertices.cpp @@ -17,6 +17,7 @@ #include #include "Common/CommonTypes.h" +#include "Common/Data/Encoding/Utf8.h" #include "Common/StringUtils.h" #include "Core/System.h" #include "Windows/resource.h" @@ -550,23 +551,50 @@ static constexpr MatrixCmdPair matrixCmds[] = { { MATRIXLIST_ROW_COUNT, GE_CMD_NOP }, }; -void CtrlMatrixList::ToggleBreakpoint(int row) { +static const MatrixCmdPair *FindCmdPair(int row) { for (int i = 0; i < ARRAY_SIZE(matrixCmds) - 1; ++i) { if (row < matrixCmds[i].row || row >= matrixCmds[i + 1].row) continue; - // Okay, this command is in range. Toggle the actual breakpoint. - auto &info = matrixCmds[i]; - bool state = !GPUBreakpoints::IsCmdBreakpoint(info.cmd); - if (state) - GPUBreakpoints::AddCmdBreakpoint(info.cmd); - else - GPUBreakpoints::RemoveCmdBreakpoint(info.cmd); - - for (int r = matrixCmds[i].row; r < matrixCmds[i + 1].row; ++r) { - SetItemState(r, state ? 1 : 0); - } + return &matrixCmds[i]; } + return nullptr; +} + +void CtrlMatrixList::ToggleBreakpoint(int row) { + const MatrixCmdPair *info = FindCmdPair(row); + if (!info) + return; + + // Okay, this command is in range. Toggle the actual breakpoint. + bool state = !GPUBreakpoints::IsCmdBreakpoint(info->cmd); + if (state) { + GPUBreakpoints::AddCmdBreakpoint(info->cmd); + } else { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + if (ret != IDYES) + return; + GPUBreakpoints::RemoveCmdBreakpoint(info->cmd); + } + + for (int r = info->row; r < (info + 1)->row; ++r) { + SetItemState(r, state ? 1 : 0); + } +} + +void CtrlMatrixList::PromptBreakpointCond(int row) { + const MatrixCmdPair *info = FindCmdPair(row); + if (!info) + return; + + std::string expression; + GPUBreakpoints::GetCmdBreakpointCond(info->cmd, &expression); + if (!InputBox_GetString(GetModuleHandle(NULL), GetHandle(), L"Expression", expression, expression)) + return; + + std::string error; + if (!GPUBreakpoints::SetCmdBreakpointCond(info->cmd, expression, &error)) + MessageBox(GetHandle(), ConvertUTF8ToWString(error).c_str(), L"Invalid expression", MB_OK | MB_ICONEXCLAMATION); } void CtrlMatrixList::OnDoubleClick(int row, int column) { @@ -624,18 +652,24 @@ void CtrlMatrixList::OnDoubleClick(int row, int column) { void CtrlMatrixList::OnRightClick(int row, int column, const POINT &point) { if (row >= GetRowCount()) return; + const MatrixCmdPair *info = FindCmdPair(row); POINT screenPt(point); ClientToScreen(GetHandle(), &screenPt); HMENU subMenu = GetContextMenu(ContextMenuID::GEDBG_MATRIX); SetMenuDefaultItem(subMenu, ID_REGLIST_CHANGE, FALSE); + EnableMenuItem(subMenu, ID_GEDBG_SETCOND, info && GPUBreakpoints::IsCmdBreakpoint(info->cmd) ? MF_ENABLED : MF_GRAYED); switch (TriggerContextMenu(ContextMenuID::GEDBG_MATRIX, GetHandle(), ContextPoint::FromClient(point))) { case ID_DISASM_TOGGLEBREAKPOINT: ToggleBreakpoint(row); break; + case ID_GEDBG_SETCOND: + PromptBreakpointCond(row); + break; + case ID_DISASM_COPYINSTRUCTIONDISASM: { float val; diff --git a/Windows/GEDebugger/TabVertices.h b/Windows/GEDebugger/TabVertices.h index 116f60f06c..0a1f48be0c 100644 --- a/Windows/GEDebugger/TabVertices.h +++ b/Windows/GEDebugger/TabVertices.h @@ -90,6 +90,7 @@ private: bool GetValue(const GPUgstate &state, int row, int col, float &val); bool ColChanged(const GPUgstate &lastState, const GPUgstate &state, int row, int col); void ToggleBreakpoint(int row); + void PromptBreakpointCond(int row); }; class TabMatrices : public Dialog { diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index d44f5556a3..9ffc1747f7 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -778,6 +778,7 @@ BEGIN MENUITEM "Copy Entire Tab (Formatted)",ID_GEDBG_COPYALL MENUITEM SEPARATOR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND MENUITEM "Add Watch", ID_GEDBG_WATCH END POPUP "gepreviewoptions" @@ -793,6 +794,7 @@ BEGIN MENUITEM "Copy Entire Tab (Formatted)",ID_GEDBG_COPYALL MENUITEM SEPARATOR MENUITEM "Toggle Breakpoint", ID_DISASM_TOGGLEBREAKPOINT + MENUITEM "Set Breakpoint Condition", ID_GEDBG_SETCOND END POPUP "getaboptions" BEGIN From 14d45c2e77e1b3028f50bc83ff850a2d2d970563 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 17:43:05 -0700 Subject: [PATCH 012/110] Build: Include all zstd files in libretro. This was previously commented out, and was intentionally changed in zstd so you could use a different xxhash. --- libretro/Makefile.common | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index 6f14483b08..de7c09c4a6 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -775,11 +775,8 @@ SOURCES_C += $(ZSTDDIR)/common/debug.c \ $(ZSTDDIR)/common/error_private.c \ $(ZSTDDIR)/common/fse_decompress.c \ $(ZSTDDIR)/common/pool.c \ - $(ZSTDDIR)/common/threading.c - -#SOURCES_C += $(ZSTDDIR)/common/xxhash.c - -SOURCES_C += \ + $(ZSTDDIR)/common/threading.c \ + $(ZSTDDIR)/common/xxhash.c \ $(ZSTDDIR)/common/zstd_common.c \ $(ZSTDDIR)/compress/fse_compress.c \ $(ZSTDDIR)/compress/hist.c \ From 1d5c90d3707406a5712b07e7075f75e277b13e0a Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 19:37:58 -0700 Subject: [PATCH 013/110] Ge: Read matrix num/data back like hardware. In case any game accidentally relies on this. --- Core/HLE/sceGe.cpp | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/Core/HLE/sceGe.cpp b/Core/HLE/sceGe.cpp index 46230373d2..81667a448e 100644 --- a/Core/HLE/sceGe.cpp +++ b/Core/HLE/sceGe.cpp @@ -565,8 +565,32 @@ static int sceGeGetMtx(int type, u32 matrixPtr) { static u32 sceGeGetCmd(int cmd) { if (cmd >= 0 && cmd < (int)ARRAY_SIZE(gstate.cmdmem)) { - // Does not mask away the high bits. - return hleLogSuccessInfoX(SCEGE, gstate.cmdmem[cmd]); + // Does not mask away the high bits. But matrix regs don't read back. + u32 val = gstate.cmdmem[cmd]; + switch (cmd) { + case GE_CMD_BONEMATRIXDATA: + case GE_CMD_WORLDMATRIXDATA: + case GE_CMD_VIEWMATRIXDATA: + case GE_CMD_PROJMATRIXDATA: + case GE_CMD_TGENMATRIXDATA: + val &= 0xFF000000; + break; + + case GE_CMD_BONEMATRIXNUMBER: + val &= 0xFF00007F; + break; + + case GE_CMD_WORLDMATRIXNUMBER: + case GE_CMD_VIEWMATRIXNUMBER: + case GE_CMD_PROJMATRIXNUMBER: + case GE_CMD_TGENMATRIXNUMBER: + val &= 0xFF00000F; + break; + + default: + break; + } + return hleLogSuccessInfoX(SCEGE, val); } return hleLogError(SCEGE, SCE_KERNEL_ERROR_INVALID_INDEX); } From 23f61171f9967853535feab088a554b3a9a3043d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 19:38:54 -0700 Subject: [PATCH 014/110] softgpu: Implement matrix data wrap-around. Overflow writes to other matrices. Matches hardware tests. --- GPU/GPUCommon.cpp | 5 +++++ GPU/Software/SoftGpu.cpp | 46 +++++++++++++++++++++++++++++----------- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 4da5fd2983..534a813459 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2143,6 +2143,7 @@ void GPUCommon::Execute_WorldMtxData(u32 op, u32 diff) { } num++; gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); + gstate.worldmtxdata = GE_CMD_WORLDMATRIXDATA << 24; } void GPUCommon::Execute_ViewMtxNum(u32 op, u32 diff) { @@ -2190,6 +2191,7 @@ void GPUCommon::Execute_ViewMtxData(u32 op, u32 diff) { } num++; gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); + gstate.viewmtxdata = GE_CMD_VIEWMATRIXDATA << 24; } void GPUCommon::Execute_ProjMtxNum(u32 op, u32 diff) { @@ -2238,6 +2240,7 @@ void GPUCommon::Execute_ProjMtxData(u32 op, u32 diff) { num++; if (num <= 16) gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxdata = GE_CMD_PROJMATRIXDATA << 24; } void GPUCommon::Execute_TgenMtxNum(u32 op, u32 diff) { @@ -2285,6 +2288,7 @@ void GPUCommon::Execute_TgenMtxData(u32 op, u32 diff) { } num++; gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); + gstate.texmtxdata = GE_CMD_TGENMATRIXDATA << 24; } void GPUCommon::Execute_BoneMtxNum(u32 op, u32 diff) { @@ -2356,6 +2360,7 @@ void GPUCommon::Execute_BoneMtxData(u32 op, u32 diff) { } num++; gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); + gstate.boneMatrixData = GE_CMD_BONEMATRIXDATA << 24; } void GPUCommon::Execute_MorphWeight(u32 op, u32 diff) { diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 8c26eac9b1..7b93e52c6f 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -1033,57 +1033,79 @@ void SoftGPU::Execute_VertexType(u32 op, u32 diff) { void SoftGPU::Execute_WorldMtxData(u32 op, u32 diff) { int num = gstate.worldmtxnum & 0xF; + u32 *target = num < 12 ? (u32 *)&gstate.worldMatrix[num] : (u32 *)&gstate.viewMatrix[num - 12]; u32 newVal = op << 8; - if (num < 12 && newVal != ((const u32 *)gstate.worldMatrix)[num]) { - ((u32 *)gstate.worldMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.worldmtxnum = (GE_CMD_WORLDMATRIXNUMBER << 24) | (num & 0xF); + gstate.worldmtxdata = GE_CMD_WORLDMATRIXDATA << 24; } void SoftGPU::Execute_ViewMtxData(u32 op, u32 diff) { int num = gstate.viewmtxnum & 0xF; + u32 *target = num < 12 ? (u32 *)&gstate.viewMatrix[num] : (u32 *)&gstate.projMatrix[num - 12]; u32 newVal = op << 8; - if (num < 12 && newVal != ((const u32 *)gstate.viewMatrix)[num]) { - ((u32 *)gstate.viewMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.viewmtxnum = (GE_CMD_VIEWMATRIXNUMBER << 24) | (num & 0xF); + gstate.viewmtxdata = GE_CMD_VIEWMATRIXDATA << 24; } void SoftGPU::Execute_ProjMtxData(u32 op, u32 diff) { - // NOTE: Changed from 0xF to catch overflows. - int num = gstate.projmtxnum & 0x1F; + int num = gstate.projmtxnum & 0xF; + u32 *target = (u32 *)&gstate.projMatrix[num]; u32 newVal = op << 8; - if (num < 0x10 && newVal != ((const u32 *)gstate.projMatrix)[num]) { - ((u32 *)gstate.projMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; - if (num <= 16) - gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxnum = (GE_CMD_PROJMATRIXNUMBER << 24) | (num & 0xF); + gstate.projmtxdata = GE_CMD_PROJMATRIXDATA << 24; } void SoftGPU::Execute_TgenMtxData(u32 op, u32 diff) { int num = gstate.texmtxnum & 0xF; u32 newVal = op << 8; + // Doesn't wrap to any other matrix. if (num < 12 && newVal != ((const u32 *)gstate.tgenMatrix)[num]) { ((u32 *)gstate.tgenMatrix)[num] = newVal; + // No dirtying, read during vertex read. } num++; gstate.texmtxnum = (GE_CMD_TGENMATRIXNUMBER << 24) | (num & 0xF); + gstate.texmtxdata = GE_CMD_TGENMATRIXDATA << 24; } void SoftGPU::Execute_BoneMtxData(u32 op, u32 diff) { int num = gstate.boneMatrixNumber & 0x7F; + u32 *target; + if (num < 96) { + target = (u32 *)&gstate.boneMatrix[num]; + } else if (num < 96 + 12) { + target = (u32 *)&gstate.worldMatrix[num - 96]; + } else if (num < 96 + 12 + 12) { + target = (u32 *)&gstate.viewMatrix[num - 96 - 12]; + } else { + target = (u32 *)&gstate.projMatrix[num - 96 - 12 - 12]; + } + u32 newVal = op << 8; - if (num < 96 && newVal != ((const u32 *)gstate.boneMatrix)[num]) { - ((u32 *)gstate.boneMatrix)[num] = newVal; + if (newVal != *target) { + *target = newVal; + // Dirty if it overflowed. We read bone data during vertex read. + if (num >= 96) + dirtyFlags_ |= SoftDirty::TRANSFORM_MATRIX; } num++; gstate.boneMatrixNumber = (GE_CMD_BONEMATRIXNUMBER << 24) | (num & 0x7F); + gstate.boneMatrixData = GE_CMD_BONEMATRIXDATA << 24; } void SoftGPU::Execute_Call(u32 op, u32 diff) { From a59d39d666ee2221e7798383f60d13782549b047 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 20:35:08 -0700 Subject: [PATCH 015/110] GE Debugger: Add more missing GE disasm. Need to investigate the immediate vert bits more. --- GPU/GeDisasm.cpp | 106 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 91 insertions(+), 15 deletions(-) diff --git a/GPU/GeDisasm.cpp b/GPU/GeDisasm.cpp index 4f4bdb0efd..c3098f5706 100644 --- a/GPU/GeDisasm.cpp +++ b/GPU/GeDisasm.cpp @@ -94,6 +94,17 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { u32 cmd = op >> 24; u32 data = op & 0xFFFFFF; + static constexpr char *primTypes[8] = { + "POINTS", + "LINES", + "LINE_STRIP", + "TRIANGLES", + "TRIANGLE_STRIP", + "TRIANGLE_FAN", + "RECTANGLES", + "CONTINUE_PREVIOUS", + }; + // Handle control and drawing commands here directly. The others we delegate. switch (cmd) { @@ -132,20 +143,10 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { { u32 count = data & 0xFFFF; u32 type = (data >> 16) & 7; - static const char* types[8] = { - "POINTS", - "LINES", - "LINE_STRIP", - "TRIANGLES", - "TRIANGLE_STRIP", - "TRIANGLE_FAN", - "RECTANGLES", - "CONTINUE_PREVIOUS", - }; if (gstate.vertType & GE_VTYPE_IDX_MASK) - snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x, iaddr= %08x", type < 7 ? types[type] : "INVALID", count, gstate_c.vertexAddr, gstate_c.indexAddr); + snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x, iaddr= %08x", type < 7 ? primTypes[type] : "INVALID", count, gstate_c.vertexAddr, gstate_c.indexAddr); else - snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x", type < 7 ? types[type] : "INVALID", count, gstate_c.vertexAddr); + snprintf(buffer, bufsize, "DRAW PRIM %s: count= %i vaddr= %08x", type < 7 ? primTypes[type] : "INVALID", count, gstate_c.vertexAddr); } break; @@ -347,11 +348,17 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { break; case GE_CMD_OFFSETX: - snprintf(buffer, bufsize, "Offset X: %i", data); + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Offset X: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Offset X: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); break; case GE_CMD_OFFSETY: - snprintf(buffer, bufsize, "Offset Y: %i", data); + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Offset Y: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Offset Y: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); break; case GE_CMD_TEXSCALEU: @@ -736,6 +743,20 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { } break; + case GE_CMD_LKS0: + case GE_CMD_LKS1: + case GE_CMD_LKS2: + case GE_CMD_LKS3: + snprintf(buffer, bufsize, "Light %d spot exponent: %f", cmd - GE_CMD_LKS0, getFloat24(data)); + break; + + case GE_CMD_LKO0: + case GE_CMD_LKO1: + case GE_CMD_LKO2: + case GE_CMD_LKO3: + snprintf(buffer, bufsize, "Light %d spot cutoff: %f", cmd - GE_CMD_LKO0, getFloat24(data)); + break; + case GE_CMD_LAC0:case GE_CMD_LAC1:case GE_CMD_LAC2:case GE_CMD_LAC3: case GE_CMD_LDC0:case GE_CMD_LDC1:case GE_CMD_LDC2:case GE_CMD_LDC3: case GE_CMD_LSC0:case GE_CMD_LSC1:case GE_CMD_LSC2:case GE_CMD_LSC3: @@ -744,9 +765,15 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { float g = (float)((data>>8) & 0xff)/255.0f; float b = (float)(data>>16)/255.0f; + static constexpr char *lightColorTypes[] = { + "ambient", + "diffuse", + "specular", + }; + int l = (cmd - GE_CMD_LAC0) / 3; int t = (cmd - GE_CMD_LAC0) % 3; - snprintf(buffer, bufsize, "Light %i color %i: %f %f %f", l, t, r, g, b); + snprintf(buffer, bufsize, "Light %d %s color: %f %f %f", l, lightColorTypes[t], r, g, b); } break; @@ -1289,6 +1316,55 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { snprintf(buffer, bufsize, "BONE data # %f", getFloat24(data)); break; + case GE_CMD_VSCX: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex screen X: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex screen X: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); + break; + + case GE_CMD_VSCY: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex screen Y: %04x / %d with sub %d (extra %02x)", data & 0xFFFF, data >> 4, data & 0xF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex screen Y: %04x / %d with sub %d", data & 0xFFFF, data >> 4, data & 0xF); + break; + + case GE_CMD_VSCZ: + if (data & ~0xFFFF) + snprintf(buffer, bufsize, "Vertex Z: %04x (extra %02x)", data & 0xFFFF, data >> 16); + else + snprintf(buffer, bufsize, "Vertex Z: %04x", data & 0xFFFF); + break; + + case GE_CMD_VTCS: + snprintf(buffer, bufsize, "Vertex tex S: %f", getFloat24(data)); + break; + + case GE_CMD_VTCT: + snprintf(buffer, bufsize, "Vertex tex T: %f", getFloat24(data)); + break; + + case GE_CMD_VTCQ: + snprintf(buffer, bufsize, "Vertex tex Q: %f", getFloat24(data)); + break; + + case GE_CMD_VCV: + snprintf(buffer, bufsize, "Vertex color: %06x", data); + break; + + case GE_CMD_VAP: + snprintf(buffer, bufsize, "Vertex draw: alpha=%02x, prim=%s, other=%06x", data & 0xFF, primTypes[(data >> 8) & 7], data & ~0x0007FF); + break; + + case GE_CMD_VFC: + snprintf(buffer, bufsize, "Vertex fog: %06x", data); + break; + + case GE_CMD_VSCV: + snprintf(buffer, bufsize, "Vertex secondary color: %06x", data); + break; + default: snprintf(buffer, bufsize, "Unknown: %08x", op); break; From 02c03216bf51443e6b7c32b94d3aae55d4bc96d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 6 Sep 2022 11:50:01 +0200 Subject: [PATCH 016/110] Add Lubos to credits list --- UI/MiscScreens.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/UI/MiscScreens.cpp b/UI/MiscScreens.cpp index f7e22a8f78..2d94bd2ffb 100644 --- a/UI/MiscScreens.cpp +++ b/UI/MiscScreens.cpp @@ -968,6 +968,7 @@ void CreditsScreen::render() { "ANR2ME", "adenovan", "iota97", + "Lubos", "", cr->T("specialthanks", "Special thanks to:"), specialthanksMaxim.c_str(), From 62ed43633c3d13d49d87463f69c890cc61c98735 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 07:44:08 -0700 Subject: [PATCH 017/110] d3d9: Correct decode of 16-bit textures. Was causing crashes since we assumed this func could handle non-replaced formats. --- GPU/D3D11/TextureCacheD3D11.cpp | 10 +++++++++- GPU/Directx9/TextureCacheDX9.cpp | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 5cc42adee6..2563825ea1 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -59,7 +59,15 @@ static const D3D11_INPUT_ELEMENT_DESC g_QuadVertexElements[] = { Draw::DataFormat FromD3D11Format(u32 fmt) { switch (fmt) { - case DXGI_FORMAT_B8G8R8A8_UNORM: default: return Draw::DataFormat::R8G8B8A8_UNORM; + case DXGI_FORMAT_B4G4R4A4_UNORM: + return Draw::DataFormat::A4R4G4B4_UNORM_PACK16; + case DXGI_FORMAT_B5G5R5A1_UNORM: + return Draw::DataFormat::A1R5G5B5_UNORM_PACK16; + case DXGI_FORMAT_B5G6R5_UNORM: + return Draw::DataFormat::R5G6B5_UNORM_PACK16; + case DXGI_FORMAT_B8G8R8A8_UNORM: + default: + return Draw::DataFormat::R8G8B8A8_UNORM; } } diff --git a/GPU/Directx9/TextureCacheDX9.cpp b/GPU/Directx9/TextureCacheDX9.cpp index 289d52d3b7..3a06c3b4f5 100644 --- a/GPU/Directx9/TextureCacheDX9.cpp +++ b/GPU/Directx9/TextureCacheDX9.cpp @@ -41,7 +41,15 @@ Draw::DataFormat FromD3D9Format(u32 fmt) { switch (fmt) { - case D3DFMT_A8R8G8B8: default: return Draw::DataFormat::R8G8B8A8_UNORM; + case D3DFMT_A4R4G4B4: + return Draw::DataFormat::B4G4R4A4_UNORM_PACK16; + case D3DFMT_A1R5G5B5: + return Draw::DataFormat::A1R5G5B5_UNORM_PACK16; + case D3DFMT_R5G6B5: + return Draw::DataFormat::R5G6B5_UNORM_PACK16; + case D3DFMT_A8R8G8B8: + default: + return Draw::DataFormat::R8G8B8A8_UNORM; } } From 35157e8762a03b4def00b3094ddf6b9c76f698fe Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 18:48:33 -0700 Subject: [PATCH 018/110] Build: Add additional zstd file for libretro. --- libretro/Makefile.common | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index de7c09c4a6..2d1322f83a 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -800,6 +800,10 @@ SOURCES_C += $(ZSTDDIR)/common/debug.c \ $(ZSTDDIR)/dictBuilder/fastcover.c \ $(ZSTDDIR)/dictBuilder/zdict.c +ifeq ($(TARGET_ARCH),x86_64) +SOURCES_C += $(ZSTDDIR)/decompress/huf_decompress_amd64.S +endif + ifneq ($(STATIC_LINKING), 1) SOURCES_C += \ $(EXTDIR)/zlib/adler32.c \ From 7c8f8817b87c7e28fb8ff510d8935500bf95566d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 18:52:20 -0700 Subject: [PATCH 019/110] GPU: Fix CanDepalettize() missing false paths. Mismatched texformats didn't have a return. --- GPU/Common/TextureCacheCommon.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 85e2427423..36c34e20a4 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1873,9 +1873,8 @@ static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferForma } else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) { // We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491). return true; - } else { - return false; } + return false; } // If the palette is detected as a smooth ramp, we can interpolate for higher color precision. From b4e1f6d902c5ed19f5bab3804e6be4e6b30671e0 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 18:54:52 -0700 Subject: [PATCH 020/110] GPU: Fix crash on overlap copy w/o cur target. --- GPU/Common/FramebufferManagerCommon.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index d907f1ac2f..3cbe6543f0 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -810,7 +810,7 @@ void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFra } } - if (dst != currentRenderVfb_ && tookActions) { + if (currentRenderVfb_ && dst != currentRenderVfb_ && tookActions) { // Will probably just change the name of the current renderpass, since one was started by the reinterpret itself. draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "After Reinterpret"); } From d249674858ab20ebb38dc12ff1d4aa13eb83b285 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 22:38:21 -0700 Subject: [PATCH 021/110] softgpu: Fix immediate rendering crash. --- GPU/GPUCommon.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 534a813459..fa59e485cc 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2410,7 +2410,8 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { void GPUCommon::FlushImm() { SetDrawType(DRAW_PRIM, immPrim_); - framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); + if (framebufferManager_) + framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // No idea how many cycles to skip, heh. return; From 531c7e452d82a94050110457932c9d496e948e20 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 22:45:01 -0700 Subject: [PATCH 022/110] GE Debugger: Count imm prims as prims. --- GPU/Debugger/Debugger.cpp | 3 ++- Windows/GEDebugger/TabState.cpp | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/GPU/Debugger/Debugger.cpp b/GPU/Debugger/Debugger.cpp index 439c763e8e..fb88fdca2f 100644 --- a/GPU/Debugger/Debugger.cpp +++ b/GPU/Debugger/Debugger.cpp @@ -73,6 +73,7 @@ void SetBreakNext(BreakNext next) { GPUBreakpoints::AddCmdBreakpoint(GE_CMD_PRIM, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_BEZIER, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_SPLINE, true); + GPUBreakpoints::AddCmdBreakpoint(GE_CMD_VAP, true); } else if (next == BreakNext::CURVE) { GPUBreakpoints::AddCmdBreakpoint(GE_CMD_BEZIER, true); GPUBreakpoints::AddCmdBreakpoint(GE_CMD_SPLINE, true); @@ -111,7 +112,7 @@ bool NotifyCommand(u32 pc) { } bool process = true; - if (cmd == GE_CMD_PRIM || cmd == GE_CMD_BEZIER || cmd == GE_CMD_SPLINE) { + if (cmd == GE_CMD_PRIM || cmd == GE_CMD_BEZIER || cmd == GE_CMD_SPLINE || cmd == GE_CMD_VAP) { primsThisFrame++; if (!restrictPrimRanges.empty()) { diff --git a/Windows/GEDebugger/TabState.cpp b/Windows/GEDebugger/TabState.cpp index 5ad864ed3f..da1baa10bf 100644 --- a/Windows/GEDebugger/TabState.cpp +++ b/Windows/GEDebugger/TabState.cpp @@ -266,6 +266,14 @@ static const TabStateRow stateSettingsRows[] = { { L"Dither 1", GE_CMD_DITH1, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, { L"Dither 2", GE_CMD_DITH2, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, { L"Dither 3", GE_CMD_DITH3, CMD_FMT_HEX, GE_CMD_DITHERENABLE }, + { L"Imm vertex XY", GE_CMD_VSCX, CMD_FMT_F16_XY, 0, GE_CMD_VSCY }, + { L"Imm vertex Z", GE_CMD_VSCZ, CMD_FMT_HEX }, + { L"Imm vertex tex STQ", GE_CMD_VTCS, CMD_FMT_XYZ, 0, GE_CMD_VTCT, GE_CMD_VTCQ }, + { L"Imm vertex color0", GE_CMD_VCV, CMD_FMT_HEX }, + { L"Imm vertex color1", GE_CMD_VSCV, CMD_FMT_HEX }, + { L"Imm vertex fog", GE_CMD_VFC, CMD_FMT_HEX }, + // TODO: Format? + { L"Imm vertex prim", GE_CMD_VAP, CMD_FMT_HEX }, }; // TODO: Commands not present in the above lists (some because they don't have meaningful values...): From ceb2af369c3c90435bf58e2d8dfe77d58589c817 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 22:45:34 -0700 Subject: [PATCH 023/110] GPU: Handle immediate prims more accurately. This allows for lines, points, textures, and similar things. Also corrects offset handling. Still some flags on VAP that seemingly don't work, and this doesn't consider the texture flag on it. --- GPU/GPUCommon.cpp | 44 ++++++++++++++++++++++++++++++---------- GPU/GPUCommon.h | 4 ++-- GPU/Software/SoftGpu.cpp | 1 + 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index fa59e485cc..a4e765ea03 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1530,6 +1530,7 @@ void GPUCommon::Execute_End(u32 op, u32 diff) { break; default: + FlushImm(); currentList->subIntrToken = prev & 0xFFFF; UpdateState(GPUSTATE_DONE); // Since we marked done, we have to restore the context now before the next list runs. @@ -1651,6 +1652,7 @@ void GPUCommon::Execute_Prim(u32 op, u32 diff) { u32 count = data & 0xFFFF; if (count == 0) return; + FlushImm(); // Upper bits are ignored. GEPrimitiveType prim = static_cast((data >> 16) & 7); @@ -2379,13 +2381,25 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { return; } + int prim = (op >> 8) & 0x7; + if (prim != GE_PRIM_KEEP_PREVIOUS) { + // Flush before changing the prim type. Only continue can be used to continue a prim. + FlushImm(); + } + TransformedVertex &v = immBuffer_[immCount_++]; - // Formula deduced from ThrillVille's clear. - int offsetX = gstate.getOffsetX16(); - int offsetY = gstate.getOffsetY16(); - v.x = ((gstate.imm_vscx & 0xFFFFFF) - offsetX) / 16.0f; - v.y = ((gstate.imm_vscy & 0xFFFFFF) - offsetY) / 16.0f; + // ThrillVille does a clear with this, additional parameters found via tests. + // The current vtype affects how the coordinate is processed. + if (gstate.isModeThrough()) { + v.x = ((int)(gstate.imm_vscx & 0xFFFF) - 0x8000) / 16.0f; + v.y = ((int)(gstate.imm_vscy & 0xFFFF) - 0x8000) / 16.0f; + } else { + int offsetX = gstate.getOffsetX16(); + int offsetY = gstate.getOffsetY16(); + v.x = ((int)(gstate.imm_vscx & 0xFFFF) - offsetX) / 16.0f; + v.y = ((int)(gstate.imm_vscy & 0xFFFF) - offsetY) / 16.0f; + } v.z = gstate.imm_vscz & 0xFFFF; v.pos_w = 1.0f; v.u = getFloat24(gstate.imm_vtcs); @@ -2394,26 +2408,29 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { v.color0_32 = (gstate.imm_cv & 0xFFFFFF) | (gstate.imm_ap << 24); v.fog = 0.0f; // we have no information about the scale here v.color1_32 = gstate.imm_scv & 0xFFFFFF; - int prim = (op >> 8) & 0x7; if (prim != GE_PRIM_KEEP_PREVIOUS) { immPrim_ = (GEPrimitiveType)prim; - } else if (prim == GE_PRIM_KEEP_PREVIOUS && immCount_ == 2) { + } else if (prim == GE_PRIM_KEEP_PREVIOUS && immPrim_ != GE_PRIM_INVALID) { + static constexpr int flushPrimCount[] = { 1, 2, 0, 3, 0, 0, 2, 0 }; // Instead of finding a proper point to flush, we just emit a full rectangle every time one // is finished. - FlushImm(); - // Need to reset immCount_ here. If we do it in FlushImm it could get skipped by gstate_c.skipDrawReason. - immCount_ = 0; + if (immCount_ == flushPrimCount[immPrim_ & 7]) + FlushImm(); } else { ERROR_LOG_REPORT_ONCE(imm_draw_prim, G3D, "Immediate draw: Unexpected primitive %d at count %d", prim, immCount_); } } void GPUCommon::FlushImm() { + if (immCount_ == 0 || immPrim_ == GE_PRIM_INVALID) + return; + SetDrawType(DRAW_PRIM, immPrim_); if (framebufferManager_) framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason); if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // No idea how many cycles to skip, heh. + immCount_ = 0; return; } UpdateUVScaleOffset(); @@ -2423,23 +2440,28 @@ void GPUCommon::FlushImm() { // through vertices. // Since the only known use is Thrillville and it only uses it to clear, we just use color and pos. struct ImmVertex { + float uv[2]; uint32_t color; float xyz[3]; }; ImmVertex temp[MAX_IMMBUFFER_SIZE]; for (int i = 0; i < immCount_; i++) { + // Since we're sending through, scale back up to w/h. + temp[i].uv[0] = immBuffer_[i].u * gstate.getTextureWidth(0); + temp[i].uv[1] = immBuffer_[i].v * gstate.getTextureHeight(0); temp[i].color = immBuffer_[i].color0_32; temp[i].xyz[0] = immBuffer_[i].pos[0]; temp[i].xyz[1] = immBuffer_[i].pos[1]; temp[i].xyz[2] = immBuffer_[i].pos[2]; } - int vtype = GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; + int vtype = GE_VTYPE_TC_FLOAT | GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; int bytesRead; uint32_t vertTypeID = GetVertTypeID(vtype, 0); drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, gstate.getCullMode(), &bytesRead); // TOOD: In the future, make a special path for these. // drawEngineCommon_->DispatchSubmitImm(immBuffer_, immCount_); + immCount_ = 0; } void GPUCommon::ExecuteOp(u32 op, u32 diff) { diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index f389b788e2..f2c64d95b8 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -286,6 +286,7 @@ protected: void UpdatePC(u32 currentPC, u32 newPC); void UpdateState(GPURunState state); void FastLoadBoneMatrix(u32 target); + void FlushImm(); // TODO: Unify this. virtual void FinishDeferred() {} @@ -352,13 +353,12 @@ protected: TransformedVertex immBuffer_[MAX_IMMBUFFER_SIZE]; int immCount_ = 0; - GEPrimitiveType immPrim_; + GEPrimitiveType immPrim_ = GE_PRIM_INVALID; std::string reportingPrimaryInfo_; std::string reportingFullInfo_; private: - void FlushImm(); void CheckDepthUsage(VirtualFramebuffer *vfb); void DoBlockTransfer(u32 skipDrawReason); void DoExecuteCall(u32 target); diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 7b93e52c6f..a6fc160af3 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -831,6 +831,7 @@ void SoftGPU::Execute_Prim(u32 op, u32 diff) { GEPrimitiveType prim = static_cast((op >> 16) & 7); if (count == 0) return; + FlushImm(); if (!Memory::IsValidAddress(gstate_c.vertexAddr)) { ERROR_LOG_REPORT(G3D, "Software: Bad vertex address %08x!", gstate_c.vertexAddr); From f27426714306e07f33b9ff588e2e63062fdae222 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 5 Sep 2022 23:13:16 -0700 Subject: [PATCH 024/110] GPU: Allow usage of texturing in immediate verts. And respect the other flags that I can reproduce working in a test. I can't seem to get the fog to work at all, or the shading mode, or the secondary color. Maybe depends on other flags or bits in other regs... --- GPU/GPUCommon.cpp | 34 +++++++++++++++++++++++++++++++++- GPU/GPUCommon.h | 1 + GPU/Software/TransformUnit.cpp | 4 +++- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index a4e765ea03..a47e9edea8 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2410,6 +2410,8 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { v.color1_32 = gstate.imm_scv & 0xFFFFFF; if (prim != GE_PRIM_KEEP_PREVIOUS) { immPrim_ = (GEPrimitiveType)prim; + // Flags seem to only be respected from the first prim. + immFlags_ = op & 0x00FFF800; } else if (prim == GE_PRIM_KEEP_PREVIOUS && immPrim_ != GE_PRIM_INVALID) { static constexpr int flushPrimCount[] = { 1, 2, 0, 3, 0, 0, 2, 0 }; // Instead of finding a proper point to flush, we just emit a full rectangle every time one @@ -2456,12 +2458,42 @@ void GPUCommon::FlushImm() { } int vtype = GE_VTYPE_TC_FLOAT | GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; + static constexpr int GE_IMM_CULLENABLE = 0x00080000; + static constexpr int GE_IMM_CULLFACE = 0x00100000; + static constexpr int GE_IMM_TEXTURE = 0x00200000; + static constexpr int GE_IMM_DITHER = 0x00800000; + + bool texturing = (immFlags_ & GE_IMM_TEXTURE) != 0; + bool prevTexturing = gstate.isTextureMapEnabled(); + bool cullEnable = (immFlags_ & GE_IMM_CULLENABLE) != 0; + bool prevCullEnable = gstate.isCullEnabled(); + int cullMode = (immFlags_ & GE_IMM_CULLFACE) != 0 ? 1 : 0; + bool prevDither = gstate.isDitherEnabled(); + bool dither = (immFlags_ & GE_IMM_DITHER) != 0; + // Some notes say there's a flag to control this, but it seems to be flat regardless. + GEShadeMode prevShadeMode = gstate.getShadeMode(); + + if (texturing != prevTexturing || cullEnable != prevCullEnable || dither != prevDither || prevShadeMode != GE_SHADE_FLAT) { + DispatchFlush(); + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)texturing; + gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)cullEnable; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | GE_SHADE_FLAT; + gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)dither; + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); + } + int bytesRead; uint32_t vertTypeID = GetVertTypeID(vtype, 0); - drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, gstate.getCullMode(), &bytesRead); + drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, cullMode, &bytesRead); // TOOD: In the future, make a special path for these. // drawEngineCommon_->DispatchSubmitImm(immBuffer_, immCount_); immCount_ = 0; + + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)prevTexturing; + gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)prevCullEnable; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | prevShadeMode; + gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)prevDither; + gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); } void GPUCommon::ExecuteOp(u32 op, u32 diff) { diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index f2c64d95b8..3a5674127f 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -354,6 +354,7 @@ protected: TransformedVertex immBuffer_[MAX_IMMBUFFER_SIZE]; int immCount_ = 0; GEPrimitiveType immPrim_ = GE_PRIM_INVALID; + uint32_t immFlags_ = 0; std::string reportingPrimaryInfo_; std::string reportingFullInfo_; diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index db50f48bb6..cbfb754b77 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -71,10 +71,12 @@ void SoftwareDrawEngine::DispatchSubmitPrim(const void *verts, const void *inds, } void SoftwareDrawEngine::DispatchSubmitImm(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, u32 vertTypeID, int cullMode, int *bytesRead) { - _assert_msg_(cullMode == gstate.getCullMode(), "Mixed cull mode not supported."); + int flipCull = cullMode != gstate.getCullMode() ? 1 : 0; // TODO: For now, just setting all dirty. transformUnit.SetDirty(SoftDirty(-1)); + gstate.cullmode ^= flipCull; transformUnit.SubmitPrimitive(verts, inds, prim, vertexCount, vertTypeID, bytesRead, this); + gstate.cullmode ^= flipCull; // TODO: Should really clear, but the vertex type is faked so things might need resetting... transformUnit.SetDirty(SoftDirty(-1)); } From 7a83f8bab5b40a1f0c67b37e431179527619ba30 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 19:45:03 -0700 Subject: [PATCH 025/110] softgpu: Use vertType prim override for flags. These parameters are a real shame, was so clean before... --- GPU/Common/VertexDecoderCommon.h | 3 +++ GPU/Software/BinManager.cpp | 4 ++-- GPU/Software/BinManager.h | 2 +- GPU/Software/Clipper.cpp | 6 +++--- GPU/Software/FuncId.cpp | 6 +++--- GPU/Software/FuncId.h | 2 +- GPU/Software/Rasterizer.cpp | 6 +++--- GPU/Software/Rasterizer.h | 2 +- GPU/Software/TransformUnit.cpp | 10 +++++----- 9 files changed, 22 insertions(+), 19 deletions(-) diff --git a/GPU/Common/VertexDecoderCommon.h b/GPU/Common/VertexDecoderCommon.h index 3d6377a86c..5ec55ebe4c 100644 --- a/GPU/Common/VertexDecoderCommon.h +++ b/GPU/Common/VertexDecoderCommon.h @@ -28,6 +28,7 @@ #include "GPU/ge_constants.h" #include "GPU/Common/ShaderCommon.h" #include "GPU/GPUCommon.h" +#include "GPU/GPUState.h" #if PPSSPP_ARCH(ARM) #include "Common/ArmEmitter.h" @@ -299,6 +300,8 @@ public: bool hasNormal() const { return decFmt_.nrmfmt != 0; } bool hasUV() const { return decFmt_.uvfmt != 0; } bool isThrough() const { return (vtype_ & GE_VTYPE_THROUGH) != 0; } + bool skinningEnabled() const { return vertTypeIsSkinningEnabled(vtype_); } + int numBoneWeights() const { return vertTypeGetNumBoneWeights(vtype_); } void Goto(int index) { data_ = base_ + index * decFmt_.stride; } diff --git a/GPU/Software/BinManager.cpp b/GPU/Software/BinManager.cpp index 7f8f1ad453..faaf7b03a8 100644 --- a/GPU/Software/BinManager.cpp +++ b/GPU/Software/BinManager.cpp @@ -161,13 +161,13 @@ BinManager::~BinManager() { } } -void BinManager::UpdateState() { +void BinManager::UpdateState(bool throughMode) { PROFILE_THIS_SCOPE("bin_state"); if (HasDirty(SoftDirty::PIXEL_ALL | SoftDirty::SAMPLER_ALL | SoftDirty::RAST_ALL)) { if (states_.Full()) Flush("states"); stateIndex_ = (int)states_.Push(RasterizerState()); - ComputeRasterizerState(&states_[stateIndex_]); + ComputeRasterizerState(&states_[stateIndex_], throughMode); states_[stateIndex_].samplerID.cached.clut = cluts_[clutIndex_].readable; ClearDirty(SoftDirty::PIXEL_ALL | SoftDirty::SAMPLER_ALL | SoftDirty::RAST_ALL); diff --git a/GPU/Software/BinManager.h b/GPU/Software/BinManager.h index 01b6837d20..1d628aa8e4 100644 --- a/GPU/Software/BinManager.h +++ b/GPU/Software/BinManager.h @@ -181,7 +181,7 @@ public: BinManager(); ~BinManager(); - void UpdateState(); + void UpdateState(bool throughMode); void UpdateClut(const void *src); const Rasterizer::RasterizerState &State() { diff --git a/GPU/Software/Clipper.cpp b/GPU/Software/Clipper.cpp index 3627db0e3d..166947ef14 100644 --- a/GPU/Software/Clipper.cpp +++ b/GPU/Software/Clipper.cpp @@ -132,7 +132,7 @@ static inline bool CheckOutsideZ(ClipCoords p, int &pos, int &neg) { } void ProcessRect(const VertexData &v0, const VertexData &v1, BinManager &binner) { - if (!gstate.isModeThrough()) { + if (!binner.State().throughMode) { // We may discard the entire rect based on depth values. int outsidePos = 0, outsideNeg = 0; CheckOutsideZ(v0.clippos, outsidePos, outsideNeg); @@ -181,7 +181,7 @@ void ProcessPoint(const VertexData &v0, BinManager &binner) { } void ProcessLine(const VertexData &v0, const VertexData &v1, BinManager &binner) { - if (gstate.isModeThrough()) { + if (binner.State().throughMode) { // Actually, should clip this one too so we don't need to do bounds checks in the rasterizer. binner.AddLine(v0, v1); return; @@ -221,7 +221,7 @@ void ProcessLine(const VertexData &v0, const VertexData &v1, BinManager &binner) void ProcessTriangle(const VertexData &v0, const VertexData &v1, const VertexData &v2, const VertexData &provoking, BinManager &binner) { int mask = 0; - if (!gstate.isModeThrough()) { + if (!binner.State().throughMode) { mask |= CalcClipMask(v0.clippos); mask |= CalcClipMask(v1.clippos); mask |= CalcClipMask(v2.clippos); diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index 729591212b..084c897829 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -48,11 +48,11 @@ static inline PixelBlendFactor OptimizeAlphaFactor(uint32_t color) { return PixelBlendFactor::FIX; } -void ComputePixelFuncID(PixelFuncID *id) { +void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->fullKey = 0; // TODO: Could this be minz > 0x0000 || maxz < 0xFFFF? Maybe unsafe, depending on verts... - id->applyDepthRange = !gstate.isModeThrough(); + id->applyDepthRange = !throughMode; // Dither happens even in clear mode. id->dithering = gstate.isDitherEnabled(); id->fbFormat = gstate.FrameBufFormat(); @@ -162,7 +162,7 @@ void ComputePixelFuncID(PixelFuncID *id) { } id->applyLogicOp = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_COPY; - id->applyFog = gstate.isFogEnabled() && !gstate.isModeThrough(); + id->applyFog = gstate.isFogEnabled() && !throughMode; } // Cache some values for later convenience. diff --git a/GPU/Software/FuncId.h b/GPU/Software/FuncId.h index f847522e25..72207ebd5a 100644 --- a/GPU/Software/FuncId.h +++ b/GPU/Software/FuncId.h @@ -243,7 +243,7 @@ struct hash { }; -void ComputePixelFuncID(PixelFuncID *id); +void ComputePixelFuncID(PixelFuncID *id, bool throughMode); std::string DescribePixelFuncID(const PixelFuncID &id); void ComputeSamplerID(SamplerID *id); diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index 48e51cd9b2..a387e3b943 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -101,8 +101,8 @@ static inline Vec4 Interpolate(const float &c0, const float &c1, const fl return Interpolate(c0, c1, c2, w0.Cast(), w1.Cast(), w2.Cast(), wsum_recip); } -void ComputeRasterizerState(RasterizerState *state) { - ComputePixelFuncID(&state->pixelID); +void ComputeRasterizerState(RasterizerState *state, bool throughMode) { + ComputePixelFuncID(&state->pixelID, throughMode); state->drawPixel = Rasterizer::GetSingleFunc(state->pixelID); state->enableTextures = gstate.isTextureMapEnabled() && !state->pixelID.clearMode; @@ -140,7 +140,7 @@ void ComputeRasterizerState(RasterizerState *state) { } state->shadeGouraud = gstate.getShadeMode() == GE_SHADE_GOURAUD; - state->throughMode = gstate.isModeThrough(); + state->throughMode = throughMode; state->antialiasLines = gstate.isAntiAliasEnabled(); state->screenOffsetX = gstate.getOffsetX16(); diff --git a/GPU/Software/Rasterizer.h b/GPU/Software/Rasterizer.h index 2725bb922e..36236f5500 100644 --- a/GPU/Software/Rasterizer.h +++ b/GPU/Software/Rasterizer.h @@ -67,7 +67,7 @@ struct RasterizerState { } }; -void ComputeRasterizerState(RasterizerState *state); +void ComputeRasterizerState(RasterizerState *state, bool throughMode); // Draws a triangle if its vertices are specified in counter-clockwise order void DrawTriangle(const VertexData &v0, const VertexData &v1, const VertexData &v2, const BinCoords &range, const RasterizerState &state); diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index cbfb754b77..2a8eeeffa6 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -202,11 +202,11 @@ struct TransformState { }; void ComputeTransformState(TransformState *state, const VertexReader &vreader) { - state->enableTransform = !gstate.isModeThrough(); + state->enableTransform = !vreader.isThrough(); state->enableLighting = gstate.isLightingEnabled(); state->enableFog = gstate.isFogEnabled(); state->readUV = !gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV(); - state->readWeights = vertTypeIsSkinningEnabled(gstate.vertType) && state->enableTransform; + state->readWeights = vreader.skinningEnabled() && state->enableTransform; state->negateNormals = gstate.areNormalsReversed(); state->uvGenMode = gstate.getUVGenMode(); @@ -302,7 +302,7 @@ VertexData TransformUnit::ReadVertex(VertexReader &vreader, const TransformState Vec3 tmppos(0.f, 0.f, 0.f); Vec3 tmpnrm(0.f, 0.f, 0.f); - for (int i = 0; i < vertTypeGetNumBoneWeights(gstate.vertType); ++i) { + for (int i = 0; i < vreader.numBoneWeights(); ++i) { Vec3 step = Vec3ByMatrix43(pos, gstate.boneMatrix + i * 12); tmppos += step * W[i]; if (vreader.hasNormal()) { @@ -506,7 +506,7 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G // TODO: Do this in two passes - first process the vertices (before indexing/stripping), // then resolve the indices. This lets us avoid transforming shared vertices twice. - binner_->UpdateState(); + binner_->UpdateState(vreader.isThrough()); static TransformState transformState; if (binner_->HasDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL)) { @@ -595,7 +595,7 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G } } - if (data_index == 4 && gstate.isModeThrough() && cullType == CullType::OFF) { + if (data_index == 4 && vreader.isThrough() && cullType == CullType::OFF) { if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data)) { data[1] = data[3]; data_index = 2; From 880f6f8d4953a0312c6cd460405bc533092461ce Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 22:03:46 -0700 Subject: [PATCH 026/110] GPU: Handle more flags on imm prim command. --- GPU/GPUCommon.cpp | 33 ++++++++++++++++++--------------- GPU/ge_constants.h | 8 ++++++++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index a47e9edea8..0d4d8cf2fd 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2406,7 +2406,9 @@ void GPUCommon::Execute_ImmVertexAlphaPrim(u32 op, u32 diff) { v.v = getFloat24(gstate.imm_vtct); v.uv_w = getFloat24(gstate.imm_vtcq); v.color0_32 = (gstate.imm_cv & 0xFFFFFF) | (gstate.imm_ap << 24); - v.fog = 0.0f; // we have no information about the scale here + // TODO: When !gstate.isModeThrough(), direct fog coefficient (0 = entirely fog), ignore fog flag (also GE_IMM_FOG.) + v.fog = (gstate.imm_fc & 0xFF) / 255.0f; + // TODO: Apply if gstate.isUsingSecondaryColor() && !gstate.isModeThrough(), ignore lighting flag. v.color1_32 = gstate.imm_scv & 0xFFFFFF; if (prim != GE_PRIM_KEEP_PREVIOUS) { immPrim_ = (GEPrimitiveType)prim; @@ -2458,26 +2460,26 @@ void GPUCommon::FlushImm() { } int vtype = GE_VTYPE_TC_FLOAT | GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; - static constexpr int GE_IMM_CULLENABLE = 0x00080000; - static constexpr int GE_IMM_CULLFACE = 0x00100000; - static constexpr int GE_IMM_TEXTURE = 0x00200000; - static constexpr int GE_IMM_DITHER = 0x00800000; + // TODO: Handle fog and secondary color somehow? - bool texturing = (immFlags_ & GE_IMM_TEXTURE) != 0; - bool prevTexturing = gstate.isTextureMapEnabled(); + bool antialias = (immFlags_ & GE_IMM_ANTIALIAS) != 0; + bool prevAntialias = gstate.isAntiAliasEnabled(); + bool shading = (immFlags_ & GE_IMM_SHADING) != 0; + bool prevShading = gstate.getShadeMode() == GE_SHADE_GOURAUD; bool cullEnable = (immFlags_ & GE_IMM_CULLENABLE) != 0; bool prevCullEnable = gstate.isCullEnabled(); int cullMode = (immFlags_ & GE_IMM_CULLFACE) != 0 ? 1 : 0; - bool prevDither = gstate.isDitherEnabled(); + bool texturing = (immFlags_ & GE_IMM_TEXTURE) != 0; + bool prevTexturing = gstate.isTextureMapEnabled(); bool dither = (immFlags_ & GE_IMM_DITHER) != 0; - // Some notes say there's a flag to control this, but it seems to be flat regardless. - GEShadeMode prevShadeMode = gstate.getShadeMode(); + bool prevDither = gstate.isDitherEnabled(); - if (texturing != prevTexturing || cullEnable != prevCullEnable || dither != prevDither || prevShadeMode != GE_SHADE_FLAT) { + if (texturing != prevTexturing || cullEnable != prevCullEnable || dither != prevDither || prevShading != shading) { DispatchFlush(); - gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)texturing; + gstate.antiAliasEnable = (GE_CMD_ANTIALIASENABLE << 24) | (int)antialias; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | (int)shading; gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)cullEnable; - gstate.shademodel = (GE_CMD_SHADEMODE << 24) | GE_SHADE_FLAT; + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)texturing; gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)dither; gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); } @@ -2489,9 +2491,10 @@ void GPUCommon::FlushImm() { // drawEngineCommon_->DispatchSubmitImm(immBuffer_, immCount_); immCount_ = 0; - gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)prevTexturing; + gstate.antiAliasEnable = (GE_CMD_ANTIALIASENABLE << 24) | (int)prevAntialias; + gstate.shademodel = (GE_CMD_SHADEMODE << 24) | (int)prevShading; gstate.cullfaceEnable = (GE_CMD_CULLFACEENABLE << 24) | (int)prevCullEnable; - gstate.shademodel = (GE_CMD_SHADEMODE << 24) | prevShadeMode; + gstate.textureMapEnable = (GE_CMD_TEXTUREMAPENABLE << 24) | (int)prevTexturing; gstate.ditherEnable = (GE_CMD_DITHERENABLE << 24) | (int)prevDither; gstate_c.Dirty(DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE | DIRTY_RASTER_STATE); } diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 3559282c57..3c47a5781e 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -350,6 +350,14 @@ inline bool IsGeBufferFormat16BitColor(GEBufferFormat fmt) { #define GE_CLEARMODE_Z (1<<10) #define GE_CLEARMODE_ALL (GE_CLEARMODE_COLOR|GE_CLEARMODE_ALPHA|GE_CLEARMODE_Z) +#define GE_IMM_ANTIALIAS 0x00000800 +#define GE_IMM_SHADING 0x00040000 +#define GE_IMM_CULLENABLE 0x00080000 +#define GE_IMM_CULLFACE 0x00100000 +#define GE_IMM_TEXTURE 0x00200000 +#define GE_IMM_FOG 0x00400000 +#define GE_IMM_DITHER 0x00800000 + enum GEMatrixType { GE_MTX_BONE0 = 0, GE_MTX_BONE1, From 402492a95842cb7cb4a7872098c64d64d6f1b234 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Tue, 6 Sep 2022 22:18:55 -0700 Subject: [PATCH 027/110] GE Debugger: Show imm prim flag detail in disasm. --- GPU/Debugger/GECommandTable.cpp | 2 -- GPU/Debugger/GECommandTable.h | 2 +- GPU/GPUCommon.cpp | 12 +++++++++++- GPU/GeDisasm.cpp | 29 +++++++++++++++++++++++++++-- GPU/ge_constants.h | 1 + 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/GPU/Debugger/GECommandTable.cpp b/GPU/Debugger/GECommandTable.cpp index 95e77f1bb6..16304b9d75 100644 --- a/GPU/Debugger/GECommandTable.cpp +++ b/GPU/Debugger/GECommandTable.cpp @@ -275,9 +275,7 @@ static constexpr GECmdInfo geCmdInfo[] = { { GE_CMD_VTCT, "immt", GECmdFormat::FLOAT }, { GE_CMD_VTCQ, "immq", GECmdFormat::FLOAT }, { GE_CMD_VCV, "immrgb", GECmdFormat::RGB }, - // TODO: Confirm if any other bits are used? { GE_CMD_VAP, "imma_prim", GECmdFormat::ALPHA_PRIM }, - // TODO: Confirm it's 8 bit? { GE_CMD_VFC, "immfog", GECmdFormat::DATA8 }, { GE_CMD_VSCV, "immrgb1", GECmdFormat::RGB }, { GE_CMD_UNKNOWN_FA, "unknownfa", GECmdFormat::NONE }, diff --git a/GPU/Debugger/GECommandTable.h b/GPU/Debugger/GECommandTable.h index 9abe0f7c6d..95b4eddf0f 100644 --- a/GPU/Debugger/GECommandTable.h +++ b/GPU/Debugger/GECommandTable.h @@ -66,7 +66,7 @@ enum class GECmdFormat { BLEND_MODE, // 4 bits srcfactor, 4 bits dstfactor, 3 bits equation. DITHER_ROW, // 4 s.3.0 fixed point dither offsets. LOGIC_OP, // 4 bits logic operation. - ALPHA_PRIM, // 8 bits alpha, 3 bits primitive type. + ALPHA_PRIM, // 8 bits alpha, 3 bits primitive type, 1 bit antialias, 6 bit clip?, 1 bit shading, 1 bit cullenable, 1 bit cullface, 1 bit tex enable, 1 bit fog, 1 bit dither. }; struct GECmdInfo { diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 0d4d8cf2fd..107398b7c8 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -2449,6 +2449,7 @@ void GPUCommon::FlushImm() { float xyz[3]; }; ImmVertex temp[MAX_IMMBUFFER_SIZE]; + uint32_t color1Used = 0; for (int i = 0; i < immCount_; i++) { // Since we're sending through, scale back up to w/h. temp[i].uv[0] = immBuffer_[i].u * gstate.getTextureWidth(0); @@ -2457,6 +2458,7 @@ void GPUCommon::FlushImm() { temp[i].xyz[0] = immBuffer_[i].pos[0]; temp[i].xyz[1] = immBuffer_[i].pos[1]; temp[i].xyz[2] = immBuffer_[i].pos[2]; + color1Used |= immBuffer_[i].color1_32; } int vtype = GE_VTYPE_TC_FLOAT | GE_VTYPE_POS_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_THROUGH; @@ -2474,6 +2476,14 @@ void GPUCommon::FlushImm() { bool dither = (immFlags_ & GE_IMM_DITHER) != 0; bool prevDither = gstate.isDitherEnabled(); + if ((immFlags_ & GE_IMM_CLIPMASK) != 0) { + WARN_LOG_REPORT_ONCE(geimmclipvalue, G3D, "Imm vertex used clip value, flags=%06x", immFlags_); + } else if ((immFlags_ & GE_IMM_FOG) != 0) { + WARN_LOG_REPORT_ONCE(geimmfog, G3D, "Imm vertex used fog, flags=%06x", immFlags_); + } else if (color1Used != 0 && gstate.isUsingSecondaryColor()) { + WARN_LOG_REPORT_ONCE(geimmcolor1, G3D, "Imm vertex used secondary color, flags=%06x", immFlags_); + } + if (texturing != prevTexturing || cullEnable != prevCullEnable || dither != prevDither || prevShading != shading) { DispatchFlush(); gstate.antiAliasEnable = (GE_CMD_ANTIALIASENABLE << 24) | (int)antialias; @@ -2487,7 +2497,7 @@ void GPUCommon::FlushImm() { int bytesRead; uint32_t vertTypeID = GetVertTypeID(vtype, 0); drawEngineCommon_->DispatchSubmitImm(temp, nullptr, immPrim_, immCount_, vertTypeID, cullMode, &bytesRead); - // TOOD: In the future, make a special path for these. + // TODO: In the future, make a special path for these. // drawEngineCommon_->DispatchSubmitImm(immBuffer_, immCount_); immCount_ = 0; diff --git a/GPU/GeDisasm.cpp b/GPU/GeDisasm.cpp index c3098f5706..f1f1293255 100644 --- a/GPU/GeDisasm.cpp +++ b/GPU/GeDisasm.cpp @@ -1354,11 +1354,36 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { break; case GE_CMD_VAP: - snprintf(buffer, bufsize, "Vertex draw: alpha=%02x, prim=%s, other=%06x", data & 0xFF, primTypes[(data >> 8) & 7], data & ~0x0007FF); + { + bool antialias = (data & GE_IMM_ANTIALIAS) != 0; + int clip = (data & GE_IMM_CLIPMASK) >> 12; + bool shading = (data & GE_IMM_SHADING) != 0; + bool cullEnable = (data & GE_IMM_CULLENABLE) != 0; + int cullMode = (data & GE_IMM_CULLFACE) != 0 ? 1 : 0; + bool texturing = (data & GE_IMM_TEXTURE) != 0; + bool dither = (data & GE_IMM_DITHER) != 0; + char *p = buffer; + p += snprintf(p, bufsize - (p - buffer), "Vertex draw: alpha=%02x, prim=%s", data & 0xFF, primTypes[(data >> 8) & 7]); + if (antialias) + p += snprintf(p, bufsize - (p - buffer), ", antialias"); + if (clip != 0) + p += snprintf(p, bufsize - (p - buffer), ", clip=%02x", clip); + if (shading) + p += snprintf(p, bufsize - (p - buffer), ", shading"); + if (cullEnable) + p += snprintf(p, bufsize - (p - buffer), ", cull=%s", cullMode == 1 ? "back (CCW)" : "front (CW)"); + if (texturing) + p += snprintf(p, bufsize - (p - buffer), ", texturing"); + if (dither) + p += snprintf(p, bufsize - (p - buffer), ", dither"); + } break; case GE_CMD_VFC: - snprintf(buffer, bufsize, "Vertex fog: %06x", data); + if (data & ~0xFF) + snprintf(buffer, bufsize, "Vertex fog: %02x / %f (extra %04x)", data & 0xFF, (data & 0xFF) / 255.0f, data >> 8); + else + snprintf(buffer, bufsize, "Vertex fog: %02x / %f", data & 0xFF, (data & 0xFF) / 255.0f); break; case GE_CMD_VSCV: diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 3c47a5781e..19a51ae5ab 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -351,6 +351,7 @@ inline bool IsGeBufferFormat16BitColor(GEBufferFormat fmt) { #define GE_CLEARMODE_ALL (GE_CLEARMODE_COLOR|GE_CLEARMODE_ALPHA|GE_CLEARMODE_Z) #define GE_IMM_ANTIALIAS 0x00000800 +#define GE_IMM_CLIPMASK 0x0003F000 #define GE_IMM_SHADING 0x00040000 #define GE_IMM_CULLENABLE 0x00080000 #define GE_IMM_CULLFACE 0x00100000 From ad12aced6c1e48648ef27654ce43d01705b48bae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 21:55:22 +0200 Subject: [PATCH 028/110] Another attempt at fixing libretro, this time the win build failed --- libretro/Makefile.common | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index 836d8a2cfe..4dc521e2d6 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -801,9 +801,11 @@ SOURCES_C += $(ZSTDDIR)/common/debug.c \ $(ZSTDDIR)/dictBuilder/fastcover.c \ $(ZSTDDIR)/dictBuilder/zdict.c +ifneq (,$(findstring msvc,$(platform))) ifeq ($(TARGET_ARCH),x86_64) SOURCES_C += $(ZSTDDIR)/decompress/huf_decompress_amd64.S endif +endif ifneq ($(STATIC_LINKING), 1) SOURCES_C += \ From e828df9f256895f86aa9462000d0093e58d814cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 6 Sep 2022 13:30:18 +0200 Subject: [PATCH 029/110] Split each renderpass/framebuffer into multiple "compatibility classes" (RenderPassType). --- Common/Data/Collections/Hashmaps.h | 9 ++ Common/GPU/Vulkan/VulkanQueueRunner.cpp | 153 +++++++++------------ Common/GPU/Vulkan/VulkanQueueRunner.h | 64 +++++---- Common/GPU/Vulkan/VulkanRenderManager.cpp | 131 ++++++++++++------ Common/GPU/Vulkan/VulkanRenderManager.h | 61 ++++----- Common/GPU/Vulkan/thin3d_vulkan.cpp | 160 +++++++++------------- Common/GPU/thin3d.h | 3 - Common/Thread/Promise.h | 2 + GPU/Common/FragmentShaderGenerator.cpp | 5 +- GPU/Common/FragmentShaderGenerator.h | 7 +- GPU/D3D11/ShaderManagerD3D11.cpp | 2 +- GPU/Directx9/ShaderManagerDX9.cpp | 2 +- GPU/GLES/ShaderManagerGLES.cpp | 2 +- GPU/Vulkan/DrawEngineVulkan.cpp | 8 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 75 +++------- GPU/Vulkan/PipelineManagerVulkan.h | 4 +- GPU/Vulkan/ShaderManagerVulkan.cpp | 20 ++- GPU/Vulkan/ShaderManagerVulkan.h | 9 +- unittest/TestShaderGenerators.cpp | 10 +- 19 files changed, 352 insertions(+), 375 deletions(-) diff --git a/Common/Data/Collections/Hashmaps.h b/Common/Data/Collections/Hashmaps.h index 4c6664277c..d7de958c1b 100644 --- a/Common/Data/Collections/Hashmaps.h +++ b/Common/Data/Collections/Hashmaps.h @@ -127,6 +127,15 @@ public: } } + template + inline void IterateMut(T func) { + for (size_t i = 0; i < map.size(); i++) { + if (state[i] == BucketState::TAKEN) { + func(map[i].key, map[i].value); + } + } + } + void Clear() { memset(state.data(), (int)BucketState::FREE, state.size()); count_ = 0; diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index 9b7ae11ea5..fc9d34ec8d 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -29,11 +29,12 @@ static void MergeRenderAreaRectInto(VkRect2D *dest, VkRect2D &src) { void VulkanQueueRunner::CreateDeviceObjects() { INFO_LOG(G3D, "VulkanQueueRunner::CreateDeviceObjects"); - InitBackbufferRenderPass(); - RPKey key{ VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, - VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE }; - framebufferRenderPass_ = GetRenderPass(key); + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + compatibleRenderPass_ = GetRenderPass(key); #if 0 // Just to check whether it makes sense to split some of these. drawidx is way bigger than the others... @@ -117,78 +118,14 @@ void VulkanQueueRunner::DestroyDeviceObjects() { } readbackBufferSize_ = 0; - renderPasses_.Iterate([&](const RPKey &rpkey, VkRenderPass rp) { - _assert_(rp != VK_NULL_HANDLE); - vulkan_->Delete().QueueDeleteRenderPass(rp); + renderPasses_.IterateMut([&](const RPKey &rpkey, VKRRenderPass *rp) { + _assert_(rp); + for (int i = 0; i < RP_TYPE_COUNT; i++) { + vulkan_->Delete().QueueDeleteRenderPass(rp->pass[i]); + } + delete rp; }); renderPasses_.Clear(); - - _assert_(backbufferRenderPass_ != VK_NULL_HANDLE); - vulkan_->Delete().QueueDeleteRenderPass(backbufferRenderPass_); - backbufferRenderPass_ = VK_NULL_HANDLE; -} - -void VulkanQueueRunner::InitBackbufferRenderPass() { - VkAttachmentDescription attachments[2]; - attachments[0].format = vulkan_->GetSwapchainFormat(); - attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; - attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // We don't want to preserve the backbuffer between frames so we really don't care. - attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // We only render once to the backbuffer per frame so we can do this here. - attachments[0].flags = 0; - - attachments[1].format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat; // must use this same format later for the back depth buffer. - attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; - attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // Don't care about storing backbuffer Z - we clear it anyway. - attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - attachments[1].flags = 0; - - VkAttachmentReference color_reference{}; - color_reference.attachment = 0; - color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - VkAttachmentReference depth_reference{}; - depth_reference.attachment = 1; - depth_reference.layout = attachments[1].finalLayout; - - VkSubpassDescription subpass{}; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.flags = 0; - subpass.inputAttachmentCount = 0; - subpass.pInputAttachments = nullptr; - subpass.colorAttachmentCount = 1; - subpass.pColorAttachments = &color_reference; - subpass.pResolveAttachments = nullptr; - subpass.pDepthStencilAttachment = &depth_reference; - subpass.preserveAttachmentCount = 0; - subpass.pPreserveAttachments = nullptr; - - // For the built-in layout transitions. - VkSubpassDependency dep{}; - dep.srcSubpass = VK_SUBPASS_EXTERNAL; - dep.dstSubpass = 0; - dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dep.srcAccessMask = 0; - dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - - VkRenderPassCreateInfo rp_info{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; - rp_info.attachmentCount = 2; - rp_info.pAttachments = attachments; - rp_info.subpassCount = 1; - rp_info.pSubpasses = &subpass; - rp_info.dependencyCount = 1; - rp_info.pDependencies = &dep; - - VkResult res = vkCreateRenderPass(vulkan_->GetDevice(), &rp_info, nullptr, &backbufferRenderPass_); - _assert_(res == VK_SUCCESS); } static VkAttachmentLoadOp ConvertLoadAction(VKRRenderPassLoadAction action) { @@ -208,21 +145,16 @@ static VkAttachmentStoreOp ConvertStoreAction(VKRRenderPassStoreAction action) { return VK_ATTACHMENT_STORE_OP_DONT_CARE; // avoid compiler warning } -VkRenderPass VulkanQueueRunner::GetRenderPass(const RPKey &key) { - auto pass = renderPasses_.Get(key); - if (pass) { - return pass; - } - +VkRenderPass VulkanQueueRunner::CreateRP(const RPKey &key, RenderPassType rpType) { VkAttachmentDescription attachments[2] = {}; - attachments[0].format = VK_FORMAT_R8G8B8A8_UNORM; + attachments[0].format = rpType == RP_TYPE_BACKBUFFER ? vulkan_->GetSwapchainFormat() : VK_FORMAT_R8G8B8A8_UNORM; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = ConvertLoadAction(key.colorLoadAction); attachments[0].storeOp = ConvertStoreAction(key.colorStoreAction); attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].initialLayout = rpType == RP_TYPE_BACKBUFFER ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachments[0].finalLayout = rpType == RP_TYPE_BACKBUFFER ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachments[0].flags = 0; attachments[1].format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat; @@ -255,15 +187,48 @@ VkRenderPass VulkanQueueRunner::GetRenderPass(const RPKey &key) { subpass.preserveAttachmentCount = 0; subpass.pPreserveAttachments = nullptr; + // Not sure if this is really necessary. + VkSubpassDependency dep{}; + dep.srcSubpass = VK_SUBPASS_EXTERNAL; + dep.dstSubpass = 0; + dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dep.srcAccessMask = 0; + dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + VkRenderPassCreateInfo rp{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; rp.attachmentCount = 2; rp.pAttachments = attachments; rp.subpassCount = 1; rp.pSubpasses = &subpass; + if (rpType == RP_TYPE_BACKBUFFER) { + rp.dependencyCount = 1; + rp.pDependencies = &dep; + } + VkRenderPass pass; VkResult res = vkCreateRenderPass(vulkan_->GetDevice(), &rp, nullptr, &pass); _assert_(res == VK_SUCCESS); _assert_(pass != VK_NULL_HANDLE); + return pass; +} + +// Self-dependency: https://github.com/gpuweb/gpuweb/issues/442#issuecomment-547604827 +// Also see https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies +VKRRenderPass *VulkanQueueRunner::GetRenderPass(const RPKey &key) { + auto foundPass = renderPasses_.Get(key); + if (foundPass) { + return foundPass; + } + + VKRRenderPass *pass = new VKRRenderPass(); + // When we create a render pass, we create all "types" of it immediately, + // practical later when referring to it. Could change to on-demand if it feels motivated + // but I think the render pass objects are cheap. + for (int i = 0; i < RP_TYPE_COUNT; i++) { + pass->pass[i] = CreateRP(key, (RenderPassType)i); + } + renderPasses_.Insert(key, pass); return pass; } @@ -272,7 +237,8 @@ void VulkanQueueRunner::PreprocessSteps(std::vector &steps) { // Optimizes renderpasses, then sequences them. // Planned optimizations: // * Create copies of render target that are rendered to multiple times and textured from in sequence, and push those render passes - // as early as possible in the frame (Wipeout billboards). + // as early as possible in the frame (Wipeout billboards). This will require taking over more of descriptor management so we can + // substitute descriptors, alternatively using texture array layers creatively. for (int j = 0; j < (int)steps.size(); j++) { if (steps[j]->stepType == VKRStepType::RENDER && @@ -1159,6 +1125,8 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c int lastStencilCompareMask = -1; int lastStencilReference = -1; + const RenderPassType rpType = step.render.renderPassType; + for (const auto &c : commands) { switch (c.cmd) { case VKRRenderCommand::REMOVED: @@ -1181,7 +1149,8 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c { VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline; if (graphicsPipeline != lastGraphicsPipeline) { - VkPipeline pipeline = graphicsPipeline->pipeline->BlockUntilReady(); + _dbg_assert_(graphicsPipeline->pipeline[rpType]); + VkPipeline pipeline = graphicsPipeline->pipeline[rpType]->BlockUntilReady(); if (pipeline != VK_NULL_HANDLE) { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); pipelineLayout = c.pipeline.pipelineLayout; @@ -1338,7 +1307,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c } void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) { - VkRenderPass renderPass; + VKRRenderPass *renderPass; int numClearVals = 0; VkClearValue clearVal[2]{}; VkFramebuffer framebuf; @@ -1349,7 +1318,7 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step _dbg_assert_(step.render.finalDepthStencilLayout != VK_IMAGE_LAYOUT_UNDEFINED); VKRFramebuffer *fb = step.render.framebuffer; - framebuf = fb->framebuf; + framebuf = fb->framebuf[step.render.renderPassType]; w = fb->width; h = fb->height; @@ -1395,7 +1364,13 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step // Raw, rotated backbuffer size. w = vulkan_->GetBackbufferWidth(); h = vulkan_->GetBackbufferHeight(); - renderPass = GetBackbufferRenderPass(); + + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + renderPass = GetRenderPass(key); + Uint8x4ToFloat4(clearVal[0].color.float32, step.render.clearColor); numClearVals = 2; // We don't bother with a depth buffer here. clearVal[1].depthStencil.depth = 0.0f; @@ -1403,7 +1378,7 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step } VkRenderPassBeginInfo rp_begin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; - rp_begin.renderPass = renderPass; + rp_begin.renderPass = renderPass->pass[(int)step.render.renderPassType]; rp_begin.framebuffer = framebuf; VkRect2D rc = step.render.renderArea; diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.h b/Common/GPU/Vulkan/VulkanQueueRunner.h index ce6dc9f5eb..eb1423132e 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.h +++ b/Common/GPU/Vulkan/VulkanQueueRunner.h @@ -47,6 +47,14 @@ enum PipelineFlags { PIPELINE_FLAG_USES_DEPTH_STENCIL = (1 << 4), // Reads or writes the depth buffer. }; +// Pipelines need to be created for the right type of render pass. +enum RenderPassType { + RP_TYPE_BACKBUFFER, + RP_TYPE_COLOR_DEPTH, + // Later will add pure-color render passes. + RP_TYPE_COUNT, +}; + struct VkRenderData { VKRRenderCommand cmd; union { @@ -147,6 +155,8 @@ struct QueueProfileContext { double cpuEndTime; }; +struct VKRRenderPass; + struct VKRStep { VKRStep(VKRStepType _type) : stepType(_type) {} ~VKRStep() {} @@ -159,6 +169,7 @@ struct VKRStep { union { struct { VKRFramebuffer *framebuffer; + // TODO: Look these up through renderPass? VKRRenderPassLoadAction colorLoad; VKRRenderPassLoadAction depthLoad; VKRRenderPassLoadAction stencilLoad; @@ -175,6 +186,9 @@ struct VKRStep { VkImageLayout finalDepthStencilLayout; u32 pipelineFlags; VkRect2D renderArea; + // Render pass type. Deduced after finishing recording the pass, from the used pipelines. + // NOTE: Storing the render pass here doesn't do much good, we change the compatible parameters (load/store ops) during step optimization. + RenderPassType renderPassType; } render; struct { VKRFramebuffer *src; @@ -204,9 +218,24 @@ struct VKRStep { }; }; +struct VKRRenderPass { + VkRenderPass pass[RP_TYPE_COUNT]; +}; + +struct RPKey { + // Only render-pass-compatibility-volatile things can be here. + VKRRenderPassLoadAction colorLoadAction; + VKRRenderPassLoadAction depthLoadAction; + VKRRenderPassLoadAction stencilLoadAction; + VKRRenderPassStoreAction colorStoreAction; + VKRRenderPassStoreAction depthStoreAction; + VKRRenderPassStoreAction stencilStoreAction; +}; + class VulkanQueueRunner { public: VulkanQueueRunner(VulkanContext *vulkan) : vulkan_(vulkan), renderPasses_(16) {} + void SetBackbuffer(VkFramebuffer fb, VkImage img) { backbuffer_ = fb; backbufferImage_ = img; @@ -221,14 +250,10 @@ public: void CreateDeviceObjects(); void DestroyDeviceObjects(); - VkRenderPass GetBackbufferRenderPass() const { - return backbufferRenderPass_; - } - // Get a render pass that's compatible with all our framebuffers. // Note that it's precached, cannot look up in the map as this might be on another thread. - VkRenderPass GetFramebufferRenderPass() const { - return framebufferRenderPass_; + VKRRenderPass *GetCompatibleRenderPass() const { + return compatibleRenderPass_; } inline int RPIndex(VKRRenderPassLoadAction color, VKRRenderPassLoadAction depth) { @@ -237,20 +262,11 @@ public: void CopyReadbackBuffer(int width, int height, Draw::DataFormat srcFormat, Draw::DataFormat destFormat, int pixelStride, uint8_t *pixels); - struct RPKey { - VKRRenderPassLoadAction colorLoadAction; - VKRRenderPassLoadAction depthLoadAction; - VKRRenderPassLoadAction stencilLoadAction; - VKRRenderPassStoreAction colorStoreAction; - VKRRenderPassStoreAction depthStoreAction; - VKRRenderPassStoreAction stencilStoreAction; - }; + VKRRenderPass *GetRenderPass(const RPKey &key); - VkRenderPass GetRenderPass(const RPKey &key); - - bool GetRenderPassKey(VkRenderPass passToFind, RPKey *outKey) const { + bool GetRenderPassKey(VKRRenderPass *passToFind, RPKey *outKey) const { bool found = false; - renderPasses_.Iterate([passToFind, &found, outKey](const RPKey &rpkey, VkRenderPass pass) { + renderPasses_.Iterate([passToFind, &found, outKey](const RPKey &rpkey, const VKRRenderPass *pass) { if (pass == passToFind) { found = true; *outKey = rpkey; @@ -273,7 +289,7 @@ public: } private: - void InitBackbufferRenderPass(); + VkRenderPass CreateRP(const RPKey &key, RenderPassType rpType); void PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); void PerformRenderPass(const VKRStep &pass, VkCommandBuffer cmd); @@ -302,14 +318,12 @@ private: VkFramebuffer backbuffer_ = VK_NULL_HANDLE; VkImage backbufferImage_ = VK_NULL_HANDLE; - VkRenderPass backbufferRenderPass_ = VK_NULL_HANDLE; - - // The "Compatible" render pass. Used when creating pipelines that render to "normal" framebuffers. - VkRenderPass framebufferRenderPass_ = VK_NULL_HANDLE; + // The "Compatible" render pass. Should be able to get rid of this soon. + VKRRenderPass *compatibleRenderPass_ = nullptr; // Renderpasses, all combinations of preserving or clearing or dont-care-ing fb contents. - // TODO: Create these on demand. - DenseHashMap renderPasses_; + // Each VKRRenderPass contains all compatibility classes (which attachments they have, etc). + DenseHashMap renderPasses_; // Readback buffer. Currently we only support synchronous readback, so we only really need one. // We size it generously. diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index a4e14a1b8d..8d5593d539 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -25,7 +25,8 @@ using namespace PPSSPP_VK; -bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { +// renderPass is an example of the "compatibility class" or RenderPassType type. +bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType) { if (!desc) { // Already failed to create this one. return false; @@ -55,12 +56,30 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { ss[1].pName = "main"; ss[1].flags = 0; - desc->pipe.pStages = ss; - desc->pipe.stageCount = 2; + VkGraphicsPipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; + pipe.pStages = ss; + pipe.stageCount = 2; + pipe.renderPass = compatibleRenderPass; + pipe.basePipelineIndex = 0; + pipe.pColorBlendState = &desc->cbs; + pipe.pDepthStencilState = &desc->dss; + pipe.pRasterizationState = &desc->rs; + + // We will use dynamic viewport state. + pipe.pVertexInputState = &desc->vis; + pipe.pViewportState = &desc->views; + pipe.pTessellationState = nullptr; + pipe.pDynamicState = &desc->ds; + pipe.pInputAssemblyState = &desc->inputAssembly; + pipe.pMultisampleState = &desc->ms; + pipe.layout = desc->pipelineLayout; + pipe.basePipelineHandle = VK_NULL_HANDLE; + pipe.basePipelineIndex = 0; + pipe.subpass = 0; double start = time_now_d(); VkPipeline vkpipeline; - VkResult result = vkCreateGraphicsPipelines(vulkan->GetDevice(), desc->pipelineCache, 1, &desc->pipe, nullptr, &vkpipeline); + VkResult result = vkCreateGraphicsPipelines(vulkan->GetDevice(), desc->pipelineCache, 1, &pipe, nullptr, &vkpipeline); INFO_LOG(G3D, "Pipeline creation time: %0.2f ms", (time_now_d() - start) * 1000.0); @@ -70,14 +89,14 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan) { // Would really like to log more here, we could probably attach more info to desc. // // At least create a null placeholder to avoid creating over and over if something is broken. - pipeline->Post(VK_NULL_HANDLE); + pipeline[rpType]->Post(VK_NULL_HANDLE); success = false; } else if (result != VK_SUCCESS) { - pipeline->Post(VK_NULL_HANDLE); + pipeline[rpType]->Post(VK_NULL_HANDLE); ERROR_LOG(G3D, "Failed creating graphics pipeline! result='%s'", VulkanResultToString(result)); success = false; } else { - pipeline->Post(vkpipeline); + pipeline[rpType]->Post(vkpipeline); } // Having the desc stick around can be useful for debugging. @@ -110,33 +129,35 @@ bool VKRComputePipeline::Create(VulkanContext *vulkan) { return success; } -VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRenderPass renderPass, int _width, int _height, const char *tag) : vulkan_(vk) { +VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag) : vulkan_(vk) { width = _width; height = _height; CreateImage(vulkan_, initCmd, color, width, height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, true, tag); CreateImage(vulkan_, initCmd, depth, width, height, vulkan_->GetDeviceInfo().preferredDepthStencilFormat, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, false, tag); - VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; - VkImageView views[2]{}; + for (int i = 0; i < RP_TYPE_COUNT; i++) { + VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; + VkImageView views[2]{}; - fbci.renderPass = renderPass; - fbci.attachmentCount = 2; - fbci.pAttachments = views; - views[0] = color.imageView; - views[1] = depth.imageView; - fbci.width = width; - fbci.height = height; - fbci.layers = 1; + fbci.renderPass = compatibleRenderPass->pass[i]; + fbci.attachmentCount = 2; + fbci.pAttachments = views; + views[0] = color.imageView; + views[1] = depth.imageView; + fbci.width = width; + fbci.height = height; + fbci.layers = 1; - VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf); - _assert_(res == VK_SUCCESS); + VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf[i]); + _assert_(res == VK_SUCCESS); - if (tag && vk->Extensions().EXT_debug_utils) { - vk->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag).c_str()); - vk->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag).c_str()); - vk->SetDebugName(framebuf, VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag).c_str()); - this->tag = tag; + if (tag && vk->Extensions().EXT_debug_utils) { + vk->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag).c_str()); + vk->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag).c_str()); + vk->SetDebugName(framebuf[i], VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag).c_str()); + this->tag = tag; + } } } @@ -155,8 +176,10 @@ VKRFramebuffer::~VKRFramebuffer() { } if (depth.depthSampleView) vulkan_->Delete().QueueDeleteImageView(depth.depthSampleView); - if (framebuf) - vulkan_->Delete().QueueDeleteFramebuffer(framebuf); + for (auto &fb : framebuf) { + if (fb) + vulkan_->Delete().QueueDeleteFramebuffer(fb); + } } void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag) { @@ -493,7 +516,7 @@ void VulkanRenderManager::CompileThreadFunc() { for (auto &entry : toCompile) { switch (entry.type) { case CompileQueueEntry::Type::GRAPHICS: - entry.graphics->Create(vulkan_); + entry.graphics->Create(vulkan_, entry.compatibleRenderPass, entry.renderPassType); break; case CompileQueueEntry::Type::COMPUTE: entry.compute->Create(vulkan_); @@ -664,23 +687,45 @@ VkCommandBuffer VulkanRenderManager::GetInitCmd() { } void VulkanRenderManager::EndCurRenderStep() { + if (!curRenderStep_) + return; + + RPKey key{ + curRenderStep_->render.colorLoad, curRenderStep_->render.depthLoad, curRenderStep_->render.stencilLoad, + curRenderStep_->render.colorStore, curRenderStep_->render.depthStore, curRenderStep_->render.stencilStore, + }; + RenderPassType rpType = RP_TYPE_COLOR_DEPTH; + curRenderStep_->render.pipelineFlags = curPipelineFlags_; + if (!curRenderStep_->render.framebuffer) { + rpType = RP_TYPE_BACKBUFFER; + } + + VKRRenderPass *renderPass = queueRunner_.GetRenderPass(key); + curRenderStep_->render.renderPassType = rpType; + // Save the accumulated pipeline flags so we can use that to configure the render pass. // We'll often be able to avoid loading/saving the depth/stencil buffer. - if (curRenderStep_) { - curRenderStep_->render.pipelineFlags = curPipelineFlags_; - // We don't do this optimization for very small targets, probably not worth it. - if (!curRenderArea_.Empty() && (curWidth_ > 32 && curHeight_ > 32)) { - curRenderStep_->render.renderArea = curRenderArea_.ToVkRect2D(); - } else { - curRenderStep_->render.renderArea.offset = {}; - curRenderStep_->render.renderArea.extent = { (uint32_t)curWidth_, (uint32_t)curHeight_ }; - } - curRenderArea_.Reset(); - - // We no longer have a current render step. - curRenderStep_ = nullptr; - curPipelineFlags_ = 0; + compileMutex_.lock(); + for (VKRGraphicsPipeline *pipeline : pipelinesToCreate_) { + pipeline->pipeline[rpType] = Promise::CreateEmpty(); + compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->pass[rpType], rpType)); } + compileCond_.notify_one(); + compileMutex_.unlock(); + pipelinesToCreate_.clear(); + + // We don't do this optimization for very small targets, probably not worth it. + if (!curRenderArea_.Empty() && (curWidth_ > 32 && curHeight_ > 32)) { + curRenderStep_->render.renderArea = curRenderArea_.ToVkRect2D(); + } else { + curRenderStep_->render.renderArea.offset = {}; + curRenderStep_->render.renderArea.extent = { (uint32_t)curWidth_, (uint32_t)curHeight_ }; + } + curRenderArea_.Reset(); + + // We no longer have a current render step. + curRenderStep_ = nullptr; + curPipelineFlags_ = 0; } void VulkanRenderManager::BindFramebufferAsRenderTarget(VKRFramebuffer *fb, VKRRenderPassLoadAction color, VKRRenderPassLoadAction depth, VKRRenderPassLoadAction stencil, uint32_t clearColor, float clearDepth, uint8_t clearStencil, const char *tag) { @@ -909,7 +954,7 @@ bool VulkanRenderManager::InitBackbufferFramebuffers(int width, int height) { VLOG("InitFramebuffers: %dx%d", width, height); VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; - fb_info.renderPass = queueRunner_.GetBackbufferRenderPass(); + fb_info.renderPass = queueRunner_.GetCompatibleRenderPass()->pass[RP_TYPE_BACKBUFFER]; fb_info.attachmentCount = 2; fb_info.pAttachments = attachments; fb_info.width = width; diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index 67dff36880..808418c470 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -43,10 +43,10 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int class VKRFramebuffer { public: - VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VkRenderPass renderPass, int _width, int _height, const char *tag); + VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag); ~VKRFramebuffer(); - VkFramebuffer framebuf = VK_NULL_HANDLE; + VkFramebuffer framebuf[RP_TYPE_COUNT]{}; VKRImage color{}; VKRImage depth{}; int width = 0; @@ -132,7 +132,12 @@ struct VKRGraphicsPipelineDesc { VkVertexInputBindingDescription ibd{}; VkPipelineVertexInputStateCreateInfo vis{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; VkPipelineViewportStateCreateInfo views{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; - VkGraphicsPipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; + + VkPipelineLayout pipelineLayout; + + // Does not include the render pass type, it's passed in separately since the + // desc is persistent. + RPKey rpKey; }; // All the data needed to create a compute pipeline. @@ -144,16 +149,18 @@ struct VKRComputePipelineDesc { // Wrapped pipeline. struct VKRGraphicsPipeline { VKRGraphicsPipeline() { - pipeline = Promise::CreateEmpty(); + for (int i = 0; i < RP_TYPE_COUNT; i++) { + pipeline[i] = nullptr; + } } ~VKRGraphicsPipeline() { delete desc; } VKRGraphicsPipelineDesc *desc = nullptr; - Promise *pipeline; + Promise *pipeline[RP_TYPE_COUNT]; - bool Create(VulkanContext *vulkan); + bool Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType); }; struct VKRComputePipeline { @@ -170,13 +177,16 @@ struct VKRComputePipeline { }; struct CompileQueueEntry { - CompileQueueEntry(VKRGraphicsPipeline *p) : type(Type::GRAPHICS), graphics(p) {} - CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p) {} + CompileQueueEntry(VKRGraphicsPipeline *p, VkRenderPass _compatibleRenderPass, RenderPassType _renderPassType) + : type(Type::GRAPHICS), graphics(p), compatibleRenderPass(_compatibleRenderPass), renderPassType(_renderPassType) {} + CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p), renderPassType(RP_TYPE_COLOR_DEPTH) {} enum class Type { GRAPHICS, COMPUTE, }; Type type; + VkRenderPass compatibleRenderPass; + RenderPassType renderPassType; VKRGraphicsPipeline *graphics = nullptr; VKRComputePipeline *compute = nullptr; }; @@ -228,13 +238,13 @@ public: // Deferred creation, like in GL. Unlike GL though, the purpose is to allow background creation and avoiding // stalling the emulation thread as much as possible. + // We delay creating pipelines until the end of the current render pass, so we can create the right type immediately. VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc) { VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); + _dbg_assert_(desc->vertexShader); + _dbg_assert_(desc->fragmentShader); pipeline->desc = desc; - compileMutex_.lock(); - compileQueue_.push_back(CompileQueueEntry(pipeline)); - compileCond_.notify_one(); - compileMutex_.unlock(); + pipelinesToCreate_.push_back(pipeline); return pipeline; } @@ -248,16 +258,6 @@ public: return pipeline; } - void BindPipeline(VkPipeline pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) { - _dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER); - _dbg_assert_(pipeline != VK_NULL_HANDLE); - VkRenderData data{ VKRRenderCommand::BIND_PIPELINE }; - data.pipeline.pipeline = pipeline; - data.pipeline.pipelineLayout = pipelineLayout; - curPipelineFlags_ |= flags; - curRenderStep_->commands.push_back(data); - } - void BindPipeline(VKRGraphicsPipeline *pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) { _dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER); _dbg_assert_(pipeline != nullptr); @@ -431,20 +431,6 @@ public: VkCommandBuffer GetInitCmd(); - VkRenderPass GetBackbufferRenderPass() { - return queueRunner_.GetBackbufferRenderPass(); - } - VkRenderPass GetFramebufferRenderPass() { - return queueRunner_.GetFramebufferRenderPass(); - } - VkRenderPass GetCompatibleRenderPass() { - if (curRenderStep_ && curRenderStep_->render.framebuffer != nullptr) { - return queueRunner_.GetFramebufferRenderPass(); - } else { - return queueRunner_.GetBackbufferRenderPass(); - } - } - // Gets a frame-unique ID of the current step being recorded. Can be used to figure out // when the current step has changed, which means the caller will need to re-record its state. int GetCurrentStepId() const { @@ -581,6 +567,9 @@ private: std::mutex compileMutex_; std::vector compileQueue_; + // pipelines to create at the end of the current render pass. + std::vector pipelinesToCreate_; + // Swap chain management struct SwapchainImageData { VkImage image; diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 8a1112d446..388939854c 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -31,6 +31,7 @@ #include "Common/GPU/Vulkan/VulkanContext.h" #include "Common/GPU/Vulkan/VulkanImage.h" #include "Common/GPU/Vulkan/VulkanMemory.h" +#include "Common/Thread/Promise.h" #include "Core/Config.h" @@ -248,13 +249,12 @@ public: class VKPipeline : public Pipeline { public: - VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags) : flags(_flags), vulkan_(vulkan) { + VKPipeline(VulkanRenderManager *rm, size_t size, PipelineFlags _flags) : rm_(rm), flags(_flags) { uboSize_ = (int)size; ubo_ = new uint8_t[uboSize_]; } ~VKPipeline() { - vulkan_->Delete().QueueDeletePipeline(backbufferPipeline); - vulkan_->Delete().QueueDeletePipeline(framebufferPipeline); + // TODO: Right now we just leak the pipeline! This is not good. delete[] ubo_; } @@ -272,17 +272,16 @@ public: return uboSize_; } - VkPipeline backbufferPipeline = VK_NULL_HANDLE; - VkPipeline framebufferPipeline = VK_NULL_HANDLE; - + VKRGraphicsPipeline *pipeline = nullptr; PipelineFlags flags; + int stride[4]{}; int dynamicUniformSize = 0; bool usesStencil = false; private: - VulkanContext *vulkan_; + VulkanRenderManager *rm_; uint8_t *ubo_; int uboSize_; }; @@ -429,7 +428,7 @@ public: void DrawIndexed(int vertexCount, int offset) override; void DrawUP(const void *vdata, int vertexCount) override; - void BindCompatiblePipeline(); + void BindCurrentPipeline(); void ApplyDynamicState(); void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) override; @@ -466,13 +465,6 @@ public: switch (obj) { case NativeObject::CONTEXT: return (uint64_t)vulkan_; - case NativeObject::FRAMEBUFFER_RENDERPASS: - // Return a representative renderpass. - return (uint64_t)renderManager_.GetFramebufferRenderPass(); - case NativeObject::BACKBUFFER_RENDERPASS: - return (uint64_t)renderManager_.GetBackbufferRenderPass(); - case NativeObject::COMPATIBLE_RENDERPASS: - return (uint64_t)renderManager_.GetCompatibleRenderPass(); case NativeObject::INIT_COMMANDBUFFER: return (uint64_t)renderManager_.GetInitCmd(); case NativeObject::BOUND_TEXTURE0_IMAGEVIEW: @@ -1047,7 +1039,24 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipelineFlags |= PIPELINE_FLAG_USES_DEPTH_STENCIL; } - VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); + VKPipeline *pipeline = new VKPipeline(&renderManager_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); + + VKRGraphicsPipelineDesc gDesc{}; + + std::vector stages; + stages.resize(desc.shaders.size()); + + for (auto &iter : desc.shaders) { + VKShaderModule *vkshader = (VKShaderModule *)iter; + if (vkshader->GetStage() == ShaderStage::Vertex) { + gDesc.vertexShader = Promise::AlreadyDone(vkshader->Get()); + } else if (vkshader->GetStage() == ShaderStage::Fragment) { + gDesc.fragmentShader = Promise::AlreadyDone(vkshader->Get()); + } else { + ERROR_LOG(G3D, "Bad stage"); + return nullptr; + } + } if (input) { for (int i = 0; i < (int)input->bindings.size(); i++) { @@ -1056,84 +1065,50 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { } else { pipeline->stride[0] = 0; } + _dbg_assert_(input->bindings.size() == 1); + _dbg_assert_((int)input->attributes.size() == (int)input->visc.vertexAttributeDescriptionCount); - std::vector stages; - stages.resize(desc.shaders.size()); - int i = 0; - for (auto &iter : desc.shaders) { - VKShaderModule *vkshader = (VKShaderModule *)iter; - if (!vkshader) { - ERROR_LOG(G3D, "CreateGraphicsPipeline got passed a null shader"); - return nullptr; - } - VkPipelineShaderStageCreateInfo &stage = stages[i++]; - stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - stage.pNext = nullptr; - stage.pSpecializationInfo = nullptr; - stage.stage = StageToVulkan(vkshader->GetStage()); - stage.module = vkshader->Get(); - stage.pName = "main"; - stage.flags = 0; + gDesc.ibd = input->bindings[0]; + for (int i = 0; i < input->attributes.size(); i++) { + gDesc.attrs[i] = input->attributes[i]; } + gDesc.vis.vertexAttributeDescriptionCount = input->visc.vertexAttributeDescriptionCount; + gDesc.vis.vertexBindingDescriptionCount = input->visc.vertexBindingDescriptionCount; + gDesc.vis.pVertexBindingDescriptions = &gDesc.ibd; + gDesc.vis.pVertexAttributeDescriptions = gDesc.attrs; - VkPipelineInputAssemblyStateCreateInfo inputAssembly = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; - inputAssembly.topology = primToVK[(int)desc.prim]; - inputAssembly.primitiveRestartEnable = false; + gDesc.blend0 = blend->attachments[0]; + gDesc.cbs = blend->info; + + gDesc.dss = depth->info; + + raster->ToVulkan(&gDesc.rs); + + // Copy bindings from input layout. + gDesc.inputAssembly.topology = primToVK[(int)desc.prim]; // We treat the three stencil states as a unit in other places, so let's do that here too. - VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK }; - VkPipelineDynamicStateCreateInfo dynamicInfo = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO }; - dynamicInfo.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2; - dynamicInfo.pDynamicStates = dynamics; + const VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK }; + gDesc.ds.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2; + for (int i = 0; i < gDesc.ds.dynamicStateCount; i++) { + gDesc.dynamicStates[i] = dynamics[i]; + } + gDesc.ds.pDynamicStates = gDesc.dynamicStates; - VkPipelineMultisampleStateCreateInfo ms{ VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; - ms.pSampleMask = nullptr; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + gDesc.ms.pSampleMask = nullptr; + gDesc.ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineViewportStateCreateInfo vs{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; - vs.viewportCount = 1; - vs.scissorCount = 1; - vs.pViewports = nullptr; // dynamic - vs.pScissors = nullptr; // dynamic + gDesc.views.viewportCount = 1; + gDesc.views.scissorCount = 1; + gDesc.views.pViewports = nullptr; // dynamic + gDesc.views.pScissors = nullptr; // dynamic + + gDesc.pipelineLayout = pipelineLayout_; VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; - raster->ToVulkan(&rs); + raster->ToVulkan(&gDesc.rs); - VkPipelineVertexInputStateCreateInfo emptyVisc{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; - - VkGraphicsPipelineCreateInfo createInfo[2]{}; - for (auto &info : createInfo) { - info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - info.flags = 0; - info.stageCount = (uint32_t)stages.size(); - info.pStages = stages.data(); - info.pColorBlendState = &blend->info; - info.pDepthStencilState = &depth->info; - info.pDynamicState = &dynamicInfo; - info.pInputAssemblyState = &inputAssembly; - info.pTessellationState = nullptr; - info.pMultisampleState = &ms; - info.pVertexInputState = input ? &input->visc : &emptyVisc; - info.pRasterizationState = &rs; - info.pViewportState = &vs; // Must set viewport and scissor counts even if we set the actual state dynamically. - info.layout = pipelineLayout_; - info.subpass = 0; - } - - createInfo[0].renderPass = renderManager_.GetBackbufferRenderPass(); - createInfo[1].renderPass = renderManager_.GetFramebufferRenderPass(); - - // OK, need to create new pipelines. - VkPipeline pipelines[2]{}; - VkResult result = vkCreateGraphicsPipelines(device_, pipelineCache_, 2, createInfo, nullptr, pipelines); - if (result != VK_SUCCESS) { - ERROR_LOG(G3D, "Failed to create graphics pipeline"); - delete pipeline; - return nullptr; - } - - pipeline->backbufferPipeline = pipelines[0]; - pipeline->framebufferPipeline = pipelines[1]; + pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc);; if (desc.uniformDesc) { pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize; @@ -1338,7 +1313,7 @@ void VKContext::Draw(int vertexCount, int offset) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.Draw(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vertexCount, offset); } @@ -1358,7 +1333,7 @@ void VKContext::DrawIndexed(int vertexCount, int offset) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.DrawIndexed(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vulkanIbuf, (int)ibBindOffset + offset * sizeof(uint32_t), vertexCount, 1, VK_INDEX_TYPE_UINT16); } @@ -1374,18 +1349,13 @@ void VKContext::DrawUP(const void *vdata, int vertexCount) { return; } - BindCompatiblePipeline(); + BindCurrentPipeline(); ApplyDynamicState(); renderManager_.Draw(descSet, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffsets_[0], vertexCount); } -void VKContext::BindCompatiblePipeline() { - VkRenderPass renderPass = renderManager_.GetCompatibleRenderPass(); - if (renderPass == renderManager_.GetBackbufferRenderPass()) { - renderManager_.BindPipeline(curPipeline_->backbufferPipeline, curPipeline_->flags, pipelineLayout_); - } else { - renderManager_.BindPipeline(curPipeline_->framebufferPipeline, curPipeline_->flags, pipelineLayout_); - } +void VKContext::BindCurrentPipeline() { + renderManager_.BindPipeline(curPipeline_->pipeline, curPipeline_->flags, pipelineLayout_); } void VKContext::Clear(int clearMask, uint32_t colorval, float depthVal, int stencilVal) { @@ -1497,7 +1467,7 @@ Framebuffer *VKContext::CreateFramebuffer(const FramebufferDesc &desc) { VkCommandBuffer cmd = renderManager_.GetInitCmd(); // TODO: We always create with depth here, even when it's not needed (such as color temp FBOs). // Should optimize those away. - VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetFramebufferRenderPass(), desc.width, desc.height, desc.tag); + VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetQueueRunner()->GetCompatibleRenderPass(), desc.width, desc.height, desc.tag); return new VKFramebuffer(vkrfb); } diff --git a/Common/GPU/thin3d.h b/Common/GPU/thin3d.h index 21d605b6cd..f44447b1af 100644 --- a/Common/GPU/thin3d.h +++ b/Common/GPU/thin3d.h @@ -239,9 +239,6 @@ enum class NativeObject { BACKBUFFER_COLOR_TEX, BACKBUFFER_DEPTH_TEX, FEATURE_LEVEL, - COMPATIBLE_RENDERPASS, - BACKBUFFER_RENDERPASS, - FRAMEBUFFER_RENDERPASS, INIT_COMMANDBUFFER, BOUND_TEXTURE0_IMAGEVIEW, BOUND_TEXTURE1_IMAGEVIEW, diff --git a/Common/Thread/Promise.h b/Common/Thread/Promise.h index 4145b4b6c1..6fae6d7a2b 100644 --- a/Common/Thread/Promise.h +++ b/Common/Thread/Promise.h @@ -79,6 +79,7 @@ public: // Returns T if the data is ready, nullptr if it's not. T Poll() { + _dbg_assert_(this != nullptr); std::lock_guard guard(readyMutex_); if (ready_) { return data_; @@ -95,6 +96,7 @@ public: } T BlockUntilReady() { + _dbg_assert_(this != nullptr); std::lock_guard guard(readyMutex_); if (ready_) { return data_; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index 42205de0e7..db1d886b1f 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -36,8 +36,11 @@ #define WRITE(p, ...) p.F(__VA_ARGS__) -bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, std::string *errorString) { +bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString) { *uniformMask = 0; + if (fragmentShaderFlags) { + *fragmentShaderFlags = (FragmentShaderFlags)0; + } errorString->clear(); bool highpFog = false; diff --git a/GPU/Common/FragmentShaderGenerator.h b/GPU/Common/FragmentShaderGenerator.h index b459543a50..325c368f73 100644 --- a/GPU/Common/FragmentShaderGenerator.h +++ b/GPU/Common/FragmentShaderGenerator.h @@ -39,4 +39,9 @@ struct FShaderID; // For stencil upload #define CONST_PS_STENCILVALUE 11 -bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, std::string *errorString); +// Can technically be deduced from the fragment shader ID, but this is safer. +enum FragmentShaderFlags { + FS_FLAG_INPUT_ATTACHMENT, +}; + +bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString); diff --git a/GPU/D3D11/ShaderManagerD3D11.cpp b/GPU/D3D11/ShaderManagerD3D11.cpp index 34c8980ad0..a8537c8545 100644 --- a/GPU/D3D11/ShaderManagerD3D11.cpp +++ b/GPU/D3D11/ShaderManagerD3D11.cpp @@ -224,7 +224,7 @@ void ShaderManagerD3D11::GetShaders(int prim, u32 vertType, D3D11VertexShader ** // Fragment shader not in cache. Let's compile it. std::string genErrorString; uint64_t uniformMask; - GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &genErrorString); + GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &genErrorString); fs = new D3D11FragmentShader(device_, featureLevel_, FSID, codeBuffer_, useHWTransform); fsCache_[FSID] = fs; } else { diff --git a/GPU/Directx9/ShaderManagerDX9.cpp b/GPU/Directx9/ShaderManagerDX9.cpp index 1700206a02..6e20ec45e0 100644 --- a/GPU/Directx9/ShaderManagerDX9.cpp +++ b/GPU/Directx9/ShaderManagerDX9.cpp @@ -623,7 +623,7 @@ VSShader *ShaderManagerDX9::ApplyShader(bool useHWTransform, bool useHWTessellat // Fragment shader not in cache. Let's compile it. std::string errorString; uint64_t uniformMask; - bool success = GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &errorString); + bool success = GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &errorString); // We're supposed to handle all possible cases. _assert_(success); fs = new PSShader(device_, FSID, codeBuffer_); diff --git a/GPU/GLES/ShaderManagerGLES.cpp b/GPU/GLES/ShaderManagerGLES.cpp index a1ae7edb61..2780fa7799 100644 --- a/GPU/GLES/ShaderManagerGLES.cpp +++ b/GPU/GLES/ShaderManagerGLES.cpp @@ -709,7 +709,7 @@ void ShaderManagerGLES::DirtyLastShader() { Shader *ShaderManagerGLES::CompileFragmentShader(FShaderID FSID) { uint64_t uniformMask; std::string errorString; - if (!GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, &errorString)) { + if (!GenerateFragmentShader(FSID, codeBuffer_, draw_->GetShaderLanguageDesc(), draw_->GetBugs(), &uniformMask, nullptr, &errorString)) { ERROR_LOG(G3D, "Shader gen error: %s", errorString.c_str()); return nullptr; } diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 0ada8b9b06..9bf95b59b7 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -768,9 +768,7 @@ void DrawEngineVulkan::DoFlush() { } _dbg_assert_msg_(vshader->UseHWTransform(), "Bad vshader"); - Draw::NativeObject object = framebufferManager_->UseBufferedRendering() ? Draw::NativeObject::FRAMEBUFFER_RENDERPASS : Draw::NativeObject::BACKBUFFER_RENDERPASS; - VkRenderPass renderPass = (VkRenderPass)draw_->GetNativeObject(object); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, renderPass, pipelineKey_, &dec_->decFmt, vshader, fshader, true); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, true); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. return; @@ -895,9 +893,7 @@ void DrawEngineVulkan::DoFlush() { } shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat); // usehwtransform _dbg_assert_msg_(!vshader->UseHWTransform(), "Bad vshader"); - Draw::NativeObject object = framebufferManager_->UseBufferedRendering() ? Draw::NativeObject::FRAMEBUFFER_RENDERPASS : Draw::NativeObject::BACKBUFFER_RENDERPASS; - VkRenderPass renderPass = (VkRenderPass)draw_->GetNativeObject(object); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, renderPass, pipelineKey_, &dec_->decFmt, vshader, fshader, false); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, false); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. decodedVerts_ = 0; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 8909283884..a8b3f327bf 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -35,16 +35,20 @@ void PipelineManagerVulkan::Clear() { // store the keys. pipelines_.Iterate([&](const VulkanPipelineKey &key, VulkanPipeline *value) { - if (value->pipeline) { - VkPipeline pipeline = value->pipeline->pipeline->BlockUntilReady(); - vulkan_->Delete().QueueDeletePipeline(pipeline); - vulkan_->Delete().QueueCallback([](void *p) { - VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; - delete pipeline; - }, value->pipeline); - } else { - // Something went wrong. - ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (value->pipeline) { + if (value->pipeline->pipeline[i]) { + VkPipeline pipeline = value->pipeline->pipeline[i]->BlockUntilReady(); + vulkan_->Delete().QueueDeletePipeline(pipeline); + vulkan_->Delete().QueueCallback([](void *p) { + VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; + delete pipeline; + }, value->pipeline); + } + } else { + // Something went wrong. + ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); + } } delete value; }); @@ -175,7 +179,7 @@ static std::string CutFromMain(std::string str) { } static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, VkPipelineCache pipelineCache, - VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &key, + VkPipelineLayout layout, const VulkanPipelineRasterStateKey &key, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { VKRGraphicsPipelineDesc *desc = new VKRGraphicsPipelineDesc(); desc->pipelineCache = pipelineCache; @@ -298,27 +302,7 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, views.pViewports = nullptr; // dynamic views.pScissors = nullptr; // dynamic - VkGraphicsPipelineCreateInfo &pipe = desc->pipe; - pipe.flags = 0; - pipe.stageCount = 2; - pipe.basePipelineIndex = 0; - - pipe.pColorBlendState = &desc->cbs; - pipe.pDepthStencilState = &desc->dss; - pipe.pRasterizationState = &desc->rs; - - // We will use dynamic viewport state. - pipe.pVertexInputState = &desc->vis; - pipe.pViewportState = &desc->views; - pipe.pTessellationState = nullptr; - pipe.pDynamicState = &desc->ds; - pipe.pInputAssemblyState = &desc->inputAssembly; - pipe.pMultisampleState = &desc->ms; - pipe.layout = layout; - pipe.basePipelineHandle = VK_NULL_HANDLE; - pipe.basePipelineIndex = 0; - pipe.renderPass = renderPass; - pipe.subpass = 0; + desc->pipelineLayout = layout; VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc); @@ -335,7 +319,7 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, return vulkanPipeline; } -VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { if (!pipelineCache_) { VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; VkResult res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_); @@ -343,10 +327,8 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager * } VulkanPipelineKey key{}; - _assert_msg_(renderPass, "Can't create a pipeline with a null renderpass"); key.raster = rasterKey; - key.renderPass = renderPass; key.useHWTransform = useHwTransform; key.vShader = vs->GetModule(); key.fShader = fs->GetModule(); @@ -357,7 +339,7 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager * return iter; VulkanPipeline *pipeline = CreateVulkanPipeline( - renderManager, pipelineCache_, layout, renderPass, + renderManager, pipelineCache_, layout, rasterKey, decFmt, vs, fs, useHwTransform); pipelines_.Insert(key, pipeline); @@ -565,8 +547,6 @@ struct StoredVulkanPipelineKey { FShaderID fShaderID; uint32_t vtxFmtId; bool useHWTransform; - bool backbufferPass; - VulkanQueueRunner::RPKey renderPassKey; // For std::set. Better zero-initialize the struct properly for this to work. bool operator < (const StoredVulkanPipelineKey &other) const { @@ -627,14 +607,6 @@ void PipelineManagerVulkan::SaveCache(FILE *file, bool saveRawPipelineCache, Sha // NOTE: This is not a vtype, but a decoded vertex format. key.vtxFmtId = pkey.vtxFmtId; } - // Figure out what kind of renderpass this pipeline uses. - if (pkey.renderPass == queueRunner->GetBackbufferRenderPass()) { - key.backbufferPass = true; - key.renderPassKey = {}; - } else { - key.backbufferPass = false; - queueRunner->GetRenderPassKey(pkey.renderPass, &key.renderPassKey); - } keys.insert(key); }); @@ -740,18 +712,9 @@ bool PipelineManagerVulkan::LoadCache(FILE *file, bool loadRawPipelineCache, Sha continue; } - VkRenderPass rp; - if (key.backbufferPass) { - rp = queueRunner->GetBackbufferRenderPass(); - } else { - rp = queueRunner->GetRenderPass(key.renderPassKey); - } - DecVtxFormat fmt; fmt.InitializeFromID(key.vtxFmtId); - VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, rp, key.raster, - key.useHWTransform ? &fmt : 0, - vs, fs, key.useHWTransform); + VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, key.raster, key.useHWTransform ? &fmt : 0, vs, fs, key.useHWTransform); if (!pipeline) { pipelineCreateFailCount += 1; } diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index a6ab695cef..5c90723518 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -34,7 +34,7 @@ class VulkanRenderManager; struct VulkanPipelineKey { VulkanPipelineRasterStateKey raster; // prim is included here - VkRenderPass renderPass; + VKRRenderPass *renderPass; Promise *vShader; Promise *fShader; uint32_t vtxFmtId; @@ -71,7 +71,7 @@ public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); - VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, VkRenderPass renderPass, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); + VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); int GetNumPipelines() const { return (int)pipelines_.size(); } void Clear(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index eb30aa4728..3d9074a259 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -89,8 +89,8 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade } -VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, const char *code) - : vulkan_(vulkan), id_(id) { +VulkanFragmentShader::VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, FragmentShaderFlags flags, const char *code) + : vulkan_(vulkan), id_(id), flags_(flags) { source_ = code; module_ = CompileShaderModuleAsync(vulkan, VK_SHADER_STAGE_FRAGMENT_BIT, source_.c_str()); if (!module_) { @@ -276,9 +276,10 @@ void ShaderManagerVulkan::GetShaders(int prim, u32 vertType, VulkanVertexShader // Fragment shader not in cache. Let's compile it. std::string genErrorString; uint64_t uniformMask = 0; // Not used - bool success = GenerateFragmentShader(FSID, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &genErrorString); + FragmentShaderFlags flags; + bool success = GenerateFragmentShader(FSID, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &flags, &genErrorString); _assert_msg_(success, "FS gen error: %s", genErrorString.c_str()); - fs = new VulkanFragmentShader(vulkan, FSID, codeBuffer_); + fs = new VulkanFragmentShader(vulkan, FSID, flags, codeBuffer_); fsCache_.Insert(FSID, fs); } @@ -370,7 +371,7 @@ VulkanFragmentShader *ShaderManagerVulkan::GetFragmentShaderFromModule(VkShaderM // instantaneous. #define CACHE_HEADER_MAGIC 0xff51f420 -#define CACHE_VERSION 22 +#define CACHE_VERSION 24 struct VulkanCacheHeader { uint32_t magic; uint32_t version; @@ -390,6 +391,10 @@ bool ShaderManagerVulkan::LoadCache(FILE *f) { if (header.featureFlags != gstate_c.featureFlags) return false; + // Temporarily disable shader cache. + if (true) + return false; + VulkanContext *vulkan = (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT); for (int i = 0; i < header.numVertexShaders; i++) { VShaderID id; @@ -417,10 +422,11 @@ bool ShaderManagerVulkan::LoadCache(FILE *f) { } std::string genErrorString; uint64_t uniformMask = 0; - if (!GenerateFragmentShader(id, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &genErrorString)) { + FragmentShaderFlags flags; + if (!GenerateFragmentShader(id, codeBuffer_, compat_, draw_->GetBugs(), &uniformMask, &flags, &genErrorString)) { return false; } - VulkanFragmentShader *fs = new VulkanFragmentShader(vulkan, id, codeBuffer_); + VulkanFragmentShader *fs = new VulkanFragmentShader(vulkan, id, flags, codeBuffer_); fsCache_.Insert(id, fs); } diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index 50915be6a2..6593a366f4 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -36,7 +36,7 @@ class VulkanPushBuffer; class VulkanFragmentShader { public: - VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, const char *code); + VulkanFragmentShader(VulkanContext *vulkan, FShaderID id, FragmentShaderFlags flags, const char *code); ~VulkanFragmentShader(); const std::string &source() const { return source_; } @@ -45,7 +45,9 @@ public: std::string GetShaderString(DebugShaderStringType type) const; Promise *GetModule() { return module_; } - const FShaderID &GetID() { return id_; } + const FShaderID &GetID() const { return id_; } + + FragmentShaderFlags Flags() const { return flags_; } protected: Promise *module_ = nullptr; @@ -54,6 +56,7 @@ protected: std::string source_; bool failed_ = false; FShaderID id_; + FragmentShaderFlags flags_; }; class VulkanVertexShader { @@ -68,7 +71,7 @@ public: std::string GetShaderString(DebugShaderStringType type) const; Promise *GetModule() { return module_; } - const VShaderID &GetID() { return id_; } + const VShaderID &GetID() const { return id_; } protected: Promise *module_ = nullptr; diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index d90d893ff3..7bdb0b3e8c 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -30,27 +30,27 @@ bool GenerateFShader(FShaderID id, char *buffer, ShaderLanguage lang, Draw::Bugs case ShaderLanguage::GLSL_VULKAN: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_VULKAN); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::GLSL_1xx: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_1xx); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::GLSL_3xx: { ShaderLanguageDesc compat(ShaderLanguage::GLSL_1xx); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::HLSL_D3D9: { ShaderLanguageDesc compat(ShaderLanguage::HLSL_D3D9); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } case ShaderLanguage::HLSL_D3D11: { ShaderLanguageDesc compat(ShaderLanguage::HLSL_D3D11); - return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, errorString); + return GenerateFragmentShader(id, buffer, compat, bugs, &uniformMask, nullptr, errorString); } default: return false; From 80ca822bf2c3bb4eb98c510390e4e14b71073da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 12:37:45 +0200 Subject: [PATCH 030/110] Create framebuffer variants on demand --- Common/GPU/Vulkan/VulkanQueueRunner.cpp | 36 ++++++++-------- Common/GPU/Vulkan/VulkanRenderManager.cpp | 51 +++++++++++++---------- Common/GPU/Vulkan/VulkanRenderManager.h | 26 ++++++++---- Common/GPU/Vulkan/thin3d_vulkan.cpp | 6 ++- 4 files changed, 69 insertions(+), 50 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index fc9d34ec8d..618fecaf0d 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -615,13 +615,13 @@ std::string VulkanQueueRunner::StepToString(const VKRStep &step) const { break; } case VKRStepType::COPY: - snprintf(buffer, sizeof(buffer), "COPY '%s' %s -> %s (%dx%d, %s)", step.tag, step.copy.src->tag.c_str(), step.copy.dst->tag.c_str(), step.copy.srcRect.extent.width, step.copy.srcRect.extent.height, AspectToString(step.copy.aspectMask)); + snprintf(buffer, sizeof(buffer), "COPY '%s' %s -> %s (%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.copy.srcRect.extent.width, step.copy.srcRect.extent.height, AspectToString(step.copy.aspectMask)); break; case VKRStepType::BLIT: - snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->tag.c_str(), step.copy.dst->tag.c_str(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask)); + snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask)); break; case VKRStepType::READBACK: - snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src->tag.c_str(), step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask)); + snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src->Tag(), step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask)); break; case VKRStepType::READBACK_IMAGE: snprintf(buffer, sizeof(buffer), "READBACK_IMAGE '%s' (%dx%d)", step.tag, step.readback_image.srcRect.extent.width, step.readback_image.srcRect.extent.height); @@ -780,14 +780,14 @@ const char *ImageLayoutToString(VkImageLayout layout) { void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) { const auto &r = pass.render; - const char *framebuf = r.framebuffer ? r.framebuffer->tag.c_str() : "backbuffer"; + const char *framebuf = r.framebuffer ? r.framebuffer->Tag() : "backbuffer"; int w = r.framebuffer ? r.framebuffer->width : vulkan_->GetBackbufferWidth(); int h = r.framebuffer ? r.framebuffer->height : vulkan_->GetBackbufferHeight(); INFO_LOG(G3D, "RENDER %s Begin(%s, draws: %d, %dx%d, %s, %s, %s)", pass.tag, framebuf, r.numDraws, w, h, RenderPassActionName(r.colorLoad), RenderPassActionName(r.depthLoad), RenderPassActionName(r.stencilLoad)); // TODO: Log these in detail. for (int i = 0; i < (int)pass.preTransitions.size(); i++) { - INFO_LOG(G3D, " PRETRANSITION: %s %s -> %s", pass.preTransitions[i].fb->tag.c_str(), AspectToString(pass.preTransitions[i].aspect), ImageLayoutToString(pass.preTransitions[i].targetLayout)); + INFO_LOG(G3D, " PRETRANSITION: %s %s -> %s", pass.preTransitions[i].fb->Tag(), AspectToString(pass.preTransitions[i].aspect), ImageLayoutToString(pass.preTransitions[i].targetLayout)); } if (verbose) { @@ -1317,8 +1317,14 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step _dbg_assert_(step.render.finalColorLayout != VK_IMAGE_LAYOUT_UNDEFINED); _dbg_assert_(step.render.finalDepthStencilLayout != VK_IMAGE_LAYOUT_UNDEFINED); + RPKey key{ + step.render.colorLoad, step.render.depthLoad, step.render.stencilLoad, + step.render.colorStore, step.render.depthStore, step.render.stencilStore, + }; + renderPass = GetRenderPass(key); + VKRFramebuffer *fb = step.render.framebuffer; - framebuf = fb->framebuf[step.render.renderPassType]; + framebuf = fb->Get(renderPass, step.render.renderPassType); w = fb->width; h = fb->height; @@ -1340,12 +1346,6 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step TransitionToOptimal(cmd, fb->color.image, fb->color.layout, fb->depth.image, fb->depth.layout, &recordBarrier_); - RPKey key{ - step.render.colorLoad, step.render.depthLoad, step.render.stencilLoad, - step.render.colorStore, step.render.depthStore, step.render.stencilStore, - }; - renderPass = GetRenderPass(key); - // The transition from the optimal format happens after EndRenderPass, now that we don't // do it as part of the renderpass itself anymore. @@ -1359,18 +1359,18 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step numClearVals = 2; } } else { - framebuf = backbuffer_; - - // Raw, rotated backbuffer size. - w = vulkan_->GetBackbufferWidth(); - h = vulkan_->GetBackbufferHeight(); - RPKey key{ VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, }; renderPass = GetRenderPass(key); + framebuf = backbuffer_; + + // Raw, rotated backbuffer size. + w = vulkan_->GetBackbufferWidth(); + h = vulkan_->GetBackbufferHeight(); + Uint8x4ToFloat4(clearVal[0].color.float32, step.render.clearColor); numClearVals = 2; // We don't bother with a depth buffer here. clearVal[1].depthStencil.depth = 0.0f; diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 8d5593d539..bbbc7d6f6d 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -129,36 +129,43 @@ bool VKRComputePipeline::Create(VulkanContext *vulkan) { return success; } -VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag) : vulkan_(vk) { +VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag) : vulkan_(vk), tag_(tag) { width = _width; height = _height; CreateImage(vulkan_, initCmd, color, width, height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, true, tag); CreateImage(vulkan_, initCmd, depth, width, height, vulkan_->GetDeviceInfo().preferredDepthStencilFormat, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, false, tag); - for (int i = 0; i < RP_TYPE_COUNT; i++) { - VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; - VkImageView views[2]{}; + // We create the actual framebuffer objects on demand, because some combinations might not make sense. +} - fbci.renderPass = compatibleRenderPass->pass[i]; - fbci.attachmentCount = 2; - fbci.pAttachments = views; - views[0] = color.imageView; - views[1] = depth.imageView; - fbci.width = width; - fbci.height = height; - fbci.layers = 1; - - VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf[i]); - _assert_(res == VK_SUCCESS); - - if (tag && vk->Extensions().EXT_debug_utils) { - vk->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag).c_str()); - vk->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag).c_str()); - vk->SetDebugName(framebuf[i], VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag).c_str()); - this->tag = tag; - } +VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPassType renderPassType) { + if (framebuf[(int)renderPassType]) { + return framebuf[(int)renderPassType]; } + + VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; + VkImageView views[2]{}; + + fbci.renderPass = compatibleRenderPass->pass[(int)renderPassType]; + fbci.attachmentCount = 2; + fbci.pAttachments = views; + views[0] = color.imageView; + views[1] = depth.imageView; + fbci.width = width; + fbci.height = height; + fbci.layers = 1; + + VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf[(int)renderPassType]); + _assert_(res == VK_SUCCESS); + + if (!tag_.empty() && vulkan_->Extensions().EXT_debug_utils) { + vulkan_->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_color_%s", tag_.c_str()).c_str()); + vulkan_->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, StringFromFormat("fb_depth_%s", tag_.c_str()).c_str()); + vulkan_->SetDebugName(framebuf[(int)renderPassType], VK_OBJECT_TYPE_FRAMEBUFFER, StringFromFormat("fb_%s", tag_.c_str()).c_str()); + } + + return framebuf[(int)renderPassType]; } VKRFramebuffer::~VKRFramebuffer() { diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index 808418c470..191f9d33e7 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -46,14 +46,23 @@ public: VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, const char *tag); ~VKRFramebuffer(); - VkFramebuffer framebuf[RP_TYPE_COUNT]{}; - VKRImage color{}; - VKRImage depth{}; + VkFramebuffer Get(VKRRenderPass *compatibleRenderPass, RenderPassType rpType); + int width = 0; int height = 0; + VKRImage color{}; + VKRImage depth{}; + const char *Tag() const { + return tag_.c_str(); + } + + // TODO: Hide. VulkanContext *vulkan_; - std::string tag; +private: + VkFramebuffer framebuf[RP_TYPE_COUNT]{}; + + std::string tag_; }; enum class VKRRunType { @@ -124,8 +133,8 @@ struct VKRGraphicsPipelineDesc { VkPipelineMultisampleStateCreateInfo ms{ VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; // Replaced the ShaderStageInfo with promises here so we can wait for compiles to finish. - Promise *vertexShader; - Promise *fragmentShader; + Promise *vertexShader = nullptr; + Promise *fragmentShader = nullptr; VkPipelineInputAssemblyStateCreateInfo inputAssembly{ VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; VkVertexInputAttributeDescription attrs[8]{}; @@ -133,11 +142,11 @@ struct VKRGraphicsPipelineDesc { VkPipelineVertexInputStateCreateInfo vis{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; VkPipelineViewportStateCreateInfo views{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; - VkPipelineLayout pipelineLayout; + VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; // Does not include the render pass type, it's passed in separately since the // desc is persistent. - RPKey rpKey; + RPKey rpKey{}; }; // All the data needed to create a compute pipeline. @@ -239,6 +248,7 @@ public: // Deferred creation, like in GL. Unlike GL though, the purpose is to allow background creation and avoiding // stalling the emulation thread as much as possible. // We delay creating pipelines until the end of the current render pass, so we can create the right type immediately. + // WARNING: desc must stick around! It's not enough to build it on the stack. VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc) { VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); _dbg_assert_(desc->vertexShader); diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 388939854c..418050fe20 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -273,6 +273,7 @@ public: } VKRGraphicsPipeline *pipeline = nullptr; + VKRGraphicsPipelineDesc vkrDesc; PipelineFlags flags; int stride[4]{}; @@ -1041,7 +1042,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { VKPipeline *pipeline = new VKPipeline(&renderManager_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); - VKRGraphicsPipelineDesc gDesc{}; + VKRGraphicsPipelineDesc &gDesc = pipeline->vkrDesc; std::vector stages; stages.resize(desc.shaders.size()); @@ -1079,6 +1080,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { gDesc.blend0 = blend->attachments[0]; gDesc.cbs = blend->info; + gDesc.cbs.pAttachments = &gDesc.blend0; gDesc.dss = depth->info; @@ -1090,7 +1092,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { // We treat the three stencil states as a unit in other places, so let's do that here too. const VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK }; gDesc.ds.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2; - for (int i = 0; i < gDesc.ds.dynamicStateCount; i++) { + for (size_t i = 0; i < gDesc.ds.dynamicStateCount; i++) { gDesc.dynamicStates[i] = dynamics[i]; } gDesc.ds.pDynamicStates = gDesc.dynamicStates; From 7ab7440475062bdabe9725a4ad3f11a4179570c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 12:48:16 +0200 Subject: [PATCH 031/110] Also create renderpass variants on demand --- Common/GPU/Vulkan/VulkanQueueRunner.cpp | 33 ++++++++++++----------- Common/GPU/Vulkan/VulkanQueueRunner.h | 26 +++++++++++++----- Common/GPU/Vulkan/VulkanRenderManager.cpp | 6 ++--- 3 files changed, 39 insertions(+), 26 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index 618fecaf0d..c3ed8e336b 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -120,9 +120,7 @@ void VulkanQueueRunner::DestroyDeviceObjects() { renderPasses_.IterateMut([&](const RPKey &rpkey, VKRRenderPass *rp) { _assert_(rp); - for (int i = 0; i < RP_TYPE_COUNT; i++) { - vulkan_->Delete().QueueDeleteRenderPass(rp->pass[i]); - } + rp->Destroy(vulkan_); delete rp; }); renderPasses_.Clear(); @@ -145,9 +143,9 @@ static VkAttachmentStoreOp ConvertStoreAction(VKRRenderPassStoreAction action) { return VK_ATTACHMENT_STORE_OP_DONT_CARE; // avoid compiler warning } -VkRenderPass VulkanQueueRunner::CreateRP(const RPKey &key, RenderPassType rpType) { +VkRenderPass CreateRP(VulkanContext *vulkan, const RPKey &key, RenderPassType rpType) { VkAttachmentDescription attachments[2] = {}; - attachments[0].format = rpType == RP_TYPE_BACKBUFFER ? vulkan_->GetSwapchainFormat() : VK_FORMAT_R8G8B8A8_UNORM; + attachments[0].format = rpType == RP_TYPE_BACKBUFFER ? vulkan->GetSwapchainFormat() : VK_FORMAT_R8G8B8A8_UNORM; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = ConvertLoadAction(key.colorLoadAction); attachments[0].storeOp = ConvertStoreAction(key.colorStoreAction); @@ -157,7 +155,7 @@ VkRenderPass VulkanQueueRunner::CreateRP(const RPKey &key, RenderPassType rpType attachments[0].finalLayout = rpType == RP_TYPE_BACKBUFFER ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachments[0].flags = 0; - attachments[1].format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat; + attachments[1].format = vulkan->GetDeviceInfo().preferredDepthStencilFormat; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = ConvertLoadAction(key.depthLoadAction); attachments[1].storeOp = ConvertStoreAction(key.depthStoreAction); @@ -207,12 +205,22 @@ VkRenderPass VulkanQueueRunner::CreateRP(const RPKey &key, RenderPassType rpType } VkRenderPass pass; - VkResult res = vkCreateRenderPass(vulkan_->GetDevice(), &rp, nullptr, &pass); + VkResult res = vkCreateRenderPass(vulkan->GetDevice(), &rp, nullptr, &pass); _assert_(res == VK_SUCCESS); _assert_(pass != VK_NULL_HANDLE); return pass; } +VkRenderPass VKRRenderPass::Get(VulkanContext *vulkan, RenderPassType rpType) { + // When we create a render pass, we create all "types" of it immediately, + // practical later when referring to it. Could change to on-demand if it feels motivated + // but I think the render pass objects are cheap. + if (!pass[(int)rpType]) { + pass[(int)rpType] = CreateRP(vulkan, key_, (RenderPassType)rpType); + } + return pass[(int)rpType]; +} + // Self-dependency: https://github.com/gpuweb/gpuweb/issues/442#issuecomment-547604827 // Also see https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies VKRRenderPass *VulkanQueueRunner::GetRenderPass(const RPKey &key) { @@ -221,14 +229,7 @@ VKRRenderPass *VulkanQueueRunner::GetRenderPass(const RPKey &key) { return foundPass; } - VKRRenderPass *pass = new VKRRenderPass(); - // When we create a render pass, we create all "types" of it immediately, - // practical later when referring to it. Could change to on-demand if it feels motivated - // but I think the render pass objects are cheap. - for (int i = 0; i < RP_TYPE_COUNT; i++) { - pass->pass[i] = CreateRP(key, (RenderPassType)i); - } - + VKRRenderPass *pass = new VKRRenderPass(key); renderPasses_.Insert(key, pass); return pass; } @@ -1378,7 +1379,7 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step } VkRenderPassBeginInfo rp_begin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; - rp_begin.renderPass = renderPass->pass[(int)step.render.renderPassType]; + rp_begin.renderPass = renderPass->Get(vulkan_, step.render.renderPassType); rp_begin.framebuffer = framebuf; VkRect2D rc = step.render.renderArea; diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.h b/Common/GPU/Vulkan/VulkanQueueRunner.h index eb1423132e..0e97879658 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.h +++ b/Common/GPU/Vulkan/VulkanQueueRunner.h @@ -155,7 +155,7 @@ struct QueueProfileContext { double cpuEndTime; }; -struct VKRRenderPass; +class VKRRenderPass; struct VKRStep { VKRStep(VKRStepType _type) : stepType(_type) {} @@ -218,10 +218,6 @@ struct VKRStep { }; }; -struct VKRRenderPass { - VkRenderPass pass[RP_TYPE_COUNT]; -}; - struct RPKey { // Only render-pass-compatibility-volatile things can be here. VKRRenderPassLoadAction colorLoadAction; @@ -232,6 +228,24 @@ struct RPKey { VKRRenderPassStoreAction stencilStoreAction; }; +class VKRRenderPass { +public: + VKRRenderPass(const RPKey &key) : key_(key) {} + + VkRenderPass Get(VulkanContext *vulkan, RenderPassType rpType); + void Destroy(VulkanContext *vulkan) { + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (pass[i]) { + vulkan->Delete().QueueDeleteRenderPass(pass[i]); + } + } + } + +private: + VkRenderPass pass[RP_TYPE_COUNT]{}; + RPKey key_; +}; + class VulkanQueueRunner { public: VulkanQueueRunner(VulkanContext *vulkan) : vulkan_(vulkan), renderPasses_(16) {} @@ -289,8 +303,6 @@ public: } private: - VkRenderPass CreateRP(const RPKey &key, RenderPassType rpType); - void PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); void PerformRenderPass(const VKRStep &pass, VkCommandBuffer cmd); void PerformCopy(const VKRStep &pass, VkCommandBuffer cmd); diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index bbbc7d6f6d..899bd56655 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -147,7 +147,7 @@ VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPas VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; VkImageView views[2]{}; - fbci.renderPass = compatibleRenderPass->pass[(int)renderPassType]; + fbci.renderPass = compatibleRenderPass->Get(vulkan_, renderPassType); fbci.attachmentCount = 2; fbci.pAttachments = views; views[0] = color.imageView; @@ -715,7 +715,7 @@ void VulkanRenderManager::EndCurRenderStep() { compileMutex_.lock(); for (VKRGraphicsPipeline *pipeline : pipelinesToCreate_) { pipeline->pipeline[rpType] = Promise::CreateEmpty(); - compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->pass[rpType], rpType)); + compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType)); } compileCond_.notify_one(); compileMutex_.unlock(); @@ -961,7 +961,7 @@ bool VulkanRenderManager::InitBackbufferFramebuffers(int width, int height) { VLOG("InitFramebuffers: %dx%d", width, height); VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; - fb_info.renderPass = queueRunner_.GetCompatibleRenderPass()->pass[RP_TYPE_BACKBUFFER]; + fb_info.renderPass = queueRunner_.GetCompatibleRenderPass()->Get(vulkan_, RP_TYPE_BACKBUFFER); fb_info.attachmentCount = 2; fb_info.pAttachments = attachments; fb_info.width = width; From befcfb470c8e4410ea393bb676fda5a76cad7784 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 15:19:20 +0200 Subject: [PATCH 032/110] Fix shader caching. --- Common/GPU/Vulkan/VulkanRenderManager.cpp | 53 ++++++++++++++++++++--- Common/GPU/Vulkan/VulkanRenderManager.h | 34 ++++++++------- Common/GPU/Vulkan/thin3d_vulkan.cpp | 2 +- GPU/Common/TextureCacheCommon.cpp | 5 +-- GPU/Vulkan/DrawEngineVulkan.cpp | 4 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 25 ++++++----- GPU/Vulkan/PipelineManagerVulkan.h | 5 ++- GPU/Vulkan/ShaderManagerVulkan.cpp | 6 +-- 8 files changed, 91 insertions(+), 43 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 899bd56655..21a444f894 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -693,6 +693,48 @@ VkCommandBuffer VulkanRenderManager::GetInitCmd() { return frameData_[curFrame].initCmd; } +VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask) { + VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); + _dbg_assert_(desc->vertexShader); + _dbg_assert_(desc->fragmentShader); + pipeline->desc = desc; + if (curRenderStep_) { + // The common case + pipelinesToCheck_.push_back(pipeline); + } else { + if (!variantBitmask) { + WARN_LOG(G3D, "WARNING: Will not compile any variants of pipeline, not in renderpass and empty variantBitmask"); + } + // Presumably we're in initialization, loading the shader cache. + // Look at variantBitmask to see what variants we should queue up. + RPKey key{ + VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, + VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE, + }; + VKRRenderPass *compatibleRenderPass = queueRunner_.GetRenderPass(key); + compileMutex_.lock(); + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (!(variantBitmask & (1 << i))) + continue; + RenderPassType rpType = (RenderPassType)i; + pipeline->pipeline[rpType] = Promise::CreateEmpty(); + compileQueue_.push_back(CompileQueueEntry(pipeline, compatibleRenderPass->Get(vulkan_, rpType), rpType)); + } + compileMutex_.unlock(); + } + return pipeline; +} + +VKRComputePipeline *VulkanRenderManager::CreateComputePipeline(VKRComputePipelineDesc *desc) { + VKRComputePipeline *pipeline = new VKRComputePipeline(); + pipeline->desc = desc; + compileMutex_.lock(); + compileQueue_.push_back(CompileQueueEntry(pipeline)); + compileCond_.notify_one(); + compileMutex_.unlock(); + return pipeline; +} + void VulkanRenderManager::EndCurRenderStep() { if (!curRenderStep_) return; @@ -713,13 +755,15 @@ void VulkanRenderManager::EndCurRenderStep() { // Save the accumulated pipeline flags so we can use that to configure the render pass. // We'll often be able to avoid loading/saving the depth/stencil buffer. compileMutex_.lock(); - for (VKRGraphicsPipeline *pipeline : pipelinesToCreate_) { - pipeline->pipeline[rpType] = Promise::CreateEmpty(); - compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType)); + for (VKRGraphicsPipeline *pipeline : pipelinesToCheck_) { + if (!pipeline->pipeline[rpType]) { + pipeline->pipeline[rpType] = Promise::CreateEmpty(); + compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType)); + } } compileCond_.notify_one(); compileMutex_.unlock(); - pipelinesToCreate_.clear(); + pipelinesToCheck_.clear(); // We don't do this optimization for very small targets, probably not worth it. if (!curRenderArea_.Empty() && (curWidth_ > 32 && curHeight_ > 32)) { @@ -959,7 +1003,6 @@ bool VulkanRenderManager::InitBackbufferFramebuffers(int width, int height) { // We share the same depth buffer but have multiple color buffers, see the loop below. VkImageView attachments[2] = { VK_NULL_HANDLE, depth_.view }; - VLOG("InitFramebuffers: %dx%d", width, height); VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; fb_info.renderPass = queueRunner_.GetCompatibleRenderPass()->Get(vulkan_, RP_TYPE_BACKBUFFER); fb_info.attachmentCount = 2; diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index 191f9d33e7..24a3fca123 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -166,6 +166,16 @@ struct VKRGraphicsPipeline { delete desc; } + u32 GetVariantsBitmask() const { + u32 bitmask = 0; + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (pipeline[i]) { + bitmask |= 1 << i; + } + } + return bitmask; + } + VKRGraphicsPipelineDesc *desc = nullptr; Promise *pipeline[RP_TYPE_COUNT]; @@ -248,30 +258,22 @@ public: // Deferred creation, like in GL. Unlike GL though, the purpose is to allow background creation and avoiding // stalling the emulation thread as much as possible. // We delay creating pipelines until the end of the current render pass, so we can create the right type immediately. - // WARNING: desc must stick around! It's not enough to build it on the stack. - VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc) { - VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); - _dbg_assert_(desc->vertexShader); - _dbg_assert_(desc->fragmentShader); - pipeline->desc = desc; - pipelinesToCreate_.push_back(pipeline); - return pipeline; - } + // Unless a variantBitmask is passed in, in which case we can just go ahead. + // WARNING: desc must stick around during the lifetime of the pipeline! It's not enough to build it on the stack and drop it. + VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask); + VKRComputePipeline *CreateComputePipeline(VKRComputePipelineDesc *desc); - VKRComputePipeline *CreateComputePipeline(VKRComputePipelineDesc *desc) { - VKRComputePipeline *pipeline = new VKRComputePipeline(); - pipeline->desc = desc; + void NudgeCompilerThread() { compileMutex_.lock(); - compileQueue_.push_back(CompileQueueEntry(pipeline)); compileCond_.notify_one(); compileMutex_.unlock(); - return pipeline; } void BindPipeline(VKRGraphicsPipeline *pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) { _dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER); _dbg_assert_(pipeline != nullptr); VkRenderData data{ VKRRenderCommand::BIND_GRAPHICS_PIPELINE }; + pipelinesToCheck_.push_back(pipeline); data.graphics_pipeline.pipeline = pipeline; data.graphics_pipeline.pipelineLayout = pipelineLayout; curPipelineFlags_ |= flags; @@ -577,8 +579,8 @@ private: std::mutex compileMutex_; std::vector compileQueue_; - // pipelines to create at the end of the current render pass. - std::vector pipelinesToCreate_; + // pipelines to check and possibly create at the end of the current render pass. + std::vector pipelinesToCheck_; // Swap chain management struct SwapchainImageData { diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 418050fe20..d456aadcfb 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -1110,7 +1110,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; raster->ToVulkan(&gDesc.rs); - pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc);; + pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER); if (desc.uniformDesc) { pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 36c34e20a4..8d58346a8c 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1866,10 +1866,9 @@ static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferForma return true; } break; - default: - WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); - return false; } + WARN_LOG(G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat)); + return false; } else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) { // We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491). return true; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 9bf95b59b7..8f4cecfd81 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -768,7 +768,7 @@ void DrawEngineVulkan::DoFlush() { } _dbg_assert_msg_(vshader->UseHWTransform(), "Bad vshader"); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, true); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, true, 0); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. return; @@ -893,7 +893,7 @@ void DrawEngineVulkan::DoFlush() { } shaderManager_->GetShaders(prim, lastVType_, &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat); // usehwtransform _dbg_assert_msg_(!vshader->UseHWTransform(), "Bad vshader"); - VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, false); + VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, false, 0); if (!pipeline || !pipeline->pipeline) { // Already logged, let's bail out. decodedVerts_ = 0; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index a8b3f327bf..76423fae84 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -18,6 +18,10 @@ using namespace PPSSPP_VK; +u32 VulkanPipeline::GetVariantsBitmask() const { + return pipeline->GetVariantsBitmask(); +} + PipelineManagerVulkan::PipelineManagerVulkan(VulkanContext *vulkan) : pipelines_(256), vulkan_(vulkan) { // The pipeline cache is created on demand (or explicitly through Load). } @@ -30,10 +34,6 @@ PipelineManagerVulkan::~PipelineManagerVulkan() { } void PipelineManagerVulkan::Clear() { - // This should kill off all the shaders at once. - // This could also be an opportunity to store the whole cache to disk. Will need to also - // store the keys. - pipelines_.Iterate([&](const VulkanPipelineKey &key, VulkanPipeline *value) { for (int i = 0; i < RP_TYPE_COUNT; i++) { if (value->pipeline) { @@ -180,7 +180,7 @@ static std::string CutFromMain(std::string str) { static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, VkPipelineCache pipelineCache, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &key, - const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { + const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantBitmask) { VKRGraphicsPipelineDesc *desc = new VKRGraphicsPipelineDesc(); desc->pipelineCache = pipelineCache; @@ -304,7 +304,7 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, desc->pipelineLayout = layout; - VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc); + VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc, variantBitmask); VulkanPipeline *vulkanPipeline = new VulkanPipeline(); vulkanPipeline->pipeline = pipeline; @@ -319,7 +319,7 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, return vulkanPipeline; } -VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform) { +VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantBitmask) { if (!pipelineCache_) { VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; VkResult res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_); @@ -340,7 +340,7 @@ VulkanPipeline *PipelineManagerVulkan::GetOrCreatePipeline(VulkanRenderManager * VulkanPipeline *pipeline = CreateVulkanPipeline( renderManager, pipelineCache_, layout, - rasterKey, decFmt, vs, fs, useHwTransform); + rasterKey, decFmt, vs, fs, useHwTransform, variantBitmask); pipelines_.Insert(key, pipeline); // Don't return placeholder null pipelines. @@ -546,7 +546,8 @@ struct StoredVulkanPipelineKey { VShaderID vShaderID; FShaderID fShaderID; uint32_t vtxFmtId; - bool useHWTransform; + uint32_t variants; + bool useHWTransform; // TODO: Still needed? // For std::set. Better zero-initialize the struct properly for this to work. bool operator < (const StoredVulkanPipelineKey &other) const { @@ -603,6 +604,7 @@ void PipelineManagerVulkan::SaveCache(FILE *file, bool saveRawPipelineCache, Sha key.useHWTransform = pkey.useHWTransform; key.fShaderID = fshader->GetID(); key.vShaderID = vshader->GetID(); + key.variants = value->GetVariantsBitmask(); if (key.useHWTransform) { // NOTE: This is not a vtype, but a decoded vertex format. key.vtxFmtId = pkey.vtxFmtId; @@ -714,11 +716,14 @@ bool PipelineManagerVulkan::LoadCache(FILE *file, bool loadRawPipelineCache, Sha DecVtxFormat fmt; fmt.InitializeFromID(key.vtxFmtId); - VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, key.raster, key.useHWTransform ? &fmt : 0, vs, fs, key.useHWTransform); + VulkanPipeline *pipeline = GetOrCreatePipeline(rm, layout, key.raster, key.useHWTransform ? &fmt : 0, vs, fs, key.useHWTransform, key.variants); if (!pipeline) { pipelineCreateFailCount += 1; } } + + rm->NudgeCompilerThread(); + NOTICE_LOG(G3D, "Recreated Vulkan pipeline cache (%d pipelines, %d failed).", (int)size, pipelineCreateFailCount); return true; } diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index 5c90723518..da4a59af62 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -58,6 +58,8 @@ struct VulkanPipeline { bool UsesBlendConstant() const { return (flags & PIPELINE_FLAG_USES_BLEND_CONSTANT) != 0; } bool UsesLines() const { return (flags & PIPELINE_FLAG_USES_LINES) != 0; } bool UsesDepthStencil() const { return (flags & PIPELINE_FLAG_USES_DEPTH_STENCIL) != 0; } + + u32 GetVariantsBitmask() const; }; class VulkanContext; @@ -71,7 +73,8 @@ public: PipelineManagerVulkan(VulkanContext *ctx); ~PipelineManagerVulkan(); - VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform); + // variantMask is only used when loading pipelines from cache. + VulkanPipeline *GetOrCreatePipeline(VulkanRenderManager *renderManager, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &rasterKey, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantMask); int GetNumPipelines() const { return (int)pipelines_.size(); } void Clear(); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 3d9074a259..3eb71ee8d8 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -371,7 +371,7 @@ VulkanFragmentShader *ShaderManagerVulkan::GetFragmentShaderFromModule(VkShaderM // instantaneous. #define CACHE_HEADER_MAGIC 0xff51f420 -#define CACHE_VERSION 24 +#define CACHE_VERSION 25 struct VulkanCacheHeader { uint32_t magic; uint32_t version; @@ -391,10 +391,6 @@ bool ShaderManagerVulkan::LoadCache(FILE *f) { if (header.featureFlags != gstate_c.featureFlags) return false; - // Temporarily disable shader cache. - if (true) - return false; - VulkanContext *vulkan = (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT); for (int i = 0; i < header.numVertexShaders; i++) { VShaderID id; From 77819c6f80da8a06cda6bef8acf4e651bf091c31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 16:11:15 +0200 Subject: [PATCH 033/110] Lifetime fixes, cleanups --- Common/Data/Collections/Hashmaps.h | 1 + Common/GPU/Vulkan/VulkanRenderManager.cpp | 31 +++++++++++++++++++- Common/GPU/Vulkan/VulkanRenderManager.h | 35 ++++++++--------------- Common/GPU/Vulkan/thin3d_vulkan.cpp | 12 ++++---- GPU/Vulkan/PipelineManagerVulkan.cpp | 25 ++++++---------- GPU/Vulkan/PipelineManagerVulkan.h | 2 ++ 6 files changed, 60 insertions(+), 46 deletions(-) diff --git a/Common/Data/Collections/Hashmaps.h b/Common/Data/Collections/Hashmaps.h index d7de958c1b..8368c83db5 100644 --- a/Common/Data/Collections/Hashmaps.h +++ b/Common/Data/Collections/Hashmaps.h @@ -136,6 +136,7 @@ public: } } + // Note! Does NOT delete any pointed-to data (in case you stored pointers in the map). void Clear() { memset(state.data(), (int)BucketState::FREE, state.size()); count_ = 0; diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 21a444f894..3a808656db 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -96,9 +96,14 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR ERROR_LOG(G3D, "Failed creating graphics pipeline! result='%s'", VulkanResultToString(result)); success = false; } else { + // Success! + if (!tag.empty()) { + vulkan->SetDebugName(vkpipeline, VK_OBJECT_TYPE_PIPELINE, tag.c_str()); + } pipeline[rpType]->Post(vkpipeline); } + // Having the desc stick around can be useful for debugging. #ifndef _DEBUG delete desc; @@ -107,6 +112,29 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR return success; } +void VKRGraphicsPipeline::QueueForDeletion(VulkanContext *vulkan) { + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (!pipeline[i]) + continue; + VkPipeline pipeline = this->pipeline[i]->BlockUntilReady(); + vulkan->Delete().QueueDeletePipeline(pipeline); + vulkan->Delete().QueueCallback([](void *p) { + VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; + delete pipeline; + }, this); + } +} + +u32 VKRGraphicsPipeline::GetVariantsBitmask() const { + u32 bitmask = 0; + for (int i = 0; i < RP_TYPE_COUNT; i++) { + if (pipeline[i]) { + bitmask |= 1 << i; + } + } + return bitmask; +} + bool VKRComputePipeline::Create(VulkanContext *vulkan) { if (!desc) { // Already failed to create this one. @@ -693,11 +721,12 @@ VkCommandBuffer VulkanRenderManager::GetInitCmd() { return frameData_[curFrame].initCmd; } -VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask) { +VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask, const char *tag) { VKRGraphicsPipeline *pipeline = new VKRGraphicsPipeline(); _dbg_assert_(desc->vertexShader); _dbg_assert_(desc->fragmentShader); pipeline->desc = desc; + pipeline->tag = tag; if (curRenderStep_) { // The common case pipelinesToCheck_.push_back(pipeline); diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index 24a3fca123..dc4bad101f 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -155,31 +155,20 @@ struct VKRComputePipelineDesc { VkComputePipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO }; }; -// Wrapped pipeline. +// Wrapped pipeline. Doesn't own desc. struct VKRGraphicsPipeline { - VKRGraphicsPipeline() { - for (int i = 0; i < RP_TYPE_COUNT; i++) { - pipeline[i] = nullptr; - } - } - ~VKRGraphicsPipeline() { - delete desc; - } - - u32 GetVariantsBitmask() const { - u32 bitmask = 0; - for (int i = 0; i < RP_TYPE_COUNT; i++) { - if (pipeline[i]) { - bitmask |= 1 << i; - } - } - return bitmask; - } - - VKRGraphicsPipelineDesc *desc = nullptr; - Promise *pipeline[RP_TYPE_COUNT]; + ~VKRGraphicsPipeline() {} bool Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType); + + // This deletes the whole VKRGraphicsPipeline, you must remove your last pointer to it when doing this. + void QueueForDeletion(VulkanContext *vulkan); + + u32 GetVariantsBitmask() const; + + VKRGraphicsPipelineDesc *desc = nullptr; + Promise *pipeline[RP_TYPE_COUNT]{}; + std::string tag; }; struct VKRComputePipeline { @@ -260,7 +249,7 @@ public: // We delay creating pipelines until the end of the current render pass, so we can create the right type immediately. // Unless a variantBitmask is passed in, in which case we can just go ahead. // WARNING: desc must stick around during the lifetime of the pipeline! It's not enough to build it on the stack and drop it. - VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask); + VKRGraphicsPipeline *CreateGraphicsPipeline(VKRGraphicsPipelineDesc *desc, uint32_t variantBitmask, const char *tag); VKRComputePipeline *CreateComputePipeline(VKRComputePipelineDesc *desc); void NudgeCompilerThread() { diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index d456aadcfb..eb847df025 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -249,12 +249,14 @@ public: class VKPipeline : public Pipeline { public: - VKPipeline(VulkanRenderManager *rm, size_t size, PipelineFlags _flags) : rm_(rm), flags(_flags) { + VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags) : vulkan_(vulkan), flags(_flags) { uboSize_ = (int)size; ubo_ = new uint8_t[uboSize_]; } ~VKPipeline() { - // TODO: Right now we just leak the pipeline! This is not good. + if (pipeline) { + pipeline->QueueForDeletion(vulkan_); + } delete[] ubo_; } @@ -282,7 +284,7 @@ public: bool usesStencil = false; private: - VulkanRenderManager *rm_; + VulkanContext *vulkan_; uint8_t *ubo_; int uboSize_; }; @@ -1040,7 +1042,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipelineFlags |= PIPELINE_FLAG_USES_DEPTH_STENCIL; } - VKPipeline *pipeline = new VKPipeline(&renderManager_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); + VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); VKRGraphicsPipelineDesc &gDesc = pipeline->vkrDesc; @@ -1110,7 +1112,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; raster->ToVulkan(&gDesc.rs); - pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER); + pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER, "thin3d"); if (desc.uniformDesc) { pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize; diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 76423fae84..9279fca6d4 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -35,21 +35,12 @@ PipelineManagerVulkan::~PipelineManagerVulkan() { void PipelineManagerVulkan::Clear() { pipelines_.Iterate([&](const VulkanPipelineKey &key, VulkanPipeline *value) { - for (int i = 0; i < RP_TYPE_COUNT; i++) { - if (value->pipeline) { - if (value->pipeline->pipeline[i]) { - VkPipeline pipeline = value->pipeline->pipeline[i]->BlockUntilReady(); - vulkan_->Delete().QueueDeletePipeline(pipeline); - vulkan_->Delete().QueueCallback([](void *p) { - VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; - delete pipeline; - }, value->pipeline); - } - } else { - // Something went wrong. - ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); - } + if (!value->pipeline) { + // Something went wrong. + ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); + delete value; } + value->pipeline->QueueForDeletion(vulkan_); delete value; }); @@ -181,7 +172,8 @@ static std::string CutFromMain(std::string str) { static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, VkPipelineCache pipelineCache, VkPipelineLayout layout, const VulkanPipelineRasterStateKey &key, const DecVtxFormat *decFmt, VulkanVertexShader *vs, VulkanFragmentShader *fs, bool useHwTransform, u32 variantBitmask) { - VKRGraphicsPipelineDesc *desc = new VKRGraphicsPipelineDesc(); + VulkanPipeline *vulkanPipeline = new VulkanPipeline(); + VKRGraphicsPipelineDesc *desc = &vulkanPipeline->desc; desc->pipelineCache = pipelineCache; PROFILE_THIS_SCOPE("pipelinebuild"); @@ -304,9 +296,8 @@ static VulkanPipeline *CreateVulkanPipeline(VulkanRenderManager *renderManager, desc->pipelineLayout = layout; - VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc, variantBitmask); + VKRGraphicsPipeline *pipeline = renderManager->CreateGraphicsPipeline(desc, variantBitmask, "game"); - VulkanPipeline *vulkanPipeline = new VulkanPipeline(); vulkanPipeline->pipeline = pipeline; vulkanPipeline->flags = 0; if (useBlendConstant) diff --git a/GPU/Vulkan/PipelineManagerVulkan.h b/GPU/Vulkan/PipelineManagerVulkan.h index da4a59af62..af32aa81bd 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.h +++ b/GPU/Vulkan/PipelineManagerVulkan.h @@ -28,6 +28,7 @@ #include "GPU/Vulkan/VulkanUtil.h" #include "GPU/Vulkan/StateMappingVulkan.h" #include "GPU/Vulkan/VulkanQueueRunner.h" +#include "GPU/Vulkan/VulkanRenderManager.h" struct VKRGraphicsPipeline; class VulkanRenderManager; @@ -53,6 +54,7 @@ struct VulkanPipelineKey { // Simply wraps a Vulkan pipeline, providing some metadata. struct VulkanPipeline { VKRGraphicsPipeline *pipeline; + VKRGraphicsPipelineDesc desc; int flags; // PipelineFlags enum above. bool UsesBlendConstant() const { return (flags & PIPELINE_FLAG_USES_BLEND_CONSTANT) != 0; } From caff2ea5732199b854c83929bbddb9be96b44422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 18:44:48 +0200 Subject: [PATCH 034/110] Correct merging of render passes. However, we have lifetime issues. --- Common/GPU/Vulkan/VulkanQueueRunner.cpp | 33 ++++++++++++++++++++++--- Common/GPU/Vulkan/VulkanQueueRunner.h | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index c3ed8e336b..cc85af0a97 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -27,6 +27,18 @@ static void MergeRenderAreaRectInto(VkRect2D *dest, VkRect2D &src) { } } +// We need to take the "max" of the features used in the two render passes. +RenderPassType MergeRPTypes(RenderPassType a, RenderPassType b) { + // Either both are backbuffer type, or neither are. + _dbg_assert_((a == RP_TYPE_BACKBUFFER) == (b == RP_TYPE_BACKBUFFER)); + if (a == b) { + // Trivial merging case. + return a; + } + // More cases to be added later. + return a; +} + void VulkanQueueRunner::CreateDeviceObjects() { INFO_LOG(G3D, "VulkanQueueRunner::CreateDeviceObjects"); @@ -279,7 +291,7 @@ void VulkanQueueRunner::PreprocessSteps(std::vector &steps) { steps[i]->render.clearStencil = steps[j]->render.clearStencil; } MergeRenderAreaRectInto(&steps[i]->render.renderArea, steps[j]->render.renderArea); - + steps[i]->render.renderPassType = MergeRPTypes(steps[i]->render.renderPassType, steps[j]->render.renderPassType); // Cheaply skip the first step. steps[j]->stepType = VKRStepType::RENDER_SKIP; break; @@ -659,6 +671,8 @@ void VulkanQueueRunner::ApplyRenderPassMerge(std::vector &steps) { // So we don't consider it for other things, maybe doesn't matter. src->dependencies.clear(); src->stepType = VKRStepType::RENDER_SKIP; + dst->render.pipelineFlags |= src->render.pipelineFlags; + dst->render.renderPassType = MergeRPTypes(dst->render.renderPassType, src->render.renderPassType); }; auto renderHasClear = [](const VKRStep *step) { const auto &r = step->render; @@ -1104,7 +1118,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c // This reads the layout of the color and depth images, and chooses a render pass using them that // will transition to the desired final layout. // NOTE: Flushes recordBarrier_. - PerformBindFramebufferAsRenderTarget(step, cmd); + VKRRenderPass *renderPass = PerformBindFramebufferAsRenderTarget(step, cmd); int curWidth = step.render.framebuffer ? step.render.framebuffer->width : vulkan_->GetBackbufferWidth(); int curHeight = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight(); @@ -1150,7 +1164,16 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c { VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline; if (graphicsPipeline != lastGraphicsPipeline) { - _dbg_assert_(graphicsPipeline->pipeline[rpType]); + if (!graphicsPipeline->pipeline[rpType]) { + // NOTE: If render steps got merged, it can happen that, as they ended during recording, + // they didn't know their final render pass type so they created the wrong pipelines in EndCurRenderStep(). + // Unfortunately I don't know if we can fix it in any more sensible place than here. + // Maybe a middle pass. But let's try to just block and compile here for now, this doesn't + // happen all that much. + graphicsPipeline->pipeline[rpType] = Promise::CreateEmpty(); + graphicsPipeline->Create(vulkan_, renderPass->Get(vulkan_, rpType), rpType); + } + VkPipeline pipeline = graphicsPipeline->pipeline[rpType]->BlockUntilReady(); if (pipeline != VK_NULL_HANDLE) { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); @@ -1307,7 +1330,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c } } -void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) { +VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) { VKRRenderPass *renderPass; int numClearVals = 0; VkClearValue clearVal[2]{}; @@ -1400,6 +1423,8 @@ void VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step rp_begin.clearValueCount = numClearVals; rp_begin.pClearValues = numClearVals ? clearVal : nullptr; vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); + + return renderPass; } void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) { diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.h b/Common/GPU/Vulkan/VulkanQueueRunner.h index 0e97879658..0cf4b28190 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.h +++ b/Common/GPU/Vulkan/VulkanQueueRunner.h @@ -303,7 +303,7 @@ public: } private: - void PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); + VKRRenderPass *PerformBindFramebufferAsRenderTarget(const VKRStep &pass, VkCommandBuffer cmd); void PerformRenderPass(const VKRStep &pass, VkCommandBuffer cmd); void PerformCopy(const VKRStep &pass, VkCommandBuffer cmd); void PerformBlit(const VKRStep &pass, VkCommandBuffer cmd); From 14b5a1a7cd753463243b54135e5f1f4ff208ba75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 19:29:54 +0200 Subject: [PATCH 035/110] Fix pipeline lifetime issue, misc. --- Common/GPU/Vulkan/VulkanContext.cpp | 5 ++++- Common/GPU/Vulkan/VulkanContext.h | 2 +- Common/GPU/Vulkan/VulkanRenderManager.cpp | 12 +++++++----- Common/GPU/Vulkan/thin3d_vulkan.cpp | 2 +- GPU/Vulkan/PipelineManagerVulkan.cpp | 4 ++-- GPU/Vulkan/ShaderManagerVulkan.cpp | 4 ++-- GPU/Vulkan/VulkanUtil.cpp | 2 +- 7 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanContext.cpp b/Common/GPU/Vulkan/VulkanContext.cpp index 63351eaf45..55edc0f31f 100644 --- a/Common/GPU/Vulkan/VulkanContext.cpp +++ b/Common/GPU/Vulkan/VulkanContext.cpp @@ -1196,12 +1196,15 @@ void VulkanContext::DestroyDevice() { device_ = nullptr; } -bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule) { +bool VulkanContext::CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule, const char *tag) { VkShaderModuleCreateInfo sm{ VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; sm.pCode = spirv.data(); sm.codeSize = spirv.size() * sizeof(uint32_t); sm.flags = 0; VkResult result = vkCreateShaderModule(device_, &sm, nullptr, shaderModule); + if (tag) { + SetDebugName(*shaderModule, VK_OBJECT_TYPE_SHADER_MODULE, tag); + } if (result != VK_SUCCESS) { return false; } else { diff --git a/Common/GPU/Vulkan/VulkanContext.h b/Common/GPU/Vulkan/VulkanContext.h index b5750c77ab..87a73a59fc 100644 --- a/Common/GPU/Vulkan/VulkanContext.h +++ b/Common/GPU/Vulkan/VulkanContext.h @@ -201,7 +201,7 @@ public: // Utility functions for shorter code VkFence CreateFence(bool presignalled); - bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule); + bool CreateShaderModule(const std::vector &spirv, VkShaderModule *shaderModule, const char *tag); int GetBackbufferWidth() { return (int)swapChainExtent_.width; } int GetBackbufferHeight() { return (int)swapChainExtent_.height; } diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 3a808656db..b7a076bba7 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -118,11 +118,11 @@ void VKRGraphicsPipeline::QueueForDeletion(VulkanContext *vulkan) { continue; VkPipeline pipeline = this->pipeline[i]->BlockUntilReady(); vulkan->Delete().QueueDeletePipeline(pipeline); - vulkan->Delete().QueueCallback([](void *p) { - VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; - delete pipeline; - }, this); } + vulkan->Delete().QueueCallback([](void *p) { + VKRGraphicsPipeline *pipeline = (VKRGraphicsPipeline *)p; + delete pipeline; + }, this); } u32 VKRGraphicsPipeline::GetVariantsBitmask() const { @@ -634,7 +634,9 @@ void VulkanRenderManager::BeginFrame(bool enableProfiling, bool enableLogProfile VLOG("PUSH: Fencing %d", curFrame); - vkWaitForFences(device, 1, &frameData.fence, true, UINT64_MAX); + if (vkWaitForFences(device, 1, &frameData.fence, true, UINT64_MAX) == VK_ERROR_DEVICE_LOST) { + _assert_msg_(false, "Device lost in vkWaitForFences"); + } vkResetFences(device, 1, &frameData.fence); // Can't set this until after the fence. diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index eb847df025..6a6855f03f 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -231,7 +231,7 @@ bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, con } #endif - if (vulkan->CreateShaderModule(spirv, &module_)) { + if (vulkan->CreateShaderModule(spirv, &module_, vkstage_ == VK_SHADER_STAGE_VERTEX_BIT ? "thin3d_vs" : "thin3d_fs")) { ok_ = true; } else { WARN_LOG(G3D, "vkCreateShaderModule failed"); diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 9279fca6d4..a88fe235a5 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -38,9 +38,9 @@ void PipelineManagerVulkan::Clear() { if (!value->pipeline) { // Something went wrong. ERROR_LOG(G3D, "Null pipeline found in PipelineManagerVulkan::Clear - didn't wait for asyncs?"); - delete value; + } else { + value->pipeline->QueueForDeletion(vulkan_); } - value->pipeline->QueueForDeletion(vulkan_); delete value; }); diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index 3eb71ee8d8..b3e5ff339f 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -71,7 +71,7 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade VkShaderModule shaderModule = VK_NULL_HANDLE; if (success) { - success = vulkan->CreateShaderModule(spirv, &shaderModule); + success = vulkan->CreateShaderModule(spirv, &shaderModule, stage == VK_SHADER_STAGE_VERTEX_BIT ? "game_vertex" : "game_fragment"); #ifdef SHADERLOG OutputDebugStringA("OK"); #endif @@ -81,7 +81,7 @@ Promise *CompileShaderModuleAsync(VulkanContext *vulkan, VkShade }; #ifdef _DEBUG - // Don't parallelize in debug mode, pathological behavior due to mutex locks in allocator. + // Don't parallelize in debug mode, pathological behavior due to mutex locks in allocator which is HEAVILY used by glslang. return Promise::AlreadyDone(compile()); #else return Promise::Spawn(&g_threadManager, compile, TaskType::CPU_COMPUTE); diff --git a/GPU/Vulkan/VulkanUtil.cpp b/GPU/Vulkan/VulkanUtil.cpp index 4664f60c8a..fb82f9a474 100644 --- a/GPU/Vulkan/VulkanUtil.cpp +++ b/GPU/Vulkan/VulkanUtil.cpp @@ -44,7 +44,7 @@ VkShaderModule CompileShaderModule(VulkanContext *vulkan, VkShaderStageFlagBits return VK_NULL_HANDLE; } else { VkShaderModule module; - if (vulkan->CreateShaderModule(spirv, &module)) { + if (vulkan->CreateShaderModule(spirv, &module, stage == VK_SHADER_STAGE_VERTEX_BIT ? "system_vs" : "system_fs")) { return module; } else { return VK_NULL_HANDLE; From cddc612f6defbf52abe102adeaa189df6e894b6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 00:22:45 +0200 Subject: [PATCH 036/110] Extend lifetime of ShaderModule objects since we might need to recreate pipelines for different render passes --- Common/GPU/Vulkan/thin3d_vulkan.cpp | 14 ++++++++++++-- GPU/Common/Draw2D.cpp | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 6a6855f03f..08f8891ae5 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -193,6 +193,7 @@ public: const std::string &GetSource() const { return source_; } ~VKShaderModule() { if (module_) { + DEBUG_LOG(G3D, "Queueing %s (shmodule %p) for release", tag_.c_str(), module_); vulkan_->Delete().QueueDeleteShaderModule(module_); } } @@ -249,14 +250,18 @@ public: class VKPipeline : public Pipeline { public: - VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags) : vulkan_(vulkan), flags(_flags) { + VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags, const char *tag) : vulkan_(vulkan), flags(_flags), tag_(tag) { uboSize_ = (int)size; ubo_ = new uint8_t[uboSize_]; } ~VKPipeline() { + DEBUG_LOG(G3D, "Queueing %s (pipeline) for release", tag_.c_str()); if (pipeline) { pipeline->QueueForDeletion(vulkan_); } + for (auto dep : deps) { + dep->Release(); + } delete[] ubo_; } @@ -278,6 +283,8 @@ public: VKRGraphicsPipelineDesc vkrDesc; PipelineFlags flags; + std::vector deps; + int stride[4]{}; int dynamicUniformSize = 0; @@ -287,6 +294,7 @@ private: VulkanContext *vulkan_; uint8_t *ubo_; int uboSize_; + std::string tag_; }; class VKTexture; @@ -1042,7 +1050,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipelineFlags |= PIPELINE_FLAG_USES_DEPTH_STENCIL; } - VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags); + VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags, "thin3d"); VKRGraphicsPipelineDesc &gDesc = pipeline->vkrDesc; @@ -1051,6 +1059,8 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { for (auto &iter : desc.shaders) { VKShaderModule *vkshader = (VKShaderModule *)iter; + vkshader->AddRef(); + pipeline->deps.push_back(vkshader); if (vkshader->GetStage() == ShaderStage::Vertex) { gDesc.vertexShader = Promise::AlreadyDone(vkshader->Get()); } else if (vkshader->GetStage() == ShaderStage::Fragment) { diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index cd54704e9a..4e29570db0 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -198,7 +198,7 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionCreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), "draw2d_fs"); + ShaderModule *fs = draw_->CreateShaderModule(ShaderStage::Fragment, shaderLanguageDesc.shaderLanguage, (const uint8_t *)fsCode, strlen(fsCode), info.tag); _assert_(fs); From 347f7c4e5a0e65d96b82a6f6572e2b81e3ca7f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 7 Sep 2022 23:55:33 +0200 Subject: [PATCH 037/110] Vulkan: Improve tagging of pipelines for debugging purposes --- Common/GPU/D3D11/thin3d_d3d11.cpp | 10 +++++----- Common/GPU/D3D9/thin3d_d3d9.cpp | 12 ++++++------ Common/GPU/OpenGL/thin3d_gl.cpp | 12 ++++++------ Common/GPU/Vulkan/thin3d_vulkan.cpp | 18 +++++++++--------- Common/GPU/thin3d.h | 4 ++-- GPU/Common/Draw2D.cpp | 6 +++++- GPU/Common/Draw2D.h | 1 + GPU/Common/PresentationCommon.cpp | 2 +- GPU/Common/ReinterpretFramebuffer.cpp | 1 + GPU/Common/StencilCommon.cpp | 2 +- GPU/Common/TextureShaderCommon.cpp | 1 + UI/GPUDriverTestScreen.cpp | 26 +++++++++++++------------- UI/NativeApp.cpp | 4 ++-- 13 files changed, 53 insertions(+), 46 deletions(-) diff --git a/Common/GPU/D3D11/thin3d_d3d11.cpp b/Common/GPU/D3D11/thin3d_d3d11.cpp index 0464235eb5..2bce9ebaff 100644 --- a/Common/GPU/D3D11/thin3d_d3d11.cpp +++ b/Common/GPU/D3D11/thin3d_d3d11.cpp @@ -82,9 +82,9 @@ public: SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Framebuffer *CreateFramebuffer(const FramebufferDesc &desc) override; void UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset, size_t size, UpdateBufferFlags flags) override; @@ -920,7 +920,7 @@ Texture *D3D11DrawContext::CreateTexture(const TextureDesc &desc) { return tex; } -ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) { +ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) { if (language != ShaderLanguage::HLSL_D3D11) { ERROR_LOG(G3D, "Unsupported shader language"); return nullptr; @@ -965,7 +965,7 @@ ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLang } if (errorMsgs) { errors = std::string((const char *)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize()); - ERROR_LOG(G3D, "Failed compiling:\n%s\n%s", data, errors.c_str()); + ERROR_LOG(G3D, "Failed compiling %s:\n%s\n%s", tag, data, errors.c_str()); errorMsgs->Release(); } @@ -1003,7 +1003,7 @@ ShaderModule *D3D11DrawContext::CreateShaderModule(ShaderStage stage, ShaderLang return nullptr; } -Pipeline *D3D11DrawContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *D3D11DrawContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { D3D11Pipeline *dPipeline = new D3D11Pipeline(); dPipeline->blend = (D3D11BlendState *)desc.blend; dPipeline->depthStencil = (D3D11DepthStencilState *)desc.depthStencil; diff --git a/Common/GPU/D3D9/thin3d_d3d9.cpp b/Common/GPU/D3D9/thin3d_d3d9.cpp index dc72ed898d..8554961119 100644 --- a/Common/GPU/D3D9/thin3d_d3d9.cpp +++ b/Common/GPU/D3D9/thin3d_d3d9.cpp @@ -489,13 +489,13 @@ public: } uint32_t GetDataFormatSupport(DataFormat fmt) const override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) override; BlendState *CreateBlendState(const BlendStateDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; Texture *CreateTexture(const TextureDesc &desc) override; @@ -692,7 +692,7 @@ D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, ID D3D9Context::~D3D9Context() { } -ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const std::string &tag) { +ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const char *tag) { D3D9ShaderModule *shader = new D3D9ShaderModule(stage, tag); if (shader->Compile(device_, data, size)) { return shader; @@ -702,15 +702,15 @@ ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, ShaderLanguage } } -Pipeline *D3D9Context::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *D3D9Context::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { if (!desc.shaders.size()) { - ERROR_LOG(G3D, "Pipeline requires at least one shader"); + ERROR_LOG(G3D, "Pipeline %s requires at least one shader", tag); return NULL; } D3D9Pipeline *pipeline = new D3D9Pipeline(); for (auto iter : desc.shaders) { if (!iter) { - ERROR_LOG(G3D, "NULL shader passed to CreateGraphicsPipeline"); + ERROR_LOG(G3D, "NULL shader passed to CreateGraphicsPipeline(%s)", tag); delete pipeline; return NULL; } diff --git a/Common/GPU/OpenGL/thin3d_gl.cpp b/Common/GPU/OpenGL/thin3d_gl.cpp index 5283b064ec..1d2e5822e2 100644 --- a/Common/GPU/OpenGL/thin3d_gl.cpp +++ b/Common/GPU/OpenGL/thin3d_gl.cpp @@ -336,9 +336,9 @@ public: BlendState *CreateBlendState(const BlendStateDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; @@ -1079,7 +1079,7 @@ void OpenGLContext::UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t off renderManager_.BufferSubdata(buf->buffer_, offset, size, dataCopy); } -Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { if (!desc.shaders.size()) { ERROR_LOG(G3D, "Pipeline requires at least one shader"); return nullptr; @@ -1099,7 +1099,7 @@ Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { iter->AddRef(); pipeline->shaders.push_back(static_cast(iter)); } else { - ERROR_LOG(G3D, "ERROR: Tried to create graphics pipeline with a null shader module"); + ERROR_LOG(G3D, "ERROR: Tried to create graphics pipeline %s with a null shader module", tag); delete pipeline; return nullptr; } @@ -1118,7 +1118,7 @@ Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipeline->inputLayout = (OpenGLInputLayout *)desc.inputLayout; return pipeline; } else { - ERROR_LOG(G3D, "Failed to create pipeline - shaders failed to link"); + ERROR_LOG(G3D, "Failed to create pipeline %s - shaders failed to link", tag); delete pipeline; return nullptr; } @@ -1163,7 +1163,7 @@ void OpenGLContext::ApplySamplers() { } } -ShaderModule *OpenGLContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) { +ShaderModule *OpenGLContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) { OpenGLShaderModule *shader = new OpenGLShaderModule(&renderManager_, stage, tag); if (shader->Compile(&renderManager_, language, data, dataSize)) { return shader; diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 08f8891ae5..0cb0a40531 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -219,7 +219,7 @@ bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, con std::vector spirv; std::string errorMessage; if (!GLSLtoSPV(vkstage_, source_.c_str(), GLSLVariant::VULKAN, spirv, &errorMessage)) { - WARN_LOG(G3D, "Shader compile to module failed: %s", errorMessage.c_str()); + WARN_LOG(G3D, "Shader compile to module failed (%s): %s", tag_.c_str(), errorMessage.c_str()); return false; } @@ -235,7 +235,7 @@ bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, con if (vulkan->CreateShaderModule(spirv, &module_, vkstage_ == VK_SHADER_STAGE_VERTEX_BIT ? "thin3d_vs" : "thin3d_fs")) { ok_ = true; } else { - WARN_LOG(G3D, "vkCreateShaderModule failed"); + WARN_LOG(G3D, "vkCreateShaderModule failed (%s)", tag_.c_str()); ok_ = false; } return ok_; @@ -384,8 +384,8 @@ public: InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override; SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override; RasterState *CreateRasterState(const RasterStateDesc &desc) override; - Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) override; - ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag) override; + Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override; + ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override; Texture *CreateTexture(const TextureDesc &desc) override; Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override; @@ -1039,7 +1039,7 @@ VkDescriptorSet VKContext::GetOrCreateDescriptorSet(VkBuffer buf) { return descSet; } -Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { +Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) { VKInputLayout *input = (VKInputLayout *)desc.inputLayout; VKBlendState *blend = (VKBlendState *)desc.blend; VKDepthStencilState *depth = (VKDepthStencilState *)desc.depthStencil; @@ -1050,7 +1050,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { pipelineFlags |= PIPELINE_FLAG_USES_DEPTH_STENCIL; } - VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags, "thin3d"); + VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), (PipelineFlags)pipelineFlags, tag); VKRGraphicsPipelineDesc &gDesc = pipeline->vkrDesc; @@ -1122,7 +1122,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc) { VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; raster->ToVulkan(&gDesc.rs); - pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER, "thin3d"); + pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, 1 << RP_TYPE_BACKBUFFER, tag ? tag : "thin3d"); if (desc.uniformDesc) { pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize; @@ -1280,12 +1280,12 @@ void VKContext::BindTextures(int start, int count, Texture **textures) { } } -ShaderModule *VKContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const std::string &tag) { +ShaderModule *VKContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const char *tag) { VKShaderModule *shader = new VKShaderModule(stage, tag); if (shader->Compile(vulkan_, language, data, size)) { return shader; } else { - ERROR_LOG(G3D, "Failed to compile shader:\n%s", (const char *)LineNumberString((const char *)data).c_str()); + ERROR_LOG(G3D, "Failed to compile shader %s:\n%s", tag, (const char *)LineNumberString((const char *)data).c_str()); shader->Release(); return nullptr; } diff --git a/Common/GPU/thin3d.h b/Common/GPU/thin3d.h index f44447b1af..6196f494f9 100644 --- a/Common/GPU/thin3d.h +++ b/Common/GPU/thin3d.h @@ -616,8 +616,8 @@ public: virtual RasterState *CreateRasterState(const RasterStateDesc &desc) = 0; // virtual ComputePipeline CreateComputePipeline(const ComputePipelineDesc &desc) = 0 virtual InputLayout *CreateInputLayout(const InputLayoutDesc &desc) = 0; - virtual ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const std::string &tag = "thin3d") = 0; - virtual Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) = 0; + virtual ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag = "thin3d") = 0; + virtual Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) = 0; // Note that these DO NOT AddRef so you must not ->Release presets unless you manually AddRef them. ShaderModule *GetVshaderPreset(VertexShaderPreset preset) { return vsPresets_[preset]; } diff --git a/GPU/Common/Draw2D.cpp b/GPU/Common/Draw2D.cpp index 4e29570db0..ff7aab3169 100644 --- a/GPU/Common/Draw2D.cpp +++ b/GPU/Common/Draw2D.cpp @@ -64,6 +64,7 @@ Draw2DPipelineInfo GenerateDraw2DCopyColorFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_NONE); return Draw2DPipelineInfo{ + "draw2d_copy_color", RASTER_COLOR, RASTER_COLOR, }; @@ -77,6 +78,7 @@ Draw2DPipelineInfo GenerateDraw2DCopyDepthFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_copy_depth", RASTER_DEPTH, RASTER_DEPTH, }; @@ -95,6 +97,7 @@ Draw2DPipelineInfo GenerateDraw2D565ToDepthFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_565_to_depth", RASTER_COLOR, RASTER_DEPTH, }; @@ -119,6 +122,7 @@ Draw2DPipelineInfo GenerateDraw2D565ToDepthDeswizzleFs(ShaderWriter &writer) { writer.EndFSMain("outColor", FSFLAG_WRITEDEPTH); return Draw2DPipelineInfo{ + "draw2d_565_to_depth_deswizzle", RASTER_COLOR, RASTER_DEPTH }; @@ -237,7 +241,7 @@ Draw2DPipeline *Draw2D::Create2DPipeline(std::functionCreateGraphicsPipeline(pipelineDesc); + Draw::Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc, info.tag); fs->Release(); diff --git a/GPU/Common/Draw2D.h b/GPU/Common/Draw2D.h index 2df15581b0..d44f7ff613 100644 --- a/GPU/Common/Draw2D.h +++ b/GPU/Common/Draw2D.h @@ -31,6 +31,7 @@ inline RasterChannel Draw2DSourceChannel(Draw2DShader shader) { } struct Draw2DPipelineInfo { + const char *tag; RasterChannel readChannel; RasterChannel writeChannel; Slice samplers; diff --git a/GPU/Common/PresentationCommon.cpp b/GPU/Common/PresentationCommon.cpp index 552e62a0c5..e430374079 100644 --- a/GPU/Common/PresentationCommon.cpp +++ b/GPU/Common/PresentationCommon.cpp @@ -439,7 +439,7 @@ Draw::Pipeline *PresentationCommon::CreatePipeline(std::vectorCreateRasterState({}); PipelineDesc pipelineDesc{ Primitive::TRIANGLE_LIST, shaders, inputLayout, depth, blendstateOff, rasterNoCull, uniformDesc }; - Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc); + Pipeline *pipeline = draw_->CreateGraphicsPipeline(pipelineDesc, "presentation"); inputLayout->Release(); depth->Release(); diff --git a/GPU/Common/ReinterpretFramebuffer.cpp b/GPU/Common/ReinterpretFramebuffer.cpp index b30c71e504..09f2552a9b 100644 --- a/GPU/Common/ReinterpretFramebuffer.cpp +++ b/GPU/Common/ReinterpretFramebuffer.cpp @@ -185,6 +185,7 @@ Draw2DPipelineInfo GenerateReinterpretFragmentShader(ShaderWriter &writer, GEBuf writer.EndFSMain("outColor", FSFLAG_NONE); return Draw2DPipelineInfo{ + "reinterpret", RASTER_COLOR, RASTER_COLOR, }; diff --git a/GPU/Common/StencilCommon.cpp b/GPU/Common/StencilCommon.cpp index 44cc9304bb..81749ef678 100644 --- a/GPU/Common/StencilCommon.cpp +++ b/GPU/Common/StencilCommon.cpp @@ -237,7 +237,7 @@ bool FramebufferManagerCommon::PerformStencilUpload(u32 addr, int size, StencilU { stencilUploadVs, stencilUploadFs }, inputLayout, stencilWrite, blendOff, rasterNoCull, &stencilUBDesc, }; - stencilUploadPipeline_ = draw_->CreateGraphicsPipeline(stencilWriteDesc); + stencilUploadPipeline_ = draw_->CreateGraphicsPipeline(stencilWriteDesc, "stencil_upload"); _assert_(stencilUploadPipeline_); delete[] fsCode; diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index 79417a482e..bebc72d516 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -213,6 +213,7 @@ Draw2DPipeline *TextureShaderCache::GetDepalettizeShader(uint32_t clutMode, GETe Draw2DPipeline *ts = draw2D_->Create2DPipeline([=](ShaderWriter &writer) -> Draw2DPipelineInfo { GenerateDepalFs(writer, config); return Draw2DPipelineInfo{ + "depal", config.bufferFormat == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR, RASTER_COLOR, samplers diff --git a/UI/GPUDriverTestScreen.cpp b/UI/GPUDriverTestScreen.cpp index 0320a5a858..b46fd7e42e 100644 --- a/UI/GPUDriverTestScreen.cpp +++ b/UI/GPUDriverTestScreen.cpp @@ -390,39 +390,39 @@ void GPUDriverTestScreen::DiscardTest() { { draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D), discardFragShader_ }, inputLayout, depthStencilWrite, blendOffNoColor, rasterNoCull, &vsColBufDesc, }; - discardWriteDepthStencil_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteDepthStencil_ = draw->CreateGraphicsPipeline(discardDesc, "test"); discardDesc.depthStencil = depthWrite; - discardWriteDepth_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteDepth_ = draw->CreateGraphicsPipeline(discardDesc, "test"); discardDesc.depthStencil = stencilWrite; - discardWriteStencil_ = draw->CreateGraphicsPipeline(discardDesc); + discardWriteStencil_ = draw->CreateGraphicsPipeline(discardDesc, "test"); PipelineDesc testDesc{ Primitive::TRIANGLE_LIST, { draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D), draw->GetFshaderPreset(FS_TEXTURE_COLOR_2D) }, inputLayout, stencilEqual, blendOff, rasterNoCull, &vsColBufDesc, }; - drawTestStencilEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilEqualDepthAlways; - drawTestStencilEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilNotEqual; - drawTestStencilNotEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilNotEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stenciNotEqualDepthAlways; - drawTestStencilNotEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilNotEqualDepthAlways_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilAlwaysDepthTestGreater; - drawTestStencilAlwaysDepthGreater_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilAlwaysDepthGreater_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = stencilAlwaysDepthTestLessEqual; - drawTestStencilAlwaysDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestStencilAlwaysDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = depthTestGreater; - drawTestDepthGreater_ = draw->CreateGraphicsPipeline(testDesc); + drawTestDepthGreater_ = draw->CreateGraphicsPipeline(testDesc, "test"); testDesc.depthStencil = depthTestLessEqual; - drawTestDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc); + drawTestDepthLessEqual_ = draw->CreateGraphicsPipeline(testDesc, "test"); inputLayout->Release(); blendOff->Release(); @@ -557,14 +557,14 @@ void GPUDriverTestScreen::ShaderTest() { { adrenoLogicDiscardVertShader_, adrenoLogicDiscardFragShader_ }, inputLayout, depthStencilOff, blendOff, rasterNoCull, &vsColBufDesc, }; - adrenoLogicDiscardPipeline_ = draw->CreateGraphicsPipeline(adrenoLogicDiscardDesc); + adrenoLogicDiscardPipeline_ = draw->CreateGraphicsPipeline(adrenoLogicDiscardDesc, "test"); PipelineDesc flatDesc{ Primitive::TRIANGLE_LIST, { flatVertShader_, flatFragShader_ }, inputLayout, depthStencilOff, blendOff, rasterNoCull, &vsColBufDesc, }; - flatShadingPipeline_ = draw->CreateGraphicsPipeline(flatDesc); + flatShadingPipeline_ = draw->CreateGraphicsPipeline(flatDesc, "test"); inputLayout->Release(); blendOff->Release(); diff --git a/UI/NativeApp.cpp b/UI/NativeApp.cpp index 871e77de18..93b11fd53e 100644 --- a/UI/NativeApp.cpp +++ b/UI/NativeApp.cpp @@ -950,13 +950,13 @@ bool CreateGlobalPipelines() { inputLayout, depth, blendNormal, rasterNoCull, &vsTexColBufDesc, }; - colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc); + colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc, "global_color"); if (!colorPipeline) { // Something really critical is wrong, don't care much about correct releasing of the states. return false; } - texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc); + texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc, "global_texcolor"); if (!texColorPipeline) { // Something really critical is wrong, don't care much about correct releasing of the states. return false; From 68dd329d95f89bcd9beaab39becafba03d319e5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 01:23:18 +0200 Subject: [PATCH 038/110] Fix for desc struct --- Common/GPU/Vulkan/VulkanRenderManager.cpp | 11 ----------- Common/GPU/Vulkan/VulkanRenderManager.h | 2 +- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index b7a076bba7..5a267a273f 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -27,11 +27,6 @@ using namespace PPSSPP_VK; // renderPass is an example of the "compatibility class" or RenderPassType type. bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType) { - if (!desc) { - // Already failed to create this one. - return false; - } - // Fill in the last part of the desc since now it's time to block. VkShaderModule vs = desc->vertexShader->BlockUntilReady(); VkShaderModule fs = desc->fragmentShader->BlockUntilReady(); @@ -103,12 +98,6 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR pipeline[rpType]->Post(vkpipeline); } - - // Having the desc stick around can be useful for debugging. -#ifndef _DEBUG - delete desc; - desc = nullptr; -#endif return success; } diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index dc4bad101f..ad2f71fa28 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -166,7 +166,7 @@ struct VKRGraphicsPipeline { u32 GetVariantsBitmask() const; - VKRGraphicsPipelineDesc *desc = nullptr; + VKRGraphicsPipelineDesc *desc = nullptr; // not owned! Promise *pipeline[RP_TYPE_COUNT]{}; std::string tag; }; From 58a7f0cf21c9a1c9d011d088a67221473918c216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 01:23:33 +0200 Subject: [PATCH 039/110] Assorted cleanup --- Common/GPU/Vulkan/VulkanQueueRunner.cpp | 24 +++++++---------------- Common/GPU/Vulkan/VulkanQueueRunner.h | 1 - Common/GPU/Vulkan/VulkanRenderManager.cpp | 1 - Common/GPU/Vulkan/VulkanRenderManager.h | 2 -- 4 files changed, 7 insertions(+), 21 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index cc85af0a97..10a88e623a 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -624,7 +624,13 @@ std::string VulkanQueueRunner::StepToString(const VKRStep &step) const { int h = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight(); int actual_w = step.render.renderArea.extent.width; int actual_h = step.render.renderArea.extent.height; - snprintf(buffer, sizeof(buffer), "RENDER %s (draws: %d, %dx%d/%dx%d, fb: %p, )", step.tag, step.render.numDraws, actual_w, actual_h, w, h, step.render.framebuffer); + const char *renderCmd; + switch (step.render.renderPassType) { + case RP_TYPE_BACKBUFFER: renderCmd = "BACKBUF"; break; + case RP_TYPE_COLOR_DEPTH: renderCmd = "RENDER"; break; + default: renderCmd = "N/A"; + } + snprintf(buffer, sizeof(buffer), "%s %s (draws: %d, %dx%d/%dx%d, fb: %p, )", renderCmd, step.tag, step.render.numDraws, actual_w, actual_h, w, h, step.render.framebuffer); break; } case VKRStepType::COPY: @@ -811,9 +817,6 @@ void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) { case VKRRenderCommand::REMOVED: INFO_LOG(G3D, " (Removed)"); break; - case VKRRenderCommand::BIND_PIPELINE: - INFO_LOG(G3D, " BindPipeline(%x)", (int)(intptr_t)cmd.pipeline.pipeline); - break; case VKRRenderCommand::BIND_GRAPHICS_PIPELINE: INFO_LOG(G3D, " BindGraphicsPipeline(%x)", (int)(intptr_t)cmd.graphics_pipeline.pipeline); break; @@ -1147,19 +1150,6 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c case VKRRenderCommand::REMOVED: break; - // Still here to support binding of non-async pipelines. - case VKRRenderCommand::BIND_PIPELINE: - { - VkPipeline pipeline = c.pipeline.pipeline; - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - pipelineLayout = c.pipeline.pipelineLayout; - // Reset dynamic state so it gets refreshed with the new pipeline. - lastStencilWriteMask = -1; - lastStencilCompareMask = -1; - lastStencilReference = -1; - break; - } - case VKRRenderCommand::BIND_GRAPHICS_PIPELINE: { VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline; diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.h b/Common/GPU/Vulkan/VulkanQueueRunner.h index 0cf4b28190..adb9e7d96e 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.h +++ b/Common/GPU/Vulkan/VulkanQueueRunner.h @@ -26,7 +26,6 @@ enum { enum class VKRRenderCommand : uint8_t { REMOVED, - BIND_PIPELINE, // raw pipeline BIND_GRAPHICS_PIPELINE, // async BIND_COMPUTE_PIPELINE, // async STENCIL, diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 5a267a273f..52f0b8fb27 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -1132,7 +1132,6 @@ static void CleanupRenderCommands(std::vector *cmds) { case VKRRenderCommand::REMOVED: continue; - case VKRRenderCommand::BIND_PIPELINE: case VKRRenderCommand::VIEWPORT: case VKRRenderCommand::SCISSOR: case VKRRenderCommand::BLEND: diff --git a/Common/GPU/Vulkan/VulkanRenderManager.h b/Common/GPU/Vulkan/VulkanRenderManager.h index ad2f71fa28..4cc7aafdfc 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.h +++ b/Common/GPU/Vulkan/VulkanRenderManager.h @@ -157,8 +157,6 @@ struct VKRComputePipelineDesc { // Wrapped pipeline. Doesn't own desc. struct VKRGraphicsPipeline { - ~VKRGraphicsPipeline() {} - bool Create(VulkanContext *vulkan, VkRenderPass compatibleRenderPass, RenderPassType rpType); // This deletes the whole VKRGraphicsPipeline, you must remove your last pointer to it when doing this. From cdda2034385048fae409f91932817259390dc406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 01:31:10 +0200 Subject: [PATCH 040/110] Fix compiler warnings --- GPU/GeDisasm.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/GeDisasm.cpp b/GPU/GeDisasm.cpp index f1f1293255..b30218b44a 100644 --- a/GPU/GeDisasm.cpp +++ b/GPU/GeDisasm.cpp @@ -94,7 +94,7 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { u32 cmd = op >> 24; u32 data = op & 0xFFFFFF; - static constexpr char *primTypes[8] = { + static const char * const primTypes[8] = { "POINTS", "LINES", "LINE_STRIP", @@ -765,7 +765,7 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { float g = (float)((data>>8) & 0xff)/255.0f; float b = (float)(data>>16)/255.0f; - static constexpr char *lightColorTypes[] = { + static const char * const lightColorTypes[] = { "ambient", "diffuse", "specular", From c9780e7609896b97b9b591e68c196e01305f2fb8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 7 Sep 2022 20:30:29 -0700 Subject: [PATCH 041/110] Build: Another attempt to fix libretro. As per lib/common/portability_macros.h in zstd. --- libretro/Makefile.common | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libretro/Makefile.common b/libretro/Makefile.common index 4dc521e2d6..ab2c4bfe1c 100644 --- a/libretro/Makefile.common +++ b/libretro/Makefile.common @@ -801,7 +801,8 @@ SOURCES_C += $(ZSTDDIR)/common/debug.c \ $(ZSTDDIR)/dictBuilder/fastcover.c \ $(ZSTDDIR)/dictBuilder/zdict.c -ifneq (,$(findstring msvc,$(platform))) +# zstd only uses asm for Linux/macOS and GNUC. +ifneq ($(PLATFORM_EXT), win32) ifeq ($(TARGET_ARCH),x86_64) SOURCES_C += $(ZSTDDIR)/decompress/huf_decompress_amd64.S endif From e6b4495e2281ef12aa54a35b226ba06e9e3e267c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 7 Sep 2022 23:41:00 -0700 Subject: [PATCH 042/110] GPU: Make NotifyConfigChanged() calls consistent. They're generally centralized in Common. --- GPU/D3D11/GPU_D3D11.cpp | 2 +- GPU/Directx9/GPU_DX9.cpp | 2 +- GPU/GLES/GPU_GLES.cpp | 4 ++-- GPU/Vulkan/GPU_Vulkan.cpp | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GPU/D3D11/GPU_D3D11.cpp b/GPU/D3D11/GPU_D3D11.cpp index 94bfa6afa9..3cfe0c4b37 100644 --- a/GPU/D3D11/GPU_D3D11.cpp +++ b/GPU/D3D11/GPU_D3D11.cpp @@ -209,7 +209,7 @@ void GPU_D3D11::BeginHostFrame() { CheckGPUFeatures(); framebufferManager_->Resized(); drawEngine_.Resized(); - textureCacheD3D11_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); shaderManagerD3D11_->DirtyLastShader(); resized_ = false; } diff --git a/GPU/Directx9/GPU_DX9.cpp b/GPU/Directx9/GPU_DX9.cpp index bd37b01aee..3e5d0bac57 100644 --- a/GPU/Directx9/GPU_DX9.cpp +++ b/GPU/Directx9/GPU_DX9.cpp @@ -265,7 +265,7 @@ void GPU_DX9::BeginHostFrame() { framebufferManager_->Resized(); drawEngine_.Resized(); shaderManagerDX9_->DirtyShader(); - textureCacheDX9_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } } diff --git a/GPU/GLES/GPU_GLES.cpp b/GPU/GLES/GPU_GLES.cpp index cb41d2cff2..75fd0080b5 100644 --- a/GPU/GLES/GPU_GLES.cpp +++ b/GPU/GLES/GPU_GLES.cpp @@ -93,7 +93,7 @@ GPU_GLES::GPU_GLES(GraphicsContext *gfxCtx, Draw::DrawContext *draw) // Update again after init to be sure of any silly driver problems. UpdateVsyncInterval(true); - textureCacheGL_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); // Load shader cache. std::string discID = g_paramSFO.GetDiscID(); @@ -325,7 +325,7 @@ void GPU_GLES::BeginHostFrame() { framebufferManager_->Resized(); drawEngine_.Resized(); shaderManagerGL_->DirtyShader(); - textureCacheGL_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } diff --git a/GPU/Vulkan/GPU_Vulkan.cpp b/GPU/Vulkan/GPU_Vulkan.cpp index 6cf56b17f3..f96d282fc7 100644 --- a/GPU/Vulkan/GPU_Vulkan.cpp +++ b/GPU/Vulkan/GPU_Vulkan.cpp @@ -91,7 +91,7 @@ GPU_Vulkan::GPU_Vulkan(GraphicsContext *gfxCtx, Draw::DrawContext *draw) // Update again after init to be sure of any silly driver problems. UpdateVsyncInterval(true); - textureCacheVulkan_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); // Load shader cache. std::string discID = g_paramSFO.GetDiscID(); @@ -303,7 +303,7 @@ void GPU_Vulkan::BeginHostFrame() { BuildReportingInfo(); framebufferManager_->Resized(); drawEngine_.Resized(); - textureCacheVulkan_->NotifyConfigChanged(); + textureCache_->NotifyConfigChanged(); resized_ = false; } From be0e7a8319811145d1a5802623dbcb0b154cc01d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 7 Sep 2022 23:41:42 -0700 Subject: [PATCH 043/110] UI: Resize after visiting developer settings. This will trigger setting updates after visiting from DevMenu. --- UI/GameSettingsScreen.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index cacd51e807..04f2ec8652 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -1890,6 +1890,7 @@ void DeveloperToolsScreen::CreateViews() { void DeveloperToolsScreen::onFinish(DialogResult result) { g_Config.Save("DeveloperToolsScreen::onFinish"); + NativeMessageReceived("gpu_resized", ""); } void GameSettingsScreen::CallbackRestoreDefaults(bool yes) { From 974cd38b1f358f397f2e9ae241ee2523454c676a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 09:15:06 +0200 Subject: [PATCH 044/110] Some more debug names to vulkan objects --- Common/GPU/Vulkan/VulkanMemory.cpp | 8 +++++++- Common/GPU/Vulkan/VulkanMemory.h | 3 +-- Common/GPU/Vulkan/thin3d_vulkan.cpp | 4 ++++ GPU/Vulkan/DrawEngineVulkan.cpp | 3 +++ 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanMemory.cpp b/Common/GPU/Vulkan/VulkanMemory.cpp index a7a5277efa..8206c80c91 100644 --- a/Common/GPU/Vulkan/VulkanMemory.cpp +++ b/Common/GPU/Vulkan/VulkanMemory.cpp @@ -59,6 +59,8 @@ bool VulkanPushBuffer::AddBuffer() { return false; } + vulkan_->SetDebugName(info.buffer, VK_OBJECT_TYPE_BUFFER, name_); + buffers_.push_back(info); buf_ = buffers_.size() - 1; return true; @@ -222,5 +224,9 @@ VkResult VulkanDescSetPool::Recreate(bool grow) { info_.pPoolSizes = &sizes_[0]; info_.poolSizeCount = (uint32_t)sizes_.size(); - return vkCreateDescriptorPool(vulkan_->GetDevice(), &info_, nullptr, &descPool_); + VkResult result = vkCreateDescriptorPool(vulkan_->GetDevice(), &info_, nullptr, &descPool_); + if (result == VK_SUCCESS) { + vulkan_->SetDebugName(descPool_, VK_OBJECT_TYPE_DESCRIPTOR_POOL, tag_); + } + return result; } diff --git a/Common/GPU/Vulkan/VulkanMemory.h b/Common/GPU/Vulkan/VulkanMemory.h index 82ef924390..79a71d4ce6 100644 --- a/Common/GPU/Vulkan/VulkanMemory.h +++ b/Common/GPU/Vulkan/VulkanMemory.h @@ -143,8 +143,7 @@ private: // Only appropriate for use in a per-frame pool. class VulkanDescSetPool { public: - VulkanDescSetPool(const char *tag, bool grow) : tag_(tag), grow_(grow) { - } + VulkanDescSetPool(const char *tag, bool grow) : tag_(tag), grow_(grow) {} ~VulkanDescSetPool(); // Must call this before use: defines how to clear cache of ANY returned values from Allocate(). diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index 0cb0a40531..bb206fd1cb 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -896,6 +896,8 @@ VKContext::VKContext(VulkanContext *vulkan, bool splitSubmit) VkResult res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_); _assert_(VK_SUCCESS == res); + vulkan_->SetDebugName(descriptorSetLayout_, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "thin3d_d_layout"); + VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; pl.pPushConstantRanges = nullptr; pl.pushConstantRangeCount = 0; @@ -904,6 +906,8 @@ VKContext::VKContext(VulkanContext *vulkan, bool splitSubmit) res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_); _assert_(VK_SUCCESS == res); + vulkan_->SetDebugName(pipelineLayout_, VK_OBJECT_TYPE_PIPELINE_LAYOUT, "thin3d_p_layout"); + VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_); _assert_(VK_SUCCESS == res); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 8f4cecfd81..e8ebd485d1 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -141,6 +141,7 @@ void DrawEngineVulkan::InitDeviceObjects() { dsl.pBindings = bindings; VkResult res = vkCreateDescriptorSetLayout(device, &dsl, nullptr, &descriptorSetLayout_); _dbg_assert_(VK_SUCCESS == res); + vulkan->SetDebugName(descriptorSetLayout_, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "drawengine_d_layout"); static constexpr int DEFAULT_DESC_POOL_SIZE = 512; std::vector dpTypes; @@ -179,6 +180,8 @@ void DrawEngineVulkan::InitDeviceObjects() { res = vkCreatePipelineLayout(device, &pl, nullptr, &pipelineLayout_); _dbg_assert_(VK_SUCCESS == res); + vulkan->SetDebugName(pipelineLayout_, VK_OBJECT_TYPE_PIPELINE_LAYOUT, "drawengine_p_layout"); + VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; From e7195d5a99a7fbf03160ef4fc526898d954d65ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 8 Sep 2022 09:18:13 +0200 Subject: [PATCH 045/110] Match FragmentShaderFlags definition with the other PR. --- GPU/Common/FragmentShaderGenerator.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/GPU/Common/FragmentShaderGenerator.h b/GPU/Common/FragmentShaderGenerator.h index 325c368f73..85c651cf8b 100644 --- a/GPU/Common/FragmentShaderGenerator.h +++ b/GPU/Common/FragmentShaderGenerator.h @@ -17,6 +17,7 @@ #pragma once +#include "Common/Common.h" #include "Common/GPU/Shader.h" #include "Common/GPU/thin3d.h" @@ -40,8 +41,9 @@ struct FShaderID; #define CONST_PS_STENCILVALUE 11 // Can technically be deduced from the fragment shader ID, but this is safer. -enum FragmentShaderFlags { - FS_FLAG_INPUT_ATTACHMENT, +enum class FragmentShaderFlags : u32 { + FS_FLAG_INPUT_ATTACHMENT = 1, }; +ENUM_CLASS_BITOPS(FragmentShaderFlags); bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString); From 818334c592f57a59738a93ddbbf49bbc5f7bb857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 09:55:01 +0200 Subject: [PATCH 046/110] atrac3: Allocate some extra bytes for the data buffer to workaround decoder bug. --- Core/HLE/sceAtrac.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index b22c439bc1..3e6fb45d2b 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -1948,7 +1948,12 @@ static int _AtracSetData(Atrac *atrac, u32 buffer, u32 readSize, u32 bufferSize, const char *codecName = atrac->codecType_ == PSP_MODE_AT_3 ? "atrac3" : "atrac3+"; const char *channelName = atrac->channels_ == 1 ? "mono" : "stereo"; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + // Over-allocate databuf to prevent going off the end if the bitstream is bad or if there are + // bugs in the decoder. This happens, see issue #15788. Arbitrary, but let's make it a whole page on the popular + // architecture that has the largest pages (M1). + const size_t overAllocBytes = 16384; + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); if (!atrac->ignoreDataBuf_) { u32 copybytes = std::min(bufferSize, atrac->first_.filesize); Memory::Memcpy(atrac->dataBuf_, buffer, copybytes, "AtracSetData"); From e5d1bb5552f640e240aab273b42c7be54f5b1898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 11:34:11 +0200 Subject: [PATCH 047/110] Warning fix --- Common/VR/PPSSPPVR.cpp | 2 +- Common/VR/PPSSPPVR.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Common/VR/PPSSPPVR.cpp b/Common/VR/PPSSPPVR.cpp index 16b170e1fb..189bb67660 100644 --- a/Common/VR/PPSSPPVR.cpp +++ b/Common/VR/PPSSPPVR.cpp @@ -95,7 +95,7 @@ bool IsVRBuild() { return true; } -void InitVROnAndroid(void* vm, void* activity, int version, char* name) { +void InitVROnAndroid(void* vm, void* activity, int version, const char* name) { ovrJava java; java.Vm = (JavaVM*)vm; java.ActivityObject = (jobject)activity; diff --git a/Common/VR/PPSSPPVR.h b/Common/VR/PPSSPPVR.h index b41b69f1be..bb46d5a63a 100644 --- a/Common/VR/PPSSPPVR.h +++ b/Common/VR/PPSSPPVR.h @@ -7,7 +7,7 @@ // VR app flow integration bool IsVRBuild(); -void InitVROnAndroid(void* vm, void* activity, int version, char* name); +void InitVROnAndroid(void* vm, void* activity, int version, const char* name); void EnterVR(bool firstStart); void GetVRResolutionPerEye(int* width, int* height); void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale); @@ -30,7 +30,7 @@ void UpdateVRView(float* projMatrix, float* leftEye, float* rightEye); // VR app flow integration inline bool IsVRBuild() { return false; } -inline void InitVROnAndroid(void* vm, void* activity, int version, char* name) {} +inline void InitVROnAndroid(void* vm, void* activity, int version, const char* name) {} inline void EnterVR(bool firstTime) {} inline void GetVRResolutionPerEye(int* width, int* height) {} inline void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale) {} From 42b2b0a2663246a5bc2a6265a59cb77bf794bce3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 11:54:20 +0200 Subject: [PATCH 048/110] atrac3: Apply the overallocation workaround in a couple more places. Fixes #15788 . --- Core/HLE/sceAtrac.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index 3e6fb45d2b..f336d8713b 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -116,6 +116,8 @@ const int PSP_ATRAC_LOOP_STREAM_DATA_IS_ON_MEMORY = -3; const u32 ATRAC3_MAX_SAMPLES = 0x400; const u32 ATRAC3PLUS_MAX_SAMPLES = 0x800; +const size_t overAllocBytes = 16384; + static const int atracDecodeDelay = 2300; #ifdef USE_FFMPEG @@ -264,7 +266,8 @@ struct Atrac { if (p.mode == p.MODE_READ) { if (dataBuf_) delete [] dataBuf_; - dataBuf_ = new u8[first_.filesize]; + dataBuf_ = new u8[first_.filesize + overAllocBytes]; + memset(dataBuf_, 0, first_.filesize + overAllocBytes); } DoArray(p, dataBuf_, first_.filesize); } @@ -453,7 +456,7 @@ struct Atrac { #else // Future versions may add other things to free, but avcodec_free_context didn't exist yet here. // Some old versions crash when we try to free extradata and subtitle_header, so let's not. A minor - // leak is better than a segfualt. + // leak is better than a segfault. // av_freep(&codecCtx_->extradata); // av_freep(&codecCtx_->subtitle_header); avcodec_close(codecCtx_); @@ -1951,7 +1954,6 @@ static int _AtracSetData(Atrac *atrac, u32 buffer, u32 readSize, u32 bufferSize, // Over-allocate databuf to prevent going off the end if the bitstream is bad or if there are // bugs in the decoder. This happens, see issue #15788. Arbitrary, but let's make it a whole page on the popular // architecture that has the largest pages (M1). - const size_t overAllocBytes = 16384; atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); if (!atrac->ignoreDataBuf_) { @@ -2460,7 +2462,9 @@ static int sceAtracLowLevelInitDecoder(int atracID, u32 paramsAddr) { atrac->first_.size = 0; atrac->first_.filesize = atrac->bytesPerFrame_; atrac->bufferState_ = ATRAC_STATUS_LOW_LEVEL; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); atrac->currentSample_ = 0; int ret = __AtracSetContext(atrac); From a6e4ec9973761ea223149ae5b7bb5f0c28696197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 10:25:41 +0200 Subject: [PATCH 049/110] Atrac3+: Allocate some extra bytes for the data buffer to workaround decoder bug. --- Core/HLE/sceAtrac.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index f44ba65fe1..e0ec6a38a5 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -1940,7 +1940,12 @@ static int _AtracSetData(Atrac *atrac, u32 buffer, u32 readSize, u32 bufferSize, const char *codecName = atrac->codecType_ == PSP_MODE_AT_3 ? "atrac3" : "atrac3+"; const char *channelName = atrac->channels_ == 1 ? "mono" : "stereo"; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + // Over-allocate databuf to prevent going off the end if the bitstream is bad or if there are + // bugs in the decoder. This happens, see issue #15788. Arbitrary, but let's make it a whole page on the popular + // architecture that has the largest pages (M1). + const size_t overAllocBytes = 16384; + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); if (!atrac->ignoreDataBuf_) { u32 copybytes = std::min(bufferSize, atrac->first_.filesize); Memory::Memcpy(atrac->dataBuf_, buffer, copybytes, "AtracSetData"); From 733152969b44a898f3a0a5ed6b6877eeb4e864aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 11:54:20 +0200 Subject: [PATCH 050/110] atrac3: Apply the overallocation workaround in a couple more places. Fixes #15788 . --- Core/HLE/sceAtrac.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index e0ec6a38a5..087e534932 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -115,6 +115,8 @@ const int PSP_ATRAC_LOOP_STREAM_DATA_IS_ON_MEMORY = -3; const u32 ATRAC3_MAX_SAMPLES = 0x400; const u32 ATRAC3PLUS_MAX_SAMPLES = 0x800; +const size_t overAllocBytes = 16384; + static const int atracDecodeDelay = 2300; #ifdef USE_FFMPEG @@ -263,7 +265,8 @@ struct Atrac { if (p.mode == p.MODE_READ) { if (dataBuf_) delete [] dataBuf_; - dataBuf_ = new u8[first_.filesize]; + dataBuf_ = new u8[first_.filesize + overAllocBytes]; + memset(dataBuf_, 0, first_.filesize + overAllocBytes); } DoArray(p, dataBuf_, first_.filesize); } @@ -452,7 +455,7 @@ struct Atrac { #else // Future versions may add other things to free, but avcodec_free_context didn't exist yet here. // Some old versions crash when we try to free extradata and subtitle_header, so let's not. A minor - // leak is better than a segfualt. + // leak is better than a segfault. // av_freep(&codecCtx_->extradata); // av_freep(&codecCtx_->subtitle_header); avcodec_close(codecCtx_); @@ -1943,7 +1946,6 @@ static int _AtracSetData(Atrac *atrac, u32 buffer, u32 readSize, u32 bufferSize, // Over-allocate databuf to prevent going off the end if the bitstream is bad or if there are // bugs in the decoder. This happens, see issue #15788. Arbitrary, but let's make it a whole page on the popular // architecture that has the largest pages (M1). - const size_t overAllocBytes = 16384; atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); if (!atrac->ignoreDataBuf_) { @@ -2452,7 +2454,9 @@ static int sceAtracLowLevelInitDecoder(int atracID, u32 paramsAddr) { atrac->first_.size = 0; atrac->first_.filesize = atrac->bytesPerFrame_; atrac->bufferState_ = ATRAC_STATUS_LOW_LEVEL; - atrac->dataBuf_ = new u8[atrac->first_.filesize]; + + atrac->dataBuf_ = new u8[atrac->first_.filesize + overAllocBytes]; + memset(atrac->dataBuf_, 0, atrac->first_.filesize + overAllocBytes); atrac->currentSample_ = 0; int ret = __AtracSetContext(atrac); From 4b66f967f4c6767f27e5be52a4e2b580001a4863 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Fri, 12 Aug 2022 23:48:25 -0700 Subject: [PATCH 051/110] softgpu: Correct bad munmap() size. --- GPU/Software/TransformUnit.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index 378b558bea..3719277141 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -46,7 +46,7 @@ TransformUnit::TransformUnit() { } TransformUnit::~TransformUnit() { - FreeMemoryPages(decoded_, DECODED_VERTEX_BUFFER_SIZE); + FreeMemoryPages(decoded_, TRANSFORM_BUF_SIZE); delete binner_; } From 6e5f056000a59ab59348e6219e6199af3f26bb6e Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 13 Aug 2022 00:16:08 -0700 Subject: [PATCH 052/110] Atrac: Avoid an uninitialized value. --- Core/HLE/sceAtrac.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index 087e534932..ba7d5f57b7 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -404,7 +404,7 @@ struct Atrac { // Used by low-level decoding and to track streaming. u32 bufferPos_; u32 bufferValidBytes_; - u32 bufferHeaderSize_; + u32 bufferHeaderSize_ = 0; u16 channels_; u16 outputChannels_; From e356c495db5023af27eb48d053cb48579a9aa0e3 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 13 Aug 2022 08:09:16 -0700 Subject: [PATCH 053/110] Atrac: Avoid accessing uninitialized stream status. Only mess with this in a stream mode. --- Core/HLE/sceAtrac.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index ba7d5f57b7..4db3087283 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -622,10 +622,12 @@ struct Atrac { void ConsumeFrame() { bufferPos_ += bytesPerFrame_; - if (bufferValidBytes_ > bytesPerFrame_) { - bufferValidBytes_ -= bytesPerFrame_; - } else { - bufferValidBytes_ = 0; + if ((bufferState_ & ATRAC_STATUS_STREAMED_MASK) == ATRAC_STATUS_STREAMED_MASK) { + if (bufferValidBytes_ > bytesPerFrame_) { + bufferValidBytes_ -= bytesPerFrame_; + } else { + bufferValidBytes_ = 0; + } } if (bufferPos_ >= StreamBufferEnd()) { // Wrap around... theoretically, this should only happen at exactly StreamBufferEnd. From dab4365557c71b0a5208221fa97482d7f710cb1f Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 13 Aug 2022 08:10:46 -0700 Subject: [PATCH 054/110] Font: Correct uninitialized values. --- Core/HLE/sceFont.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Core/HLE/sceFont.cpp b/Core/HLE/sceFont.cpp index 951b0700c0..e91eeef88b 100644 --- a/Core/HLE/sceFont.cpp +++ b/Core/HLE/sceFont.cpp @@ -486,8 +486,7 @@ public: // For save states only. } - FontLib(u32 paramPtr, u32 errorCodePtr) : fontHRes_(128.0f), fontVRes_(128.0f), altCharCode_(0x5F), charInfoBitmapAddress_(0) { - nfl_ = 0; + FontLib(u32 paramPtr, u32 errorCodePtr) { Memory::ReadStruct(paramPtr, ¶ms_); if (params_.numFonts > 9) { params_.numFonts = 9; @@ -753,14 +752,14 @@ private: std::vector fontRefCount_; FontNewLibParams params_; - float fontHRes_; - float fontVRes_; - int fileFontHandle_; - int handle_; - int altCharCode_; + float fontHRes_ = 128.0f; + float fontVRes_ = 128.0f; + int fileFontHandle_ = -1; + int handle_ = -1; + int altCharCode_ = 0x5F; std::vector openAllocatedAddresses_; - u32 charInfoBitmapAddress_; - PSPPointer nfl_; + u32 charInfoBitmapAddress_ = 0; + PSPPointer nfl_{}; DISALLOW_COPY_AND_ASSIGN(FontLib); }; From 024f8ef89bb40e80c755cb4ef04ecf5dcafc16f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 18 Aug 2022 15:20:16 +0200 Subject: [PATCH 055/110] Initialize a bunch of Dialog structs --- Core/Dialog/PSPDialog.h | 10 +++++----- Core/Dialog/PSPGamedataInstallDialog.h | 18 +++++++++--------- Core/Dialog/PSPMsgDialog.h | 6 +++--- Core/Dialog/PSPOskDialog.h | 9 ++++----- Core/Dialog/PSPSaveDialog.h | 6 +++--- Core/Dialog/SavedataParam.cpp | 11 +---------- Core/Dialog/SavedataParam.h | 13 ++++++------- 7 files changed, 31 insertions(+), 42 deletions(-) diff --git a/Core/Dialog/PSPDialog.h b/Core/Dialog/PSPDialog.h index 54a9488e36..636fc20334 100644 --- a/Core/Dialog/PSPDialog.h +++ b/Core/Dialog/PSPDialog.h @@ -99,7 +99,7 @@ protected: void ChangeStatus(DialogStatus newStatus, int delayUs); void ChangeStatusInit(int delayUs); void ChangeStatusShutdown(int delayUs); - DialogStatus ReadStatus() { + DialogStatus ReadStatus() const { return status; } @@ -117,10 +117,10 @@ protected: unsigned int lastButtons = 0; unsigned int buttons = 0; - float fadeTimer; - bool isFading; - bool fadeIn; - u32 fadeValue; + float fadeTimer = 0.0f; + bool isFading = false; + bool fadeIn = false; + u32 fadeValue = 0; ImageID okButtonImg; ImageID cancelButtonImg; diff --git a/Core/Dialog/PSPGamedataInstallDialog.h b/Core/Dialog/PSPGamedataInstallDialog.h index 3dfd8687ef..e669a31873 100644 --- a/Core/Dialog/PSPGamedataInstallDialog.h +++ b/Core/Dialog/PSPGamedataInstallDialog.h @@ -59,16 +59,16 @@ private: void CloseCurrentFile(); void WriteSfoFile(); - SceUtilityGamedataInstallParam request; + SceUtilityGamedataInstallParam request{}; PSPPointer param; std::vector inFileNames; - int numFiles; - int readFiles; - u64 allFilesSize; // use this to calculate progress value. - u64 allReadSize; // use this to calculate progress value. - int progressValue; + int numFiles = 0; + int readFiles = 0; + u64 allFilesSize = 0; // use this to calculate progress value. + u64 allReadSize = 0; // use this to calculate progress value. + int progressValue = 0; - int currentInputFile; - u32 currentInputBytesLeft; - int currentOutputFile; + int currentInputFile = 0; + u32 currentInputBytesLeft = 0; + int currentOutputFile = 0; }; diff --git a/Core/Dialog/PSPMsgDialog.h b/Core/Dialog/PSPMsgDialog.h index e5912d2ee3..78ee4e54f4 100644 --- a/Core/Dialog/PSPMsgDialog.h +++ b/Core/Dialog/PSPMsgDialog.h @@ -94,11 +94,11 @@ private: u32 flag = 0; - pspMessageDialog messageDialog; - int messageDialogAddr; + pspMessageDialog messageDialog{}; + int messageDialogAddr = 0; char msgText[512]; - int yesnoChoice; + int yesnoChoice = 0; float scrollPos_ = 0.0f; int framesUpHeld_ = 0; int framesDownHeld_ = 0; diff --git a/Core/Dialog/PSPOskDialog.h b/Core/Dialog/PSPOskDialog.h index 8eb55586c0..c760afb1e4 100644 --- a/Core/Dialog/PSPOskDialog.h +++ b/Core/Dialog/PSPOskDialog.h @@ -148,7 +148,6 @@ struct SceUtilityOskParams SceUtilityOskState_le state; // Maybe just padding? s32_le unk_60; - }; // Internal enum, not from PSP. @@ -245,16 +244,16 @@ private: std::string oskIntext; std::string oskOuttext; - int selectedChar; + int selectedChar = 0; std::u16string inputChars; OskKeyboardDisplay currentKeyboard; OskKeyboardLanguage currentKeyboardLanguage; - bool isCombinated; + bool isCombinated = false; std::mutex nativeMutex_; PSPOskNativeStatus nativeStatus_ = PSPOskNativeStatus::IDLE; std::string nativeValue_; - int i_level; // for Korean Keyboard support - int i_value[3]; // for Korean Keyboard support + int i_level = 0; // for Korean Keyboard support + int i_value[3]{}; // for Korean Keyboard support }; diff --git a/Core/Dialog/PSPSaveDialog.h b/Core/Dialog/PSPSaveDialog.h index 8058d8a962..90f8d6312a 100644 --- a/Core/Dialog/PSPSaveDialog.h +++ b/Core/Dialog/PSPSaveDialog.h @@ -139,13 +139,13 @@ private: DisplayState display = DS_NONE; SavedataParam param; - SceUtilitySavedataParam request; + SceUtilitySavedataParam request{}; // For detecting changes made by the game. - SceUtilitySavedataParam originalRequest; + SceUtilitySavedataParam originalRequest{}; u32 requestAddr = 0; int currentSelectedSave = 0; - int yesnoChoice; + int yesnoChoice = 0; enum SaveIOStatus { diff --git a/Core/Dialog/SavedataParam.cpp b/Core/Dialog/SavedataParam.cpp index f4ba47a20e..980a3edf31 100644 --- a/Core/Dialog/SavedataParam.cpp +++ b/Core/Dialog/SavedataParam.cpp @@ -193,16 +193,7 @@ void SaveFileInfo::DoState(PointerWrap &p) } } -SavedataParam::SavedataParam() - : pspParam(0) - , selectedSave(0) - , saveDataList(0) - , noSaveIcon(0) - , saveDataListCount(0) - , saveNameListDataCount(0) -{ - -} +SavedataParam::SavedataParam() { } void SavedataParam::Init() { diff --git a/Core/Dialog/SavedataParam.h b/Core/Dialog/SavedataParam.h index b7daa02845..e7bdf9ad46 100644 --- a/Core/Dialog/SavedataParam.h +++ b/Core/Dialog/SavedataParam.h @@ -265,7 +265,6 @@ struct SceUtilitySavedataParam // Function 22 GETSIZES PSPPointer sizeInfo; - }; // Non native, this one we can reorganize as we like @@ -377,10 +376,10 @@ private: std::set GetSecureFileNames(const std::string &dirPath); bool GetExpectedHash(const std::string &dirPath, const std::string &filename, u8 hash[16]); - SceUtilitySavedataParam* pspParam; - int selectedSave; - SaveFileInfo *saveDataList; - SaveFileInfo *noSaveIcon; - int saveDataListCount; - int saveNameListDataCount; + SceUtilitySavedataParam* pspParam = nullptr; + int selectedSave = 0; + SaveFileInfo *saveDataList = nullptr; + SaveFileInfo *noSaveIcon = nullptr; + int saveDataListCount = 0; + int saveNameListDataCount = 0; }; From 80e0bb9c1f8eb3f2abadc7f348992fc3331ebc26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Thu, 1 Sep 2022 11:54:48 +0200 Subject: [PATCH 056/110] Remove a per-audio-frame allocation in sceAudio --- Core/HLE/__sceAudio.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/Core/HLE/__sceAudio.cpp b/Core/HLE/__sceAudio.cpp index 9632d90e0b..3176d26130 100644 --- a/Core/HLE/__sceAudio.cpp +++ b/Core/HLE/__sceAudio.cpp @@ -64,8 +64,8 @@ int srcFrequency = 0; const int hwSampleRate = 44100; -int hwBlockSize = 64; -int hostAttemptBlockSize = 512; +const int hwBlockSize = 64; +const int hostAttemptBlockSize = 512; static int audioIntervalCycles; static int audioHostIntervalCycles; @@ -110,8 +110,6 @@ void __AudioInit() { chanQueueMaxSizeFactor = 2; chanQueueMinSizeFactor = 1; - hwBlockSize = 64; - hostAttemptBlockSize = 512; __AudioCPUMHzChange(); @@ -338,7 +336,8 @@ void __AudioUpdate(bool resetRecording) { // to the CPU. Much better to throttle the frame rate on frame display and just throw away audio // if the buffer somehow gets full. bool firstChannel = true; - std::vector srcBuffer; + const int16_t srcBufferSize = hwBlockSize * 2; + int16_t srcBuffer[srcBufferSize]; for (u32 i = 0; i < PSP_AUDIO_CHANNEL_MAX + 1; i++) { if (!chans[i].reserved) @@ -351,7 +350,7 @@ void __AudioUpdate(bool resetRecording) { } bool needsResample = i == PSP_AUDIO_CHANNEL_SRC && srcFrequency != 0 && srcFrequency != mixFrequency; - size_t sz = needsResample ? (hwBlockSize * 2 * srcFrequency) / mixFrequency : hwBlockSize * 2; + size_t sz = needsResample ? (srcBufferSize * srcFrequency) / mixFrequency : srcBufferSize; if (sz > chanSampleQueues[i].size()) { ERROR_LOG(SCEAUDIO, "Channel %i buffer underrun at %i of %i", i, (int)chanSampleQueues[i].size() / 2, (int)sz / 2); } @@ -372,13 +371,11 @@ void __AudioUpdate(bool resetRecording) { return buf1[sz1 - 1]; }; - srcBuffer.resize(hwBlockSize * 2); - // TODO: This is terrible, since it's doing it by small chunk and discarding frac. const uint32_t ratio = (uint32_t)(65536.0 * srcFrequency / (double)mixFrequency); uint32_t frac = 0; size_t readIndex = 0; - for (size_t outIndex = 0; readIndex < sz && outIndex < srcBuffer.size(); outIndex += 2) { + for (size_t outIndex = 0; readIndex < sz && outIndex < srcBufferSize; outIndex += 2) { size_t readIndex2 = readIndex + 2; int16_t l1 = read(readIndex); int16_t r1 = read(readIndex + 1); @@ -393,8 +390,8 @@ void __AudioUpdate(bool resetRecording) { frac &= 0xffff; } - buf1 = srcBuffer.data(); - sz1 = srcBuffer.size(); + buf1 = srcBuffer; + sz1 = srcBufferSize; buf2 = nullptr; sz2 = 0; } From 04a89950804623a9a4650e1b9fb4137b208cf11d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 22 Aug 2022 21:29:49 -0700 Subject: [PATCH 057/110] D3D11: Correct viewport offset sign handling. --- GPU/D3D11/DrawEngineD3D11.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index 8715116b30..d4cb80738d 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -602,7 +602,7 @@ rotateVBO: int maxIndex = indexGen.MaxIndex(); SoftwareTransform swTransform(params); - const Lin::Vec3 trans(gstate_c.vpXOffset, gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset, -gstate_c.vpYOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, -gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight < 0, trans, scale); From 79b864b89a8a656f43ae56ed2322f1161aec6385 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Mon, 22 Aug 2022 21:30:10 -0700 Subject: [PATCH 058/110] D3D9: Correct viewport offset sign. --- GPU/Directx9/DrawEngineDX9.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index 216bc7a8a0..154aa89b77 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -575,12 +575,10 @@ rotateVBO: SoftwareTransform swTransform(params); // Half pixel offset hack. - float xScale = gstate_c.vpWidth < 0 ? -1.0f : 1.0f; float xOffset = -1.0f / gstate_c.curRTRenderWidth; - float yScale = gstate_c.vpHeight > 0 ? -1.0f : 1.0f; float yOffset = 1.0f / gstate_c.curRTRenderHeight; - const Lin::Vec3 trans(gstate_c.vpXOffset * xScale + xOffset, gstate_c.vpYOffset * yScale + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); + const Lin::Vec3 trans(gstate_c.vpXOffset + xOffset, -gstate_c.vpYOffset + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f); const Lin::Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f); swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight > 0, trans, scale); From a5564c2ce252e917a57c06df069096f75d901194 Mon Sep 17 00:00:00 2001 From: iota97 Date: Fri, 29 Jul 2022 20:15:09 +0200 Subject: [PATCH 059/110] readme link --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 66485598b3..03df3bca66 100644 --- a/README.md +++ b/README.md @@ -512,4 +512,9 @@ Credit goes to: [#15687]: https://github.com/hrydgard/ppsspp/issues/15687 "Add Zettai Zetsumei Toshi 3" [#7295]: https://github.com/hrydgard/ppsspp/issues/7295 "Juiced 2: Hot Import Nights, screen artifacts and missing half of race tracks" [#15717]: https://github.com/hrydgard/ppsspp/issues/15717 "Allows \"merging\" render targets that overlap on the Y axis. Fixes Juiced 2" -[#15698]: https://github.com/hrydgard/ppsspp/issues/15698 "Osk: Allow upper/lower for all keyboards" \ No newline at end of file +[#15698]: https://github.com/hrydgard/ppsspp/issues/15698 "Osk: Allow upper/lower for all keyboards" +[#15738]: https://github.com/hrydgard/ppsspp/issues/15738 "Add confirmation dialog when generating a new Mac address" +[#15739]: https://github.com/hrydgard/ppsspp/issues/15739 "irjit: Correct another PurgeTemps case" +[#15740]: https://github.com/hrydgard/ppsspp/issues/15740 "Replacement: Clear cache on disable" +[#15734]: https://github.com/hrydgard/ppsspp/issues/15734 "Better pt-pt translation" +[#15733]: https://github.com/hrydgard/ppsspp/issues/15733 "Fix bug in blue-to-alpha - alpha blending could be on when it shouldn't be." From e56e5947d5d4cadad7e69f2f3c3dbfea5d95a15b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 10 Sep 2022 00:26:23 +0200 Subject: [PATCH 060/110] Vulkan: Declare gl_Position as invariant. See #11583 The code that computes shader outputs declared as invariant gets certain optimizations disabled that could change the value - it makes it more likely that different ways to do the same calculations end up with the same value. This can help some types of Z fighting problems and similar. Generally not a big deal for performance, plus, we're rarely vshader-bottlenecked... --- GPU/Common/VertexShaderGenerator.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GPU/Common/VertexShaderGenerator.cpp b/GPU/Common/VertexShaderGenerator.cpp index 071f1f4f5b..ccda9af86b 100644 --- a/GPU/Common/VertexShaderGenerator.cpp +++ b/GPU/Common/VertexShaderGenerator.cpp @@ -276,6 +276,9 @@ bool GenerateVertexShader(const VShaderID &id, char *buffer, const ShaderLanguag // See the fragment shader generator WRITE(p, "layout (location = 3) out highp float v_fogdepth;\n"); } + + WRITE(p, "invariant gl_Position;\n"); + } else if (compat.shaderLanguage == HLSL_D3D11 || compat.shaderLanguage == HLSL_D3D9) { // Note: These two share some code after this hellishly large if/else. if (compat.shaderLanguage == HLSL_D3D11) { From d560c790198f0f5c502428d9edc2e1e106cb70fc Mon Sep 17 00:00:00 2001 From: Stephan Sokolow Date: Sat, 10 Sep 2022 01:54:13 +0000 Subject: [PATCH 061/110] Add Emulator to Categories in ppsspp.desktop.in Add the "Emulator" subcategory to the .desktop file so launchers can better auto-sort their contents. --- ppsspp.desktop.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ppsspp.desktop.in b/ppsspp.desktop.in index 49debf93c0..05fd1e7348 100644 --- a/ppsspp.desktop.in +++ b/ppsspp.desktop.in @@ -4,4 +4,4 @@ Exec=@TargetBin@ Icon=ppsspp Type=Application Comment=ppsspp (fast and portable PSP emulator) -Categories=Game +Categories=Game;Emulator From fbc02bdf1253f4977eff338050fbccdb5a70c2e0 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 21 Aug 2022 00:27:31 -0700 Subject: [PATCH 062/110] softgpu: Correct morph weight updates. Broke LittleBigPlanet character's face, for example. --- GPU/Software/SoftGpu.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index 6a4ddf88b7..502362104e 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -201,14 +201,14 @@ const SoftwareCommandTableEntry softgpuCommandTable[] = { { GE_CMD_CLUTFORMAT, 0, SoftDirty::SAMPLER_BASIC }, // Morph weights. TODO: Remove precomputation? - { GE_CMD_MORPHWEIGHT0, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT1, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT2, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT3, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT4, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT5, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT6, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, - { GE_CMD_MORPHWEIGHT7, 0, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT0, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT1, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT2, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT3, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT4, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT5, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT6, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, + { GE_CMD_MORPHWEIGHT7, FLAG_EXECUTEONCHANGE, SoftDirty::NONE, &GPUCommon::Execute_MorphWeight }, // No state of flushing required for patch parameters, currently. { GE_CMD_PATCHDIVISION }, From 38ba29240b4cff4fe075a9d0d11d4b12500fd987 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 20 Aug 2022 14:03:24 -0700 Subject: [PATCH 063/110] GPU: Dirty params when converting viewport state. This flag will be false when we convert next time, so parameters won't get updated as expected. --- GPU/D3D11/DrawEngineD3D11.cpp | 7 +++++++ GPU/Directx9/DrawEngineDX9.cpp | 7 +++++++ GPU/GLES/DrawEngineGLES.cpp | 7 +++++++ GPU/Vulkan/DrawEngineVulkan.cpp | 7 +++++++ 4 files changed, 28 insertions(+) diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index d4cb80738d..73fc93f217 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -597,6 +597,13 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index 154aa89b77..5fc0f29171 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -569,6 +569,13 @@ rotateVBO: framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index f8f7a2cbbc..7a06fd4c64 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -366,6 +366,13 @@ void DrawEngineGLES::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 0c464853e6..5676980c7b 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -868,6 +868,13 @@ void DrawEngineVulkan::DoFlush() { framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(), framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(), vpAndScissor); + + if (vpAndScissor.dirtyProj) { + gstate_c.Dirty(DIRTY_PROJMATRIX); + } + if (vpAndScissor.dirtyDepth) { + gstate_c.Dirty(DIRTY_DEPTHRANGE); + } } int maxIndex = indexGen.MaxIndex(); From cc25ec5faa44fe91d4cf07aee2b56449d7e64b7c Mon Sep 17 00:00:00 2001 From: rofl0r Date: Sat, 30 Jul 2022 20:50:56 +0000 Subject: [PATCH 064/110] CI: also upload release source tarball on tag push the mac os build action uses an action that automatically creates a release from a tag push, which circumvents triggering the regular release actions. also switch from the unmaintained actions/upload-release-asset@v1 to the active softprops/action-gh-release@v1 action. closes #15761 --- .github/workflows/tarball.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/tarball.yml b/.github/workflows/tarball.yml index add0f685d8..d8c5fac636 100644 --- a/.github/workflows/tarball.yml +++ b/.github/workflows/tarball.yml @@ -5,6 +5,9 @@ on: release: types: - created + push: + tags: + - "v*.*.*" jobs: build: @@ -19,7 +22,9 @@ jobs: - name: archive id: archive run: | - VERSION=$(printf "%s\n" ${{ github.event.release.tag_name }} | sed 's/^v//') + VERSION=${GITHUB_REF##*/} + test -z "$VERSION" && VERSION=${{ github.event.release.tag_name }} + VERSION=$(printf "%s\n" "$VERSION" | sed 's/^v//') PKGNAME="ppsspp-$VERSION" mkdir -p /tmp/$PKGNAME mv * /tmp/$PKGNAME @@ -38,11 +43,7 @@ jobs: echo "::set-output name=tarball::$TARBALL" - name: upload tarball - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: softprops/action-gh-release@v1 with: - upload_url: ${{ github.event.release.upload_url }} - asset_path: ./${{ steps.archive.outputs.tarball }} - asset_name: ${{ steps.archive.outputs.tarball }} - asset_content_type: application/x-xz + files: ${{ steps.archive.outputs.tarball }} + token: ${{ secrets.GITHUB_TOKEN }} From d41b94d12d1a627002f153d3f5d6f3b146a2b55d Mon Sep 17 00:00:00 2001 From: rofl0r Date: Sun, 31 Jul 2022 04:41:19 +0000 Subject: [PATCH 065/110] CI: make indentation in tarball.yml consistent --- .github/workflows/tarball.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tarball.yml b/.github/workflows/tarball.yml index d8c5fac636..f7f625e3b4 100644 --- a/.github/workflows/tarball.yml +++ b/.github/workflows/tarball.yml @@ -45,5 +45,5 @@ jobs: - name: upload tarball uses: softprops/action-gh-release@v1 with: - files: ${{ steps.archive.outputs.tarball }} - token: ${{ secrets.GITHUB_TOKEN }} + files: ${{ steps.archive.outputs.tarball }} + token: ${{ secrets.GITHUB_TOKEN }} From 4090112bf80929c6ad22a711188e64742ba810dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 9 Sep 2022 11:16:25 +0200 Subject: [PATCH 066/110] Update README.md for v1.13.2 --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 03df3bca66..688da9568b 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,12 @@ If you want to download regularly updated builds for Android, Windows x86 and x6 For game compatibility, see [community compatibility feedback](https://report.ppsspp.org/games). +What's new in 1.13.2 +==================== +* Crashfix on Android 12 when playing certain background music ([#15990]) +* Fix Star Ocean battles in D3D backends (#[15889]) +* Minor fixes that might fix some other crashes + What's new in 1.13.1 ==================== @@ -518,3 +524,4 @@ Credit goes to: [#15740]: https://github.com/hrydgard/ppsspp/issues/15740 "Replacement: Clear cache on disable" [#15734]: https://github.com/hrydgard/ppsspp/issues/15734 "Better pt-pt translation" [#15733]: https://github.com/hrydgard/ppsspp/issues/15733 "Fix bug in blue-to-alpha - alpha blending could be on when it shouldn't be." +[#15990]: https://github.com/hrydgard/ppsspp/issues/15990 "Atrac3+: Allocate some extra bytes for the data buffer to workaround decoder bug." From 9fe6338e3bf397f8a009a51a282c139dfa180eb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 10 Sep 2022 15:50:49 +0200 Subject: [PATCH 067/110] Update version to 1.13.2 --- android/AndroidManifest.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index fbb5332b0d..bee1ccda15 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -3,8 +3,8 @@ xmlns:tools="http://schemas.android.com/tools" package="org.ppsspp.ppsspp" android:installLocation="auto" - android:versionCode="113010000" - android:versionName="1.13.1.0"> + android:versionCode="113020000" + android:versionName="1.13.2.0"> From 54fe342f4b0cfab29095b120f3f377704f0c4464 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 08:30:09 -0700 Subject: [PATCH 068/110] Vulkan: Wake compile thread when enqueued. Previously was being woken up every frame unconditionally, causing some logspam. --- Common/GPU/Vulkan/VulkanRenderManager.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 52f0b8fb27..10cc890009 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -553,6 +553,7 @@ void VulkanRenderManager::CompileThreadFunc() { void VulkanRenderManager::DrainCompileQueue() { std::unique_lock lock(compileMutex_); + compileCond_.notify_all(); while (!compileQueue_.empty()) { queueRunner_.WaitForCompileNotification(); } @@ -733,13 +734,17 @@ VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipe }; VKRRenderPass *compatibleRenderPass = queueRunner_.GetRenderPass(key); compileMutex_.lock(); + bool needsCompile = false; for (int i = 0; i < RP_TYPE_COUNT; i++) { if (!(variantBitmask & (1 << i))) continue; RenderPassType rpType = (RenderPassType)i; pipeline->pipeline[rpType] = Promise::CreateEmpty(); compileQueue_.push_back(CompileQueueEntry(pipeline, compatibleRenderPass->Get(vulkan_, rpType), rpType)); + needsCompile = true; } + if (needsCompile) + compileCond_.notify_one(); compileMutex_.unlock(); } return pipeline; @@ -775,13 +780,16 @@ void VulkanRenderManager::EndCurRenderStep() { // Save the accumulated pipeline flags so we can use that to configure the render pass. // We'll often be able to avoid loading/saving the depth/stencil buffer. compileMutex_.lock(); + bool needsCompile = false; for (VKRGraphicsPipeline *pipeline : pipelinesToCheck_) { if (!pipeline->pipeline[rpType]) { pipeline->pipeline[rpType] = Promise::CreateEmpty(); compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType)); + needsCompile = true; } } - compileCond_.notify_one(); + if (needsCompile) + compileCond_.notify_one(); compileMutex_.unlock(); pipelinesToCheck_.clear(); From c200aa6f4b58f8ae33fd9e81167082b7fa34f377 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 08:52:50 -0700 Subject: [PATCH 069/110] GE Debugger: Correct cond break removal warnings. Oops, they were just always confirming. --- Windows/GEDebugger/TabState.cpp | 4 ++-- Windows/GEDebugger/TabVertices.cpp | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Windows/GEDebugger/TabState.cpp b/Windows/GEDebugger/TabState.cpp index da1baa10bf..200eb9ae75 100644 --- a/Windows/GEDebugger/TabState.cpp +++ b/Windows/GEDebugger/TabState.cpp @@ -910,7 +910,7 @@ void CtrlStateValues::OnDoubleClick(int row, int column) { if (column == STATEVALUES_COL_BREAKPOINT) { bool proceed = true; - if (IsCmdBreakpoint(info.cmd)) { + if (GetCmdBreakpointCond(info.cmd, nullptr)) { int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); proceed = ret == IDYES; } @@ -993,7 +993,7 @@ void CtrlStateValues::OnRightClick(int row, int column, const POINT &point) { { case ID_DISASM_TOGGLEBREAKPOINT: { bool proceed = true; - if (IsCmdBreakpoint(info.cmd)) { + if (GetCmdBreakpointCond(info.cmd, nullptr)) { int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); proceed = ret == IDYES; } diff --git a/Windows/GEDebugger/TabVertices.cpp b/Windows/GEDebugger/TabVertices.cpp index 9606672840..f7ab9af7ac 100644 --- a/Windows/GEDebugger/TabVertices.cpp +++ b/Windows/GEDebugger/TabVertices.cpp @@ -571,9 +571,11 @@ void CtrlMatrixList::ToggleBreakpoint(int row) { if (state) { GPUBreakpoints::AddCmdBreakpoint(info->cmd); } else { - int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); - if (ret != IDYES) - return; + if (GPUBreakpoints::GetCmdBreakpointCond(info->cmd, nullptr)) { + int ret = MessageBox(GetHandle(), L"This breakpoint has a custom condition.\nDo you want to remove it?", L"Confirmation", MB_YESNO); + if (ret != IDYES) + return; + } GPUBreakpoints::RemoveCmdBreakpoint(info->cmd); } From a2ca85bc8723ec04c171dc8b308b3b69a43b227f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sat, 10 Sep 2022 19:32:39 +0200 Subject: [PATCH 070/110] Add logging for LoadCLUT from framebuffer. See #15923 . Logs nicely in Burnout Dominator. --- GPU/Common/TextureCacheCommon.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 8d58346a8c..eaef9ea6da 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1177,6 +1177,7 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { // And is it inside the rendered area? Sometimes games pack data outside. bool matchRegion = ((offset / bpp) % framebuffer->fb_stride) < framebuffer->width; if (matchRange && matchRegion && offset < clutRenderOffset_) { + WARN_LOG_N_TIMES(clutfb, 5, G3D, "LoadCLUT(%d bytes) from framebuffer %08x (%s), byte offset %d", loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), offset); framebuffer->last_frame_clut = gpuStats.numFlips; framebuffer->usageFlags |= FB_USAGE_CLUT; clutRenderAddress_ = framebuffer->fb_address; From 6004d4a4596106056d1fbccfe00f66fa2348a2cb Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 13:28:35 -0700 Subject: [PATCH 071/110] softgpu: Refactor duplicate rectangle compat check. This just moves the logic to a single place for changes. --- GPU/Software/RasterizerRectangle.cpp | 52 ++++++++++++---------------- GPU/Software/SoftGpu.cpp | 2 +- 2 files changed, 23 insertions(+), 31 deletions(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index f25be97f64..7408b1558b 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -321,26 +321,32 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b return false; } +static bool AreCoordsRectangleCompatible(const RasterizerState &state, const VertexData &data0, const VertexData &data1) { + if (!(data1.color0 == data0.color0)) + return false; + if (!(data1.screenpos.z == data0.screenpos.z)) { + // Sometimes, we don't actually care about z. + if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) + return false; + } + if (!state.throughMode) { + if (!state.throughMode && !(data1.color1 == data0.color1)) + return false; + // Do we have to think about perspective correction or slope mip level? + if (state.enableTextures && data1.clippos.w != data0.clippos.w) + return false; + if (state.pixelID.applyFog && data1.fogdepth != data0.fogdepth) + return false; + } + return true; +} + bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData data[4], int *tlIndex, int *brIndex) { // Color and Z must be flat. Also find the TL and BR meanwhile. int tl = 0, br = 0; for (int i = 1; i < 4; ++i) { - if (!(data[i].color0 == data[0].color0)) + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) return false; - if (!(data[i].screenpos.z == data[0].screenpos.z)) { - // Sometimes, we don't actually care about z. - if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) - return false; - } - if (!state.throughMode) { - if (!state.throughMode && !(data[i].color1 == data[0].color1)) - return false; - // Do we have to think about perspective correction or slope mip level? - if (state.enableTextures && data[i].clippos.w != data[0].clippos.w) - return false; - if (state.pixelID.applyFog && data[i].fogdepth != data[0].fogdepth) - return false; - } if (data[i].screenpos.x <= data[tl].screenpos.x && data[i].screenpos.y <= data[tl].screenpos.y) tl = i; @@ -394,22 +400,8 @@ bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData dat bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data, int c, int *tlIndex, int *brIndex) { // Color and Z must be flat. for (int i = 1; i < c; ++i) { - if (!(data[i].color0 == data[0].color0)) + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) return false; - if (!(data[i].screenpos.z == data[0].screenpos.z)) { - // Sometimes, we don't actually care about z. - if (state.pixelID.depthWrite || state.pixelID.DepthTestFunc() != GE_COMP_ALWAYS) - return false; - } - if (!state.throughMode) { - if (!state.throughMode && !(data[i].color1 == data[0].color1)) - return false; - // Do we have to think about perspective correction or slope mip level? - if (state.enableTextures && data[i].clippos.w != data[0].clippos.w) - return false; - if (state.pixelID.applyFog && data[i].fogdepth != data[0].fogdepth) - return false; - } } // Check for the common case: a single TL-TR-BR-BL. diff --git a/GPU/Software/SoftGpu.cpp b/GPU/Software/SoftGpu.cpp index a6fc160af3..18cdb0b314 100644 --- a/GPU/Software/SoftGpu.cpp +++ b/GPU/Software/SoftGpu.cpp @@ -838,7 +838,7 @@ void SoftGPU::Execute_Prim(u32 op, u32 diff) { return; } - const void *verts = Memory::GetPointer(gstate_c.vertexAddr); + const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *indices = NULL; if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { if (!Memory::IsValidAddress(gstate_c.indexAddr)) { From e7d49cd7d0087fb9a423f3e16491f6f973c34f32 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 13:29:40 -0700 Subject: [PATCH 072/110] softgpu: Allow almost flat rectangles to go fast. Improves transform rectangles used in Chains of Olympus, for example on the title screen. --- GPU/Software/RasterizerRectangle.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index 7408b1558b..79162dc607 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -333,10 +333,18 @@ static bool AreCoordsRectangleCompatible(const RasterizerState &state, const Ver if (!state.throughMode && !(data1.color1 == data0.color1)) return false; // Do we have to think about perspective correction or slope mip level? - if (state.enableTextures && data1.clippos.w != data0.clippos.w) - return false; - if (state.pixelID.applyFog && data1.fogdepth != data0.fogdepth) - return false; + if (state.enableTextures && data1.clippos.w != data0.clippos.w) { + // If the w is off by less than a factor of 1/512, it should be safe to treat as a rectangle. + static constexpr float halftexel = 0.5f / 512.0f; + if (data1.clippos.w - halftexel > data0.clippos.w || data1.clippos.w + halftexel < data0.clippos.w) + return false; + } + if (state.pixelID.applyFog && data1.fogdepth != data0.fogdepth) { + // Similar to w, this only matters if they're farther apart than 1/255. + static constexpr float foghalfstep = 0.5f / 255.0f; + if (data1.fogdepth - foghalfstep > data0.fogdepth || data1.fogdepth + foghalfstep < data0.fogdepth) + return false; + } } return true; } From 2505ae28589c80d27ca3d7d3e04b9b5c4ce2ce7c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 13:36:01 -0700 Subject: [PATCH 073/110] GE Debugger: Fix logging of texture size. --- GPU/GeDisasm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GeDisasm.cpp b/GPU/GeDisasm.cpp index b30218b44a..a645b5bc2b 100644 --- a/GPU/GeDisasm.cpp +++ b/GPU/GeDisasm.cpp @@ -605,7 +605,7 @@ void GeDisassembleOp(u32 pc, u32 op, u32 prev, char *buffer, int bufsize) { { int w = 1 << (data & 0xf); int h = 1 << ((data>>8) & 0xf); - if ((data & ~0x0F0F) && w <= 512 && h <= 512) + if ((data & ~0x0F0F) == 0 && w <= 512 && h <= 512) snprintf(buffer, bufsize, "Texture size %d: %dx%d", cmd - GE_CMD_TEXSIZE0, w, h); else snprintf(buffer, bufsize, "Texture size %d: %dx%d (extra %06x)", cmd - GE_CMD_TEXSIZE0, w, h, data); From 13ca08b2357e8dec7ffa79d04116dd842e623d1c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 14:56:13 -0700 Subject: [PATCH 074/110] softgpu: Avoid over-aggressive rect conversion. The TL and BR have to match between UVs and pos, not enough for UV to be in order. This was causing an artifact on Chains of Olympus' title. --- GPU/Software/RasterizerRectangle.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index 79162dc607..f3ba20840a 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -435,7 +435,9 @@ bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data if (textl.x == texbl.x && textr.x == texbr.x && textl.y == textr.y && texbl.y == texbr.y) { // Okay, the texture is also good, but let's avoid rotation issues. - return textl.y < texbr.y && textl.x < texbr.x; + const auto &postl = data[*tlIndex].screenpos; + const auto &posbr = data[*brIndex].screenpos; + return textl.y < texbr.y && postl.y < posbr.y && textl.x < texbr.x && postl.x < posbr.x; } } } From f5f5c9ea8775d5e73a163098e9df17cec2df6556 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 14:58:27 -0700 Subject: [PATCH 075/110] softgpu: Avoid calling unordered coords tl/br. These are just corners, we don't know if they're top or not at this point. --- GPU/Software/RasterizerRectangle.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index f3ba20840a..f30ae1c128 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -414,14 +414,14 @@ bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data // Check for the common case: a single TL-TR-BR-BL. if (c == 4) { - const auto &tl = data[0].screenpos, &tr = data[1].screenpos; - const auto &bl = data[3].screenpos, &br = data[2].screenpos; - if (tl.x == bl.x && tr.x == br.x && tl.y == tr.y && bl.y == br.y) { + const auto &pos0 = data[0].screenpos, &pos1 = data[1].screenpos; + const auto &pos2 = data[2].screenpos, &pos3 = data[3].screenpos; + if (pos0.x == pos3.x && pos1.x == pos2.x && pos0.y == pos1.y && pos3.y == pos2.y) { // Looking like yes. Set TL/BR based on y order first... - *tlIndex = tl.y > bl.y ? 2 : 0; - *brIndex = tl.y > bl.y ? 0 : 2; + *tlIndex = pos0.y > pos3.y ? 2 : 0; + *brIndex = pos0.y > pos3.y ? 0 : 2; // And if it's horizontally flipped, trade to the actual TL/BR. - if (tl.x > tr.x) { + if (pos0.x > pos1.x) { *tlIndex ^= 1; *brIndex ^= 1; } From 18c9a4d9c9d8eaa5166e160bb02c3f1fc4471643 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 19:31:53 -0700 Subject: [PATCH 076/110] GE Debugger: Fix crash stepping with large tex. Some math was overflowing in allocations, and it would allocate zero bytes. Let's just refuse textures more actively. --- GPU/Software/Rasterizer.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index a387e3b943..4f230e1693 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -1401,7 +1401,11 @@ bool GetCurrentTexture(GPUDebugBuffer &buffer, int level) int w = gstate.getTextureWidth(level); int h = gstate.getTextureHeight(level); - if (!texaddr || !Memory::IsValidRange(texaddr, (textureBitsPerPixel[texfmt] * texbufw * h) / 8)) + u32 sizeInBits = textureBitsPerPixel[texfmt] * (texbufw * (h - 1) + w); + if (!texaddr || !Memory::IsValidRange(texaddr, sizeInBits / 8)) + return false; + // We'll break trying to allocate this much. + if (w >= 0x8000 && h >= 0x8000) return false; buffer.Allocate(w, h, GE_FORMAT_8888, false); From 100cbec620fffec435143ac11e49b340589968cb Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 19:44:44 -0700 Subject: [PATCH 077/110] GE Debugger: Fix crash on bp before list running. --- GPU/Debugger/Breakpoints.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/GPU/Debugger/Breakpoints.cpp b/GPU/Debugger/Breakpoints.cpp index 8d76cbd5e7..225b25799d 100644 --- a/GPU/Debugger/Breakpoints.cpp +++ b/GPU/Debugger/Breakpoints.cpp @@ -29,6 +29,9 @@ namespace GPUBreakpoints { +static void NothingToDo(bool) { +} + struct BreakpointInfo { bool isConditional = false; PostfixExpression expression; @@ -45,7 +48,7 @@ static std::set breakRenderTargets; static size_t breakPCsCount = 0; static size_t breakTexturesCount = 0; static size_t breakRenderTargetsCount = 0; -static std::function notifyBreakpoints; +static std::function notifyBreakpoints = &NothingToDo; // If these are set, the above are also, but they should be temporary. static bool breakCmdsTemp[256]; From 6c6d817ce75377731346232bf7fee08ba398c327 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 20:14:37 -0700 Subject: [PATCH 078/110] Vulkan: Avoid crash if large texture attempted. Doesn't do the clamp/wrap thing, but at least this won't crash. --- Common/GPU/Vulkan/VulkanImage.cpp | 4 ++++ GPU/Vulkan/TextureCacheVulkan.cpp | 3 +-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanImage.cpp b/Common/GPU/Vulkan/VulkanImage.cpp index c013f5d9ee..72eb339c12 100644 --- a/Common/GPU/Vulkan/VulkanImage.cpp +++ b/Common/GPU/Vulkan/VulkanImage.cpp @@ -36,6 +36,10 @@ bool VulkanTexture::CreateDirect(VkCommandBuffer cmd, int w, int h, int depth, i ERROR_LOG(G3D, "Can't create a zero-size VulkanTexture"); return false; } + if (w > 4096 || h > 4096) { + ERROR_LOG(G3D, "Can't create a texture this large"); + return false; + } Wipe(); diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index d11e92ba05..2800627593 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -389,13 +389,12 @@ void TextureCacheVulkan::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutB } void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { - if (!entry) { + if (!entry || !entry->vkTex) { imageView_ = VK_NULL_HANDLE; curSampler_ = VK_NULL_HANDLE; return; } - _dbg_assert_(entry->vkTex); entry->vkTex->Touch(); int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; From 3242bb8d6688e7eb7071976653afebc1df97e22c Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 20:15:43 -0700 Subject: [PATCH 079/110] TexCache: Allow valid bufw sizes. These don't cause crashes anymore. --- GPU/Common/TextureCacheCommon.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index eaef9ea6da..7e42991ee6 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -2271,12 +2271,6 @@ bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEnt // For the estimate, we assume cluts always point to 8888 for simplicity. cacheSizeEstimate_ += EstimateTexMemoryUsage(entry); - if ((entry->bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && entry->addr >= PSP_GetKernelMemoryEnd()) { - ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff); - // Proceeding here can cause a crash. - return false; - } - plan.badMipSizes = false; // maxLevel here is the max level to upload. Not the count. plan.levelsToLoad = entry->maxLevel + 1; From 1056301c95d3bbcaa94eb5c0f5cd383838a1b645 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 20:16:05 -0700 Subject: [PATCH 080/110] D3D11: Prevent crash on larger textures. --- GPU/D3D11/TextureCacheD3D11.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 2563825ea1..750c7427c5 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -300,6 +300,10 @@ void TextureCacheD3D11::BuildTexture(TexCacheEntry *const entry) { int tw; int th; plan.GetMipSize(0, &tw, &th); + if (tw > 16384) + tw = 16384; + if (th > 16384) + th = 16384; if (plan.depth == 1) { // We don't yet have mip generation, so clamp the number of levels to the ones we can load directly. From 123d6dbb1160e46698898f2c39de1cac4d1414d3 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 20:17:54 -0700 Subject: [PATCH 081/110] GE Debugger: Correct confusing block transfer size. --- Windows/GEDebugger/TabState.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Windows/GEDebugger/TabState.cpp b/Windows/GEDebugger/TabState.cpp index 200eb9ae75..63a7199ed6 100644 --- a/Windows/GEDebugger/TabState.cpp +++ b/Windows/GEDebugger/TabState.cpp @@ -63,6 +63,7 @@ enum CmdFormatType { CMD_FMT_XY, CMD_FMT_XYXY, CMD_FMT_XYZ, + CMD_FMT_XYPLUS1, CMD_FMT_TEXSIZE, CMD_FMT_F16_XY, CMD_FMT_VERTEXTYPE, @@ -233,7 +234,7 @@ static const TabStateRow stateSettingsRows[] = { { L"Transfer src pos", GE_CMD_TRANSFERSRCPOS, CMD_FMT_XY }, { L"Transfer dst", GE_CMD_TRANSFERDST, CMD_FMT_PTRWIDTH, 0, GE_CMD_TRANSFERDSTW }, { L"Transfer dst pos", GE_CMD_TRANSFERDSTPOS, CMD_FMT_XY }, - { L"Transfer size", GE_CMD_TRANSFERSIZE, CMD_FMT_XY }, + { L"Transfer size", GE_CMD_TRANSFERSIZE, CMD_FMT_XYPLUS1 }, { L"Vertex type", GE_CMD_VERTEXTYPE, CMD_FMT_VERTEXTYPE }, { L"Offset addr", GE_CMD_OFFSETADDR, CMD_FMT_OFFSETADDR }, { L"Vertex addr", GE_CMD_VADDR, CMD_FMT_VADDR }, @@ -376,6 +377,14 @@ void FormatStateRow(wchar_t *dest, const TabStateRow &info, u32 value, bool enab } break; + case CMD_FMT_XYPLUS1: + { + int x = value & 0x3FF; + int y = value >> 10; + swprintf(dest, 255, L"%d,%d", x + 1, y + 1); + } + break; + case CMD_FMT_XYXY: { int x1 = value & 0x3FF; From 90e009edb9c1cdfb53d8b2e1382244ae19857862 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 19:33:02 -0700 Subject: [PATCH 082/110] softgpu: Clamp/wrap textures at 512 pixels. A texture larger than 512 is "valid", but simply wraps/clamps at 512. Importantly, the texture coords are still calculated at the specified size, which can be up to 32768. --- GPU/Software/RasterizerRectangle.cpp | 4 ++++ GPU/Software/Sampler.cpp | 4 +++- GPU/Software/Sampler.h | 1 + GPU/Software/SamplerX86.cpp | 12 ++++++++++-- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index f25be97f64..877b298ef9 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -265,6 +265,10 @@ bool g_needsClearAfterDialog = false; static inline bool NoClampOrWrap(const RasterizerState &state, const Vec2f &tc) { if (tc.x < 0 || tc.y < 0) return false; + if (state.samplerID.cached.sizes[0].w > 512 || state.samplerID.cached.sizes[0].h > 512) + return false; + if (!state.throughMode) + return tc.x <= 1.0f && tc.y <= 1.0f; return tc.x <= state.samplerID.cached.sizes[0].w && tc.y <= state.samplerID.cached.sizes[0].h; } diff --git a/GPU/Software/Sampler.cpp b/GPU/Software/Sampler.cpp index 8aad116b14..8c55e15760 100644 --- a/GPU/Software/Sampler.cpp +++ b/GPU/Software/Sampler.cpp @@ -383,13 +383,15 @@ inline static Nearest4 SOFTRAST_CALL SampleNearest(const int u[N], const int v[N static inline int ClampUV(int v, int height) { if (v >= height - 1) return height - 1; + if (v >= 511) + return 511; else if (v < 0) return 0; return v; } static inline int WrapUV(int v, int height) { - return v & (height - 1); + return v & (height - 1) & 511; } template diff --git a/GPU/Software/Sampler.h b/GPU/Software/Sampler.h index e663004cbf..2379c5edfb 100644 --- a/GPU/Software/Sampler.h +++ b/GPU/Software/Sampler.h @@ -114,6 +114,7 @@ private: const u8 *constVNext_ = nullptr; const u8 *constOnes32_ = nullptr; const u8 *constOnes16_ = nullptr; + const u8 *constMaxTexel32_ = nullptr; const u8 *const10All16_ = nullptr; const u8 *const10Low_ = nullptr; const u8 *const10All8_ = nullptr; diff --git a/GPU/Software/SamplerX86.cpp b/GPU/Software/SamplerX86.cpp index 415eed2723..932c6d1a62 100644 --- a/GPU/Software/SamplerX86.cpp +++ b/GPU/Software/SamplerX86.cpp @@ -903,6 +903,8 @@ void SamplerJitCache::WriteConstantPool(const SamplerID &id) { WriteSimpleConst4x32(constOnes32_, 1); WriteSimpleConst8x16(constOnes16_, 1); + // This is the mask for clamp or wrap, the max texel in the S or T direction. + WriteSimpleConst4x32(constMaxTexel32_, 511); if (constUNext_ == nullptr) { constUNext_ = AlignCode16(); @@ -927,8 +929,8 @@ void SamplerJitCache::WriteConstantPool(const SamplerID &id) { Write32(*(uint32_t *)&w256f); Write32(*(uint32_t *)&h256f); - WriteDynamicConst4x32(constWidthMinus1i_, (1 << id.width0Shift) - 1); - WriteDynamicConst4x32(constHeightMinus1i_, (1 << id.height0Shift) - 1); + WriteDynamicConst4x32(constWidthMinus1i_, id.width0Shift > 9 ? 511 : (1 << id.width0Shift) - 1); + WriteDynamicConst4x32(constHeightMinus1i_, id.height0Shift > 9 ? 511 : (1 << id.height0Shift) - 1); } else { constWidthHeight256f_ = nullptr; constWidthMinus1i_ = nullptr; @@ -2651,6 +2653,7 @@ bool SamplerJitCache::Jit_GetTexelCoords(const SamplerID &id) { } SUB(32, R(tempReg), Imm8(1)); + AND(32, R(tempReg), Imm32(0x000001FF)); if (clamp) { CMP(32, R(dest), R(tempReg)); CMOVcc(32, dest, R(tempReg), CC_G); @@ -2710,6 +2713,10 @@ bool SamplerJitCache::Jit_GetTexelCoords(const SamplerID &id) { AND(32, R(uReg), R(uReg)); auto applyClampWrap = [this](X64Reg dest, bool clamp, uint8_t shift) { + // Clamp and wrap both max out at 512. + if (shift > 9) + shift = 9; + if (clamp) { X64Reg tempReg = regCache_.Alloc(RegCache::GEN_TEMP0); MOV(32, R(tempReg), Imm32((1 << shift) - 1)); @@ -2802,6 +2809,7 @@ bool SamplerJitCache::Jit_GetTexelCoordsQuad(const SamplerID &id) { // For wrap/clamp purposes, we want width or height minus one. Do that now. PSUBD(sizesReg, M(constOnes32_)); + PAND(sizesReg, M(constMaxTexel32_)); } else { // Easy mode. UNPCKLPS(sReg, R(tReg)); From 15d5fa48f79af980a7c589d359f163fc699d2acd Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Sep 2022 21:22:13 -0700 Subject: [PATCH 083/110] softgpu: Check depth test early on simple stencil. If we don't need to write stencil on sfail/zfail, we can do the depthtest early, which allows us to more often skip texture sampling. This gives a good improvement in Chains of Olympus. --- GPU/Software/DrawPixel.cpp | 10 ++-- GPU/Software/DrawPixel.h | 2 + GPU/Software/DrawPixelX86.cpp | 10 ++-- GPU/Software/FuncId.cpp | 7 +++ GPU/Software/FuncId.h | 3 +- GPU/Software/Rasterizer.cpp | 95 +++++++++++++++++++++++++++++------ 6 files changed, 104 insertions(+), 23 deletions(-) diff --git a/GPU/Software/DrawPixel.cpp b/GPU/Software/DrawPixel.cpp index 3585c9a3ff..ab244aacf8 100644 --- a/GPU/Software/DrawPixel.cpp +++ b/GPU/Software/DrawPixel.cpp @@ -325,6 +325,10 @@ static inline bool DepthTestPassed(GEComparison func, int x, int y, int stride, } } +bool CheckDepthTestPassed(GEComparison func, int x, int y, int stride, u16 z) { + return DepthTestPassed(func, x, y, stride, z); +} + static inline u32 ApplyLogicOp(GELogicOp op, u32 old_color, u32 new_color) { // All of the operations here intentionally preserve alpha/stencil. switch (op) { @@ -400,7 +404,7 @@ template void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg color_in, const PixelFuncID &pixelID) { Vec4 prim_color = Vec4(color_in).Clamp(0, 255); // Depth range test - applied in clear mode, if not through mode. - if (pixelID.applyDepthRange) + if (pixelID.applyDepthRange && !pixelID.earlyZChecks) if (z < pixelID.cached.minz || z > pixelID.cached.maxz) return; @@ -436,14 +440,14 @@ void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg colo } // Also apply depth at the same time. If disabled, same as passing. - if (pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { + if (!pixelID.earlyZChecks && pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { stencil = ApplyStencilOp(fbFormat, stencilReplace, pixelID.ZFail(), stencil); SetPixelStencil(fbFormat, pixelID.cached.framebufStride, targetWriteMask, x, y, stencil); return; } stencil = ApplyStencilOp(fbFormat, stencilReplace, pixelID.ZPass(), stencil); - } else { + } else if (!pixelID.earlyZChecks) { if (pixelID.DepthTestFunc() != GE_COMP_ALWAYS && !DepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { return; } diff --git a/GPU/Software/DrawPixel.h b/GPU/Software/DrawPixel.h index b1063d59a1..982ee27765 100644 --- a/GPU/Software/DrawPixel.h +++ b/GPU/Software/DrawPixel.h @@ -41,6 +41,8 @@ SingleFunc GetSingleFunc(const PixelFuncID &id); void Init(); void Shutdown(); +bool CheckDepthTestPassed(GEComparison func, int x, int y, int stride, u16 z); + bool DescribeCodePtr(const u8 *ptr, std::string &name); struct PixelBlendState { diff --git a/GPU/Software/DrawPixelX86.cpp b/GPU/Software/DrawPixelX86.cpp index 536f1efb02..8f006bece4 100644 --- a/GPU/Software/DrawPixelX86.cpp +++ b/GPU/Software/DrawPixelX86.cpp @@ -149,7 +149,7 @@ RegCache::Reg PixelJitCache::GetColorOff(const PixelFuncID &id) { if (!regCache_.Has(RegCache::GEN_COLOR_OFF)) { Describe("GetColorOff"); if (id.useStandardStride && !id.dithering) { - bool loadDepthOff = id.depthWrite || id.DepthTestFunc() != GE_COMP_ALWAYS; + bool loadDepthOff = id.depthWrite || (id.DepthTestFunc() != GE_COMP_ALWAYS && !id.earlyZChecks); X64Reg depthTemp = INVALID_REG; X64Reg argYReg = regCache_.Find(RegCache::GEN_ARG_Y); X64Reg argXReg = regCache_.Find(RegCache::GEN_ARG_X); @@ -345,7 +345,7 @@ void PixelJitCache::WriteConstantPool(const PixelFuncID &id) { } bool PixelJitCache::Jit_ApplyDepthRange(const PixelFuncID &id) { - if (id.applyDepthRange) { + if (id.applyDepthRange && !id.earlyZChecks) { Describe("ApplyDepthR"); X64Reg argZReg = regCache_.Find(RegCache::GEN_ARG_Z); X64Reg idReg = GetPixelID(); @@ -365,7 +365,7 @@ bool PixelJitCache::Jit_ApplyDepthRange(const PixelFuncID &id) { // Since this is early on, try to free up the z reg if we don't need it anymore. if (id.clearMode && !id.DepthClear()) regCache_.ForceRelease(RegCache::GEN_ARG_Z); - else if (!id.clearMode && !id.depthWrite && id.DepthTestFunc() == GE_COMP_ALWAYS) + else if (!id.clearMode && !id.depthWrite && (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks)) regCache_.ForceRelease(RegCache::GEN_ARG_Z); return true; @@ -721,7 +721,7 @@ bool PixelJitCache::Jit_StencilTest(const PixelFuncID &id, RegCache::Reg stencil } bool PixelJitCache::Jit_DepthTestForStencil(const PixelFuncID &id, RegCache::Reg stencilReg) { - if (id.DepthTestFunc() == GE_COMP_ALWAYS) + if (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks) return true; X64Reg depthOffReg = GetDepthOff(id); @@ -964,7 +964,7 @@ bool PixelJitCache::Jit_WriteStencilOnly(const PixelFuncID &id, RegCache::Reg st } bool PixelJitCache::Jit_DepthTest(const PixelFuncID &id) { - if (id.DepthTestFunc() == GE_COMP_ALWAYS) + if (id.DepthTestFunc() == GE_COMP_ALWAYS || id.earlyZChecks) return true; if (id.DepthTestFunc() == GE_COMP_NEVER) { diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index 084c897829..0471114caa 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -163,6 +163,13 @@ void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->applyLogicOp = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_COPY; id->applyFog = gstate.isFogEnabled() && !throughMode; + + id->earlyZChecks = id->DepthTestFunc() != GE_COMP_ALWAYS; + if (id->stencilTest && id->earlyZChecks) { + // Can't do them early if stencil might need to write. + if (id->SFail() != GE_STENCILOP_KEEP || id->ZFail() != GE_STENCILOP_KEEP) + id->earlyZChecks = false; + } } // Cache some values for later convenience. diff --git a/GPU/Software/FuncId.h b/GPU/Software/FuncId.h index 72207ebd5a..46307fc55c 100644 --- a/GPU/Software/FuncId.h +++ b/GPU/Software/FuncId.h @@ -107,7 +107,8 @@ struct PixelFuncID { uint8_t sFail : 3; uint8_t zFail : 3; uint8_t zPass : 3; - // 60 bits, 4 free. + bool earlyZChecks : 1; + // 61 bits, 3 free. }; }; diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index a387e3b943..c534d37792 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -710,6 +710,11 @@ void DrawTriangleSlice( const bool flatColor1 = flatColorAll || (v0.color1 == v1.color1 && v0.color1 == v2.color1); const bool noFog = clearMode || !pixelID.applyFog || (v0.fogdepth >= 1.0f && v1.fogdepth >= 1.0f && v2.fogdepth >= 1.0f); + if (pixelID.applyDepthRange && flatZ) { + if (v0.screenpos.z < pixelID.cached.minz || v0.screenpos.z > pixelID.cached.maxz) + return; + } + #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) uint32_t bpp = pixelID.FBFormat() == GE_FORMAT_8888 ? 4 : 2; std::string tag = StringFromFormat("DisplayListT_%08x", state.listPC); @@ -754,6 +759,32 @@ void DrawTriangleSlice( if (AnyMask(mask)) { Vec4 wsum_recip = EdgeRecip(w0, w1, w2); + Vec4 z; + if (flatZ) { + z = Vec4::AssignToAll(v2.screenpos.z); + } else { + // Z is interpolated pretty much directly. + Vec4 zfloats = w0.Cast() * v0.screenpos.z + w1.Cast() * v1.screenpos.z + w2.Cast() * v2.screenpos.z; + z = (zfloats * wsum_recip).Cast(); + } + + if (pixelID.earlyZChecks) { + for (int i = 0; i < 4; ++i) { + if (pixelID.applyDepthRange) { + if (z[i] < pixelID.cached.minz || z[i] > pixelID.cached.maxz) + mask[i] = -1; + } + if (mask[i] < 0) + continue; + + int x = p.x + (i & 1); + int y = p.y + (i / 2); + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z[i])) { + mask[i] = -1; + } + } + } + // Color interpolation is not perspective corrected on the PSP. Vec4 prim_color[4]; if (!flatColor0) { @@ -816,15 +847,6 @@ void DrawTriangleSlice( } } - Vec4 z; - if (flatZ) { - z = Vec4::AssignToAll(v2.screenpos.z); - } else { - // Z is interpolated pretty much directly. - Vec4 zfloats = w0.Cast() * v0.screenpos.z + w1.Cast() * v1.screenpos.z + w2.Cast() * v2.screenpos.z; - z = (zfloats * wsum_recip).Cast(); - } - PROFILE_THIS_SCOPE("draw_tri_px"); DrawingCoords subp = p; for (int i = 0; i < 4; ++i) { @@ -947,6 +969,12 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & Vec4 z = Vec4::AssignToAll(v1.screenpos.z); Vec3 sec_color = v1.color1; + if (state.pixelID.applyDepthRange) { + // We can bail early since the Z is flat. + if (v1.screenpos.z < state.pixelID.cached.minz || v1.screenpos.z > state.pixelID.cached.maxz) + return; + } + #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) uint32_t bpp = state.pixelID.FBFormat() == GE_FORMAT_8888 ? 4 : 2; std::string tag = StringFromFormat("DisplayListR_%08x", state.listPC); @@ -972,6 +1000,19 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & prim_color[i] = v1.color0; } + if (state.pixelID.earlyZChecks) { + for (int i = 0; i < 4; ++i) { + if (mask[i] < 0) + continue; + + int x = p.x + (i & 1); + int y = p.y + (i / 2); + if (!CheckDepthTestPassed(state.pixelID.DepthTestFunc(), x, y, state.pixelID.cached.depthbufStride, z[i])) { + mask[i] = -1; + } + } + } + if (state.enableTextures) { Vec4 s, t; s = Vec4::AssignToAll(st.s()) + sto4; @@ -1038,6 +1079,20 @@ void DrawPoint(const VertexData &v0, const BinCoords &range, const RasterizerSta auto &pixelID = state.pixelID; auto &samplerID = state.samplerID; + DrawingCoords p = TransformUnit::ScreenToDrawing(pos); + u16 z = pos.z; + + if (pixelID.earlyZChecks) { + if (pixelID.applyDepthRange) { + if (z < pixelID.cached.minz || z > pixelID.cached.maxz) + return; + } + + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), p.x, p.y, pixelID.cached.depthbufStride, z)) { + return; + } + } + if (state.enableTextures) { float s = v0.texturecoords.s(); float t = v0.texturecoords.t(); @@ -1060,9 +1115,6 @@ void DrawPoint(const VertexData &v0, const BinCoords &range, const RasterizerSta if (!pixelID.clearMode) prim_color += Vec4(sec_color, 0); - DrawingCoords p = TransformUnit::ScreenToDrawing(pos); - u16 z = pos.z; - u8 fog = 255; if (pixelID.applyFog) { fog = ClampFogDepth(v0.fogdepth); @@ -1302,7 +1354,23 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range double z = a.z; const int steps1 = steps == 0 ? 1 : steps; for (int i = 0; i < steps; i++) { - if (x >= range.x1 && y >= range.y1 && x <= range.x2 && y <= range.y2) { + DrawingCoords p = TransformUnit::ScreenToDrawing(x, y); + + bool maskOK = x >= range.x1 && y >= range.y1 && x <= range.x2 && y <= range.y2; + if (maskOK) { + if (pixelID.earlyZChecks) { + if (pixelID.applyDepthRange) { + if (z < pixelID.cached.minz || z > pixelID.cached.maxz) + maskOK = false; + } + + if (!CheckDepthTestPassed(pixelID.DepthTestFunc(), x, y, pixelID.cached.depthbufStride, z)) { + maskOK = false; + } + } + } + + if (maskOK) { // Interpolate between the two points. Vec4 prim_color; Vec3 sec_color; @@ -1368,7 +1436,6 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range prim_color += Vec4(sec_color, 0); PROFILE_THIS_SCOPE("draw_px"); - DrawingCoords p = TransformUnit::ScreenToDrawing(x, y); state.drawPixel(p.x, p.y, z, fog, ToVec4IntArg(prim_color), pixelID); #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) From 4889d5285d422cfb6ce12b7f09b9f271649ed80e Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 2 Feb 2022 22:10:32 -0800 Subject: [PATCH 084/110] vertexjit: Use consistent skinInDecode. Just a little cleanup. --- GPU/Common/VertexDecoderArm.cpp | 2 +- GPU/Common/VertexDecoderArm64.cpp | 2 +- GPU/Common/VertexDecoderCommon.cpp | 2 +- GPU/Common/VertexDecoderCommon.h | 1 + GPU/Common/VertexDecoderX86.cpp | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/GPU/Common/VertexDecoderArm.cpp b/GPU/Common/VertexDecoderArm.cpp index c2f6ae46fd..e3d5b11f6b 100644 --- a/GPU/Common/VertexDecoderArm.cpp +++ b/GPU/Common/VertexDecoderArm.cpp @@ -204,7 +204,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { // Copying from R3 to R4 MOVP2R(R3, gstate.boneMatrix); MOVP2R(R4, bones); diff --git a/GPU/Common/VertexDecoderArm64.cpp b/GPU/Common/VertexDecoderArm64.cpp index 32cc5bc291..5ff1d605f3 100644 --- a/GPU/Common/VertexDecoderArm64.cpp +++ b/GPU/Common/VertexDecoderArm64.cpp @@ -190,7 +190,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { // Copying from R3 to R4 MOVP2R(X3, gstate.boneMatrix); MOVP2R(X4, bones); diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index 6ac9806c01..a9b4a1039a 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -1083,7 +1083,7 @@ void VertexDecoder::SetVertexType(u32 fmt, const VertexDecoderOptions &options, DEBUG_LOG(G3D, "VTYPE: THRU=%i TC=%i COL=%i POS=%i NRM=%i WT=%i NW=%i IDX=%i MC=%i", (int)throughmode, tc, col, pos, nrm, weighttype, nweights, idx, morphcount); } - bool skinInDecode = weighttype != 0 && g_Config.bSoftwareSkinning; + skinInDecode = weighttype != 0 && g_Config.bSoftwareSkinning; if (weighttype) { // && nweights? weightoff = size; diff --git a/GPU/Common/VertexDecoderCommon.h b/GPU/Common/VertexDecoderCommon.h index 5ec55ebe4c..983f76f9b2 100644 --- a/GPU/Common/VertexDecoderCommon.h +++ b/GPU/Common/VertexDecoderCommon.h @@ -458,6 +458,7 @@ public: DecVtxFormat decFmt; bool throughmode; + bool skinInDecode; u8 size; u8 onesize_; diff --git a/GPU/Common/VertexDecoderX86.cpp b/GPU/Common/VertexDecoderX86.cpp index 611bf56c21..d684078989 100644 --- a/GPU/Common/VertexDecoderX86.cpp +++ b/GPU/Common/VertexDecoderX86.cpp @@ -219,7 +219,7 @@ JittedVertexDecoder VertexDecoderJitCache::Compile(const VertexDecoder &dec, int // Add code to convert matrices to 4x4. // Later we might want to do this when the matrices are loaded instead. - if (dec.weighttype && g_Config.bSoftwareSkinning) { + if (dec.skinInDecode) { MOV(PTRBITS, R(tempReg1), ImmPtr(&threeMasks)); MOVAPS(XMM4, MatR(tempReg1)); MOV(PTRBITS, R(tempReg1), ImmPtr(&aOne)); From 33a93e238ae42ea8fcfb040518676b01da9388f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 10:26:01 +0200 Subject: [PATCH 085/110] CLUT download: Replace the broken block transfer check with a new compat flag. This compat flag should be temporary until we've implemented a readback-free path for CLUTs from framebuffers, both when texturing from static textures and other framebuffers. --- Core/Compatibility.cpp | 1 + Core/Compatibility.h | 1 + GPU/Common/TextureCacheCommon.cpp | 9 ++++++--- assets/compat.ini | 3 +++ 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Core/Compatibility.cpp b/Core/Compatibility.cpp index 11233bf1bb..c9bb3428a8 100644 --- a/Core/Compatibility.cpp +++ b/Core/Compatibility.cpp @@ -98,6 +98,7 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) { CheckSetting(iniFile, gameID, "DeswizzleDepth", &flags_.DeswizzleDepth); CheckSetting(iniFile, gameID, "SplitFramebufferMargin", &flags_.SplitFramebufferMargin); CheckSetting(iniFile, gameID, "ForceLowerResolutionForEffectsOn", &flags_.ForceLowerResolutionForEffectsOn); + CheckSetting(iniFile, gameID, "AllowDownloadCLUT", &flags_.AllowDownloadCLUT); } void Compatibility::CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag) { diff --git a/Core/Compatibility.h b/Core/Compatibility.h index 9b1dfa5fd7..060ee3c268 100644 --- a/Core/Compatibility.h +++ b/Core/Compatibility.h @@ -88,6 +88,7 @@ struct CompatFlags { bool DeswizzleDepth; bool SplitFramebufferMargin; bool ForceLowerResolutionForEffectsOn; + bool AllowDownloadCLUT; }; class IniFile; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index eaef9ea6da..b5abfbde59 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1177,7 +1177,7 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { // And is it inside the rendered area? Sometimes games pack data outside. bool matchRegion = ((offset / bpp) % framebuffer->fb_stride) < framebuffer->width; if (matchRange && matchRegion && offset < clutRenderOffset_) { - WARN_LOG_N_TIMES(clutfb, 5, G3D, "LoadCLUT(%d bytes) from framebuffer %08x (%s), byte offset %d", loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), offset); + WARN_LOG_N_TIMES(clutfb, 5, G3D, "Detected LoadCLUT(%d bytes) from framebuffer %08x (%s), byte offset %d", loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), offset); framebuffer->last_frame_clut = gpuStats.numFlips; framebuffer->usageFlags |= FB_USAGE_CLUT; clutRenderAddress_ = framebuffer->fb_address; @@ -1191,15 +1191,18 @@ void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes) { NotifyMemInfo(MemBlockFlags::ALLOC, clutAddr, loadBytes, "CLUT"); } - // It's possible for a game to (successfully) access outside valid memory. + // It's possible for a game to load CLUT outside valid memory without crashing, should result in zeroes. u32 bytes = Memory::ValidSize(clutAddr, loadBytes); - if (clutRenderAddress_ != 0xFFFFFFFF && !g_Config.bBlockTransferGPU) { + if (clutRenderAddress_ != 0xFFFFFFFF && PSP_CoreParameter().compat.flags().AllowDownloadCLUT) { framebufferManager_->DownloadFramebufferForClut(clutRenderAddress_, clutRenderOffset_ + bytes); Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes); if (bytes < loadBytes) { memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes); } } else { + // Here we could check for clutRenderAddres_ != 0xFFFFFFFF and zero the CLUT or something, + // but choosing not to for now. Though the results of loading the CLUT from RAM here is + // almost certainly going to be bogus. #ifdef _M_SSE if (bytes == loadBytes) { const __m128i *source = (const __m128i *)Memory::GetPointerUnchecked(clutAddr); diff --git a/assets/compat.ini b/assets/compat.ini index 976edb0959..63a4f168f7 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -1294,3 +1294,6 @@ ULES01301 = true ULES00262 = true ULUS10064 = true ULKS46087 = true + +[AllowDownloadCLUT] +# Temporary compatibility option, while developing a GPU CLUT-from-framebuffer path. From 5e6b06483511fd247bba57ccf437d775b3262ead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 10:30:43 +0200 Subject: [PATCH 086/110] DownloadFramebufferForCLUT: Apply the fix mentioned in #8590 --- GPU/Common/FramebufferManagerCommon.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GPU/Common/FramebufferManagerCommon.cpp b/GPU/Common/FramebufferManagerCommon.cpp index 3cbe6543f0..e4ecfb4192 100644 --- a/GPU/Common/FramebufferManagerCommon.cpp +++ b/GPU/Common/FramebufferManagerCommon.cpp @@ -2552,6 +2552,11 @@ void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 lo int w = std::min(pixels % vfb->fb_stride, (int)vfb->width); int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height); + if (w == 0 || h > 1) { + // Exactly aligned, or more than one row. + w = std::min(vfb->fb_stride, vfb->width); + } + // We might still have a pending draw to the fb in question, flush if so. FlushBeforeCopy(); From 9bd8b11bf8a5019b74e03cbb75b9366ca1af7e22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 13:27:17 +0200 Subject: [PATCH 087/110] Implement shader depal for D3D11. --- Common/GPU/ShaderWriter.cpp | 35 +++++++++++++++ Common/GPU/ShaderWriter.h | 2 + GPU/Common/FragmentShaderGenerator.cpp | 62 ++++++++++++++------------ GPU/Common/TextureCacheCommon.cpp | 1 - GPU/D3D11/D3D11Util.cpp | 5 ++- GPU/D3D11/TextureCacheD3D11.cpp | 5 ++- GPU/GLES/ShaderManagerGLES.cpp | 14 +++--- 7 files changed, 84 insertions(+), 40 deletions(-) diff --git a/Common/GPU/ShaderWriter.cpp b/Common/GPU/ShaderWriter.cpp index 0332e4d346..62d5760408 100644 --- a/Common/GPU/ShaderWriter.cpp +++ b/Common/GPU/ShaderWriter.cpp @@ -24,6 +24,7 @@ const char * const hlsl_preamble_fs = "#define vec4 float4\n" "#define uvec3 uint3\n" "#define uvec4 uint4\n" +"#define ivec2 int2\n" "#define ivec3 int3\n" "#define ivec4 int4\n" "#define mat4 float4x4\n" @@ -424,6 +425,40 @@ ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv return *this; } +ShaderWriter &ShaderWriter::SampleTexture2DOffset(const char *sampName, const char *uv, int offX, int offY) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F("%s.Sample(%sSamp, %s, int2(%d, %d))", sampName, sampName, uv, offX, offY); + break; + case HLSL_D3D9: + // Not supported, we do a normal sample here to not crash or something + F("tex2D(%s, %s)", sampName, uv); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("%sOffset(%s, %s, ivec2(%d, %d))", lang_.texture, sampName, uv, offX, offY); + break; + } + return *this; +} + +ShaderWriter &ShaderWriter::LoadTexture2D(const char *sampName, const char *uv, int level) { + switch (lang_.shaderLanguage) { + case HLSL_D3D11: + F("%s.Load(ivec3(%s, %d))", sampName, uv, level); + break; + case HLSL_D3D9: + // Not supported, we return a bad value + C("float4(1.0, 0.0, 1.0, 1.0)"); + break; + default: + // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. + F("texelFetch(%s, %s, %d)", lang_.texture, sampName, uv, level); + break; + } + return *this; +} + ShaderWriter &ShaderWriter::GetTextureSize(const char *szVariable, const char *texName) { switch (lang_.shaderLanguage) { case HLSL_D3D11: diff --git a/Common/GPU/ShaderWriter.h b/Common/GPU/ShaderWriter.h index 7464ebc652..f6a04c828b 100644 --- a/Common/GPU/ShaderWriter.h +++ b/Common/GPU/ShaderWriter.h @@ -78,6 +78,8 @@ public: void ConstFloat(const char *name, float value); ShaderWriter &SampleTexture2D(const char *texName, const char *uv); + ShaderWriter &SampleTexture2DOffset(const char *texName, const char *uv, int offX, int offY); + ShaderWriter &LoadTexture2D(const char *texName, const char *integer_uv, int level); ShaderWriter &GetTextureSize(const char *szVariable, const char *texName); // Simple shaders with no special tricks. diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index db1d886b1f..feec43ff75 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -221,7 +221,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "float u_mipBias : register(c%i);\n", CONST_PS_MIPBIAS); } } else { - WRITE(p, "SamplerState samp : register(s0);\n"); + WRITE(p, "SamplerState texSamp : register(s0);\n"); if (texture3D) { WRITE(p, "Texture3D tex : register(t0);\n"); } else { @@ -231,6 +231,12 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu // No sampler required, we Load WRITE(p, "Texture2D fbotex : register(t1);\n"); } + + if (shaderDepal) { + WRITE(p, "SamplerState palSamp : register(s3);\n"); + WRITE(p, "Texture2D pal : register(t3);\n"); + } + WRITE(p, "cbuffer base : register(b0) {\n%s};\n", ub_baseStr); if (shaderDepal) { @@ -561,15 +567,15 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu if (compat.shaderLanguage == HLSL_D3D11) { if (texture3D) { if (doTextureProjection) { - WRITE(p, " vec4 t = tex.Sample(samp, vec3(v_texcoord.xy / v_texcoord.z, u_mipBias))%s;\n", bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(v_texcoord.xy / v_texcoord.z, u_mipBias))%s;\n", bgraTexture ? ".bgra" : ""); } else { - WRITE(p, " vec4 t = tex.Sample(samp, vec3(%s.xy, u_mipBias))%s;\n", texcoord, bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(%s.xy, u_mipBias))%s;\n", texcoord, bgraTexture ? ".bgra" : ""); } } else { if (doTextureProjection) { - WRITE(p, " vec4 t = tex.Sample(samp, v_texcoord.xy / v_texcoord.z)%s;\n", bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, v_texcoord.xy / v_texcoord.z)%s;\n", bgraTexture ? ".bgra" : ""); } else { - WRITE(p, " vec4 t = tex.Sample(samp, %s.xy)%s;\n", texcoord, bgraTexture ? ".bgra" : ""); + WRITE(p, " vec4 t = tex.Sample(texSamp, %s.xy)%s;\n", texcoord, bgraTexture ? ".bgra" : ""); } } } else if (compat.shaderLanguage == HLSL_D3D9) { @@ -608,28 +614,28 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. // However it is good for precision on older hardware like PowerVR. - WRITE(p, " vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord); + p.F(" vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord); } else { - WRITE(p, " vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); + p.F(" vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord); } // Restrictions on this are checked before setting the smoothed flag. // Only RGB565 and RGBA5551 are supported, and only the specific shifts hitting the // channels directly. // Also, since we know the CLUT is smooth, we do not need to do the bilinear filter manually, we can just // lookup with the filtered value once. - WRITE(p, " vec4 t = %s(tex, %s.xy);\n", compat.texture, texcoord); - WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); - WRITE(p, " uint depalFmt = (u_depal_mask_shift_off_fmt >> 24) & 0x3U;\n"); - WRITE(p, " float index0 = t.r;\n"); - WRITE(p, " float factor = 31.0 / 256.0;\n"); - WRITE(p, " if (depalFmt == 0u) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh. - WRITE(p, " if (depalShift == 5u) { index0 = t.g; factor = 63.0 / 256.0; }\n"); - WRITE(p, " else if (depalShift == 11u) { index0 = t.b; }\n"); - WRITE(p, " } else {\n"); - WRITE(p, " if (depalShift == 5u) { index0 = t.g; }\n"); - WRITE(p, " else if (depalShift == 10u) { index0 = t.b; }\n"); - WRITE(p, " }\n"); - WRITE(p, " t = %s(pal, vec2(index0 * factor, 0.0));\n", compat.texture); + p.F(" vec4 t = ").SampleTexture2D("tex", "uv").C(";\n"); + p.C(" uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); + p.C(" uint depalFmt = (u_depal_mask_shift_off_fmt >> 24) & 0x3U;\n"); + p.C(" float index0 = t.r;\n"); + p.C(" float factor = 31.0 / 256.0;\n"); + p.C(" if (depalFmt == 0u) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh. + p.C(" if (depalShift == 5u) { index0 = t.g; factor = 63.0 / 256.0; }\n"); + p.C(" else if (depalShift == 11u) { index0 = t.b; }\n"); + p.C(" } else {\n"); + p.C(" if (depalShift == 5u) { index0 = t.g; }\n"); + p.C(" else if (depalShift == 10u) { index0 = t.b; }\n"); + p.C(" }\n"); + p.F(" t = ").SampleTexture2D("pal", "vec2(index0 * factor, 0.0)").C(";\n"); } else { if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. @@ -648,10 +654,10 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " } else {\n"); WRITE(p, " uv_round = uv;\n"); WRITE(p, " }\n"); - WRITE(p, " highp vec4 t = %s(tex, uv_round);\n", compat.texture); - WRITE(p, " highp vec4 t1 = %sOffset(tex, uv_round, ivec2(1, 0));\n", compat.texture); - WRITE(p, " highp vec4 t2 = %sOffset(tex, uv_round, ivec2(0, 1));\n", compat.texture); - WRITE(p, " highp vec4 t3 = %sOffset(tex, uv_round, ivec2(1, 1));\n", compat.texture); + p.C(" highp vec4 t = ").SampleTexture2D("tex", "uv_round").C(";\n"); + p.C(" highp vec4 t1 = ").SampleTexture2DOffset("tex", "uv_round", 1, 0).C(";\n"); + p.C(" highp vec4 t2 = ").SampleTexture2DOffset("tex", "uv_round", 0, 1).C(";\n"); + p.C(" highp vec4 t3 = ").SampleTexture2DOffset("tex", "uv_round", 1, 1).C(";\n"); WRITE(p, " uint depalMask = (u_depal_mask_shift_off_fmt & 0xFFU);\n"); WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 8) & 0xFFU;\n"); WRITE(p, " uint depalOffset = ((u_depal_mask_shift_off_fmt >> 16) & 0xFFU) << 4;\n"); @@ -708,14 +714,14 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " break;\n"); WRITE(p, " };\n"); WRITE(p, " index0 = ((index0 >> depalShift) & depalMask) | depalOffset;\n"); - WRITE(p, " t = texelFetch(pal, ivec2(index0, 0), 0);\n"); + p.C(" t = ").LoadTexture2D("pal", "ivec2(index0, 0)", 0).C(";\n"); WRITE(p, " if (bilinear && !(index0 == index1 && index1 == index2 && index2 == index3)) {\n"); WRITE(p, " index1 = ((index1 >> depalShift) & depalMask) | depalOffset;\n"); WRITE(p, " index2 = ((index2 >> depalShift) & depalMask) | depalOffset;\n"); WRITE(p, " index3 = ((index3 >> depalShift) & depalMask) | depalOffset;\n"); - WRITE(p, " t1 = texelFetch(pal, ivec2(index1, 0), 0);\n"); - WRITE(p, " t2 = texelFetch(pal, ivec2(index2, 0), 0);\n"); - WRITE(p, " t3 = texelFetch(pal, ivec2(index3, 0), 0);\n"); + p.C(" t1 = ").LoadTexture2D("pal", "ivec2(index1, 0)", 0).C(";\n"); + p.C(" t2 = ").LoadTexture2D("pal", "ivec2(index2, 0)", 0).C(";\n"); + p.C(" t3 = ").LoadTexture2D("pal", "ivec2(index3, 0)", 0).C(";\n"); WRITE(p, " t = mix(t, t1, fraction.x);\n"); WRITE(p, " t2 = mix(t2, t3, fraction.x);\n"); WRITE(p, " t = mix(t, t2, fraction.y);\n"); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index b5abfbde59..cefc86f4c5 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1924,7 +1924,6 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // TODO: Implement shader depal in the fragment shader generator for D3D11 at least. switch (draw_->GetShaderLanguageDesc().shaderLanguage) { - case ShaderLanguage::HLSL_D3D11: case ShaderLanguage::HLSL_D3D9: useShaderDepal = false; break; diff --git a/GPU/D3D11/D3D11Util.cpp b/GPU/D3D11/D3D11Util.cpp index d8a68c5f14..9fd4c64a48 100644 --- a/GPU/D3D11/D3D11Util.cpp +++ b/GPU/D3D11/D3D11Util.cpp @@ -26,13 +26,14 @@ std::vector CompileShaderToBytecodeD3D11(const char *code, size_t codeS std::string errors; if (errorMsgs) { errors = std::string((const char *)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize()); + std::string numberedCode = LineNumberString(code); if (SUCCEEDED(result)) { WARN_LOG(G3D, "%s: %s", "warnings", errors.c_str()); } else { - ERROR_LOG(G3D, "%s: %s", "errors", errors.c_str()); + ERROR_LOG(G3D, "%s: %s\n\n%s", "errors", errors.c_str(), numberedCode.c_str()); } - OutputDebugStringA(LineNumberString(code).c_str()); OutputDebugStringA(errors.c_str()); + OutputDebugStringA(numberedCode.c_str()); errorMsgs->Release(); } if (compiledCode) { diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 2563825ea1..c656f3d7dd 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -180,8 +180,8 @@ void TextureCacheD3D11::ReleaseTexture(TexCacheEntry *entry, bool delete_them) { void TextureCacheD3D11::ForgetLastTexture() { InvalidateLastTexture(); - ID3D11ShaderResourceView *nullTex[2]{}; - context_->PSSetShaderResources(0, 2, nullTex); + ID3D11ShaderResourceView *nullTex[4]{}; + context_->PSSetShaderResources(0, 4, nullTex); } void TextureCacheD3D11::InvalidateLastTexture() { @@ -258,6 +258,7 @@ void TextureCacheD3D11::BindTexture(TexCacheEntry *entry) { SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ID3D11SamplerState *state = samplerCache_.GetOrCreateSampler(device_, samplerKey); context_->PSSetSamplers(0, 1, &state); + gstate_c.SetUseShaderDepal(false, false); } void TextureCacheD3D11::ApplySamplingParams(const SamplerCacheKey &key) { diff --git a/GPU/GLES/ShaderManagerGLES.cpp b/GPU/GLES/ShaderManagerGLES.cpp index 2780fa7799..69bd1384ca 100644 --- a/GPU/GLES/ShaderManagerGLES.cpp +++ b/GPU/GLES/ShaderManagerGLES.cpp @@ -184,13 +184,13 @@ LinkedShader::LinkedShader(GLRenderManager *render, VShaderID VSID, Shader *vs, availableUniforms = vs->GetUniformMask() | fs->GetUniformMask(); std::vector initialize; - initialize.push_back({ &u_tex, 0, 0 }); - initialize.push_back({ &u_fbotex, 0, 1 }); - initialize.push_back({ &u_testtex, 0, 2 }); - initialize.push_back({ &u_pal, 0, 3 }); // CLUT - initialize.push_back({ &u_tess_points, 0, 4 }); // Control Points - initialize.push_back({ &u_tess_weights_u, 0, 5 }); - initialize.push_back({ &u_tess_weights_v, 0, 6 }); + initialize.push_back({ &u_tex, 0, TEX_SLOT_PSP_TEXTURE }); + initialize.push_back({ &u_fbotex, 0, TEX_SLOT_SHADERBLEND_SRC }); + initialize.push_back({ &u_testtex, 0, TEX_SLOT_ALPHATEST }); + initialize.push_back({ &u_pal, 0, TEX_SLOT_CLUT }); // CLUT + initialize.push_back({ &u_tess_points, 0, TEX_SLOT_SPLINE_POINTS }); // Control Points + initialize.push_back({ &u_tess_weights_u, 0, TEX_SLOT_SPLINE_WEIGHTS_U }); + initialize.push_back({ &u_tess_weights_v, 0, TEX_SLOT_SPLINE_WEIGHTS_V }); bool useDualSource = (gstate_c.featureFlags & GPU_SUPPORTS_DUALSOURCE_BLEND) != 0; bool useClip0 = VSID.Bit(VS_BIT_VERTEX_RANGE_CULLING) && gstate_c.Supports(GPU_SUPPORTS_CLIP_DISTANCE); From 694dbe1271085155433ef2ddf52d7305dc8a8bc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 14:14:18 +0200 Subject: [PATCH 088/110] Add ShaderDepalMode enum, use in shader ID. Replaces smoothed bit. --- GPU/Common/FragmentShaderGenerator.cpp | 36 ++++++++++++++++---------- GPU/Common/ShaderId.cpp | 16 +++++++----- GPU/Common/ShaderId.h | 7 +++-- GPU/Common/TextureCacheCommon.cpp | 6 ++--- GPU/D3D11/TextureCacheD3D11.cpp | 2 +- GPU/GLES/TextureCacheGLES.cpp | 2 +- GPU/GPU.h | 7 +++++ GPU/GPUState.h | 10 +++---- GPU/Vulkan/ShaderManagerVulkan.cpp | 2 +- GPU/Vulkan/TextureCacheVulkan.cpp | 2 +- unittest/TestShaderGenerators.cpp | 1 - 11 files changed, 53 insertions(+), 38 deletions(-) diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index feec43ff75..d1aabac698 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -92,8 +92,11 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool flatBug = bugs.Has(Draw::Bugs::BROKEN_FLAT_IN_SHADER) && g_Config.bVendorBugChecksEnabled; bool doFlatShading = id.Bit(FS_BIT_FLATSHADE) && !flatBug; - bool shaderDepal = id.Bit(FS_BIT_SHADER_DEPAL) && !texture3D; // combination with texture3D not supported. Enforced elsewhere too. - bool smoothedDepal = id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL); + ShaderDepalMode shaderDepalMode = (ShaderDepalMode)id.Bits(FS_BIT_SHADER_DEPAL_MODE, 2); + if (texture3D) { + shaderDepalMode = ShaderDepalMode::OFF; + } + bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; @@ -134,7 +137,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu bool needFragCoord = readFramebuffer || gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); bool writeDepth = gstate_c.Supports(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT); - if (shaderDepal && !doTexture) { + if (shaderDepalMode != ShaderDepalMode::OFF && !doTexture) { *errorString = "depal requires a texture"; return false; } @@ -153,7 +156,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "layout (binding = 1) uniform sampler2D fbotex;\n"); } - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { WRITE(p, "layout (binding = 2) uniform sampler2D pal;\n"); } @@ -232,16 +235,13 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "Texture2D fbotex : register(t1);\n"); } - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { WRITE(p, "SamplerState palSamp : register(s3);\n"); WRITE(p, "Texture2D pal : register(t3);\n"); + WRITE(p, "float2 textureSize(Texture2D tex, int mip) { float2 size; tex.GetDimensions(size.x, size.y); return size; }\n"); } WRITE(p, "cbuffer base : register(b0) {\n%s};\n", ub_baseStr); - - if (shaderDepal) { - WRITE(p, "float2 textureSize(Texture2D tex, int mip) { float2 size; tex.GetDimensions(size.x, size.y); return size; }\n"); - } } if (enableAlphaTest) { @@ -302,7 +302,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, "};\n"); } } else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) { - if ((shaderDepal || colorWriteMask) && gl_extensions.IsGLES) { + if ((shaderDepalMode != ShaderDepalMode::OFF || colorWriteMask) && gl_extensions.IsGLES) { WRITE(p, "precision highp int;\n"); } @@ -353,7 +353,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } - if (shaderDepal) { + if (shaderDepalMode != ShaderDepalMode::OFF) { WRITE(p, "uniform sampler2D pal;\n"); WRITE(p, "uniform uint u_depal_mask_shift_off_fmt;\n"); *uniformMask |= DIRTY_DEPAL; @@ -563,7 +563,8 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu doTextureProjection = false; } - if (!shaderDepal) { + switch (shaderDepalMode) { + case ShaderDepalMode::OFF: if (compat.shaderLanguage == HLSL_D3D11) { if (texture3D) { if (doTextureProjection) { @@ -609,7 +610,8 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu } } } - } else if (shaderDepal && smoothedDepal) { + break; + case ShaderDepalMode::SMOOTHED: // Specific mode for Test Drive. Fixes the banding. if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. @@ -636,7 +638,8 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu p.C(" else if (depalShift == 10u) { index0 = t.b; }\n"); p.C(" }\n"); p.F(" t = ").SampleTexture2D("pal", "vec2(index0 * factor, 0.0)").C(";\n"); - } else { + break; + case ShaderDepalMode::NORMAL: if (doTextureProjection) { // We don't use textureProj because we need better control and it's probably not much of a savings anyway. // However it is good for precision on older hardware like PowerVR. @@ -726,6 +729,11 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu WRITE(p, " t2 = mix(t2, t3, fraction.x);\n"); WRITE(p, " t = mix(t, t2, fraction.y);\n"); WRITE(p, " }\n"); + break; + case ShaderDepalMode::CLUT8_8888: + // Not yet implemented. + WRITE(p, " t = vec4(0.0, 0.0, 0.0, 0.0);\n"); + break; } if (texFunc != GE_TEXFUNC_REPLACE || !doTextureAlpha) diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index d05cc3a986..f873024c39 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -180,8 +180,12 @@ std::string FragmentShaderDesc(const FShaderID &id) { if (id.Bit(FS_BIT_COLOR_DOUBLE)) desc << "2x "; if (id.Bit(FS_BIT_FLATSHADE)) desc << "Flat "; if (id.Bit(FS_BIT_BGRA_TEXTURE)) desc << "BGRA "; - if (id.Bit(FS_BIT_SHADER_DEPAL)) desc << "Depal "; - if (id.Bit(FS_BIT_SHADER_SMOOTHED_DEPAL)) desc << "SmoothDepal "; + switch ((ShaderDepalMode)id.Bit(FS_BIT_SHADER_DEPAL_MODE)) { + case ShaderDepalMode::OFF: break; + case ShaderDepalMode::NORMAL: desc << "Depal "; break; + case ShaderDepalMode::SMOOTHED: desc << "SmoothDepal "; break; + case ShaderDepalMode::CLUT8_8888: desc << "CLUT8From8888Depal"; break; + } if (id.Bit(FS_BIT_COLOR_WRITEMASK)) desc << "WriteMask "; if (id.Bit(FS_BIT_SHADER_TEX_CLAMP)) { desc << "TClamp"; @@ -261,8 +265,9 @@ void ComputeFragmentShaderID(FShaderID *id_out, const ComputedPipelineState &pip bool doTextureProjection = (gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX && MatrixNeedsProjection(gstate.tgenMatrix)); bool doTextureAlpha = gstate.isTextureAlphaUsed(); bool doFlatShading = gstate.getShadeMode() == GE_SHADE_FLAT; - bool useShaderDepal = gstate_c.useShaderDepal; - bool useSmoothedDepal = gstate_c.useSmoothedShaderDepal; + + ShaderDepalMode shaderDepalMode = gstate_c.shaderDepalMode; + bool colorWriteMask = pipelineState.maskState.applyFramebufferRead; ReplaceBlendType replaceBlend = pipelineState.blendState.replaceBlend; @@ -289,8 +294,7 @@ void ComputeFragmentShaderID(FShaderID *id_out, const ComputedPipelineState &pip id.SetBit(FS_BIT_TEXTURE_AT_OFFSET, textureAtOffset); } id.SetBit(FS_BIT_BGRA_TEXTURE, gstate_c.bgraTexture); - id.SetBit(FS_BIT_SHADER_DEPAL, useShaderDepal); - id.SetBit(FS_BIT_SHADER_SMOOTHED_DEPAL, useSmoothedDepal); + id.SetBits(FS_BIT_SHADER_DEPAL_MODE, 2, (int)shaderDepalMode); id.SetBit(FS_BIT_3D_TEXTURE, gstate_c.curTextureIs3D); } diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index bd54e2bd82..999faf2e44 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -66,7 +66,7 @@ enum FShaderBit : uint8_t { FS_BIT_DO_TEXTURE = 1, FS_BIT_TEXFUNC = 2, // 3 bits FS_BIT_TEXALPHA = 5, - FS_BIT_SHADER_DEPAL = 6, + FS_BIT_3D_TEXTURE = 6, FS_BIT_SHADER_TEX_CLAMP = 7, FS_BIT_CLAMP_S = 8, FS_BIT_CLAMP_T = 9, @@ -93,9 +93,8 @@ enum FShaderBit : uint8_t { FS_BIT_TEST_DISCARD_TO_ZERO = 48, FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL = 49, FS_BIT_COLOR_WRITEMASK = 50, - FS_BIT_3D_TEXTURE = 51, - FS_BIT_SHADER_SMOOTHED_DEPAL = 52, - FS_BIT_REPLACE_LOGIC_OP = 53, // 4 bits. GE_LOGIC_COPY means no-op/off. + FS_BIT_REPLACE_LOGIC_OP = 51, // 4 bits. GE_LOGIC_COPY means no-op/off. + FS_BIT_SHADER_DEPAL_MODE = 55, // 2 bits (ShaderDepalMode) }; static inline FShaderBit operator +(FShaderBit bit, int i) { diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index cefc86f4c5..1be81f8abc 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -1956,7 +1956,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer // Since we started/ended render passes, might need these. gstate_c.Dirty(DIRTY_DEPAL); - gstate_c.SetUseShaderDepal(true, smoothedDepal); + gstate_c.SetUseShaderDepal(smoothedDepal ? ShaderDepalMode::SMOOTHED : ShaderDepalMode::NORMAL); gstate_c.depalFramebufferFormat = framebuffer->fb_format; const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16); @@ -1972,7 +1972,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer depthUpperBits = (depth && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0; textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format, smoothedDepal, depthUpperBits); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } if (textureShader) { @@ -2045,7 +2045,7 @@ void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET); BoundFramebufferTexture(); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650); } diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index c656f3d7dd..799f905514 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -258,7 +258,7 @@ void TextureCacheD3D11::BindTexture(TexCacheEntry *entry) { SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ID3D11SamplerState *state = samplerCache_.GetOrCreateSampler(device_, samplerKey); context_->PSSetSamplers(0, 1, &state); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheD3D11::ApplySamplingParams(const SamplerCacheKey &key) { diff --git a/GPU/GLES/TextureCacheGLES.cpp b/GPU/GLES/TextureCacheGLES.cpp index 928854f1e2..14ebad20be 100644 --- a/GPU/GLES/TextureCacheGLES.cpp +++ b/GPU/GLES/TextureCacheGLES.cpp @@ -230,7 +230,7 @@ void TextureCacheGLES::BindTexture(TexCacheEntry *entry) { int maxLevel = (entry->status & TexCacheEntry::STATUS_NO_MIPS) ? 0 : entry->maxLevel; SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry); ApplySamplingParams(samplerKey); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheGLES::Unbind() { diff --git a/GPU/GPU.h b/GPU/GPU.h index 5410fb43d5..1fd455c662 100644 --- a/GPU/GPU.h +++ b/GPU/GPU.h @@ -40,6 +40,13 @@ enum SkipDrawReasonFlags { SKIPDRAW_WINDOW_MINIMIZED = 8, // Don't draw when the host window is minimized. }; +enum class ShaderDepalMode { + OFF = 0, + NORMAL = 1, + SMOOTHED = 2, + CLUT8_8888 = 3, // Read 8888 framebuffer as 8-bit CLUT. +}; + // Global GPU-related utility functions. // Nothing directly Ge-related in here. diff --git a/GPU/GPUState.h b/GPU/GPUState.h index f31d31e176..cbfb58395d 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -529,10 +529,9 @@ struct GPUStateCache { bool IsDirty(u64 what) const { return (dirty & what) != 0ULL; } - void SetUseShaderDepal(bool depal, bool smoothed) { - if (depal != useShaderDepal) { - useShaderDepal = depal; - useSmoothedShaderDepal = smoothed; + void SetUseShaderDepal(ShaderDepalMode mode) { + if (mode != shaderDepalMode) { + shaderDepalMode = mode; Dirty(DIRTY_FRAGMENTSHADER_STATE); } } @@ -628,8 +627,7 @@ struct GPUStateCache { SubmitType submitType; int spline_num_points_u; - bool useShaderDepal; - bool useSmoothedShaderDepal; + ShaderDepalMode shaderDepalMode; GEBufferFormat depalFramebufferFormat; u32 getRelativeAddress(u32 data) const; diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index b3e5ff339f..9cb91e00c6 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -371,7 +371,7 @@ VulkanFragmentShader *ShaderManagerVulkan::GetFragmentShaderFromModule(VkShaderM // instantaneous. #define CACHE_HEADER_MAGIC 0xff51f420 -#define CACHE_VERSION 25 +#define CACHE_VERSION 26 struct VulkanCacheHeader { uint32_t magic; uint32_t version; diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index d11e92ba05..bbb0f611bb 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -403,7 +403,7 @@ void TextureCacheVulkan::BindTexture(TexCacheEntry *entry) { curSampler_ = samplerCache_.GetOrCreateSampler(samplerKey); imageView_ = entry->vkTex->GetImageView(); drawEngine_->SetDepalTexture(VK_NULL_HANDLE, false); - gstate_c.SetUseShaderDepal(false, false); + gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF); } void TextureCacheVulkan::ApplySamplingParams(const SamplerCacheKey &key) { diff --git a/unittest/TestShaderGenerators.cpp b/unittest/TestShaderGenerators.cpp index 7bdb0b3e8c..8cf73cd8b4 100644 --- a/unittest/TestShaderGenerators.cpp +++ b/unittest/TestShaderGenerators.cpp @@ -402,7 +402,6 @@ bool TestFragmentShaders() { // bits we don't need to test because they are irrelevant on d3d11 id.SetBit(FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL, false); - id.SetBit(FS_BIT_SHADER_DEPAL, false); // DX9 disabling: if (static_cast(id.Bits(FS_BIT_STENCIL_TO_ALPHA, 2)) == ReplaceAlphaType::REPLACE_ALPHA_DUALSOURCE) From 4491c480a62ad3e1a6ce47d9fb4d7e04dbbc142b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 14:46:00 +0200 Subject: [PATCH 089/110] Texture/framebuffer matching: Do margin check in bytes. --- GPU/Common/FramebufferManagerCommon.h | 1 + GPU/Common/TextureCacheCommon.cpp | 41 +++++++++++++++------------ 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/GPU/Common/FramebufferManagerCommon.h b/GPU/Common/FramebufferManagerCommon.h index e4e2b86cf6..b54cc0611d 100644 --- a/GPU/Common/FramebufferManagerCommon.h +++ b/GPU/Common/FramebufferManagerCommon.h @@ -148,6 +148,7 @@ struct VirtualFramebuffer { // Convenience methods inline int WidthInBytes() const { return width * BufferFormatBytesPerPixel(fb_format); } + inline int BufferWidthInBytes() const { return bufferWidth * BufferFormatBytesPerPixel(fb_format); } inline int FbStrideInBytes() const { return fb_stride * BufferFormatBytesPerPixel(fb_format); } inline int ZStrideInBytes() const { return z_stride * 2; } }; diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 1be81f8abc..1e7b7137a8 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -915,10 +915,11 @@ bool TextureCacheCommon::MatchFramebuffer( const bool noOffset = texaddr == addr; const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes; - const u32 w = 1 << ((entry.dim >> 0) & 0xf); - const u32 h = 1 << ((entry.dim >> 8) & 0xf); + const u32 texWidth = 1 << ((entry.dim >> 0) & 0xf); + const u32 texHeight = 1 << ((entry.dim >> 8) & 0xf); + // 512 on a 272 framebuffer is sane, so let's be lenient. - const u32 minSubareaHeight = h / 4; + const u32 minSubareaHeight = texHeight / 4; // If they match "exactly", it's non-CLUT and from the top left. if (exactMatch) { @@ -948,19 +949,20 @@ bool TextureCacheCommon::MatchFramebuffer( (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); - const int bitOffset = (texaddr - addr) * 8; - if (bitOffset != 0) { - const int pixelOffset = bitOffset / (int)std::max(1U, (u32)textureBitsPerPixel[entry.format]); + const int texBitsPerPixel = std::max(1U, (u32)textureBitsPerPixel[entry.format]); + const int byteOffset = texaddr - addr; + if (byteOffset != 0) { + const int texelOffset = byteOffset * 8 / texBitsPerPixel; - if (pixelOffset > 0) { - matchInfo->yOffset = entry.bufw == 0 ? 0 : pixelOffset / (int)entry.bufw; - matchInfo->xOffset = entry.bufw == 0 ? 0 : pixelOffset % (int)entry.bufw; - } else if (pixelOffset < 0) { + if (texelOffset > 0) { + matchInfo->yOffset = entry.bufw == 0 ? 0 : texelOffset / (int)entry.bufw; + matchInfo->xOffset = entry.bufw == 0 ? 0 : texelOffset % (int)entry.bufw; + } else if (texelOffset < 0) { // We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround. - if (pixelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { + if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { return false; } - matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-pixelOffset % (int)entry.bufw); + matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw); } } @@ -969,13 +971,11 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } - if (fb_stride_in_bytes != tex_stride_in_bytes) { - // Probably irrelevant. - return false; - } - // Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.) - if (matchInfo->xOffset >= framebuffer->bufferWidth && matchInfo->xOffset + w <= (u32)fb_stride) { + // Do the computation in bytes so that it's valid even in case of weird reinterpret scenarios. + const int xOffsetInBytes = matchInfo->xOffset * 8 / texBitsPerPixel; + const int texWidthInBytes = texWidth * 8 / texBitsPerPixel; + if (xOffsetInBytes >= framebuffer->BufferWidthInBytes() && xOffsetInBytes + texWidthInBytes <= (int)fb_stride_in_bytes) { // This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride. return false; } @@ -987,6 +987,11 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + if (fb_stride_in_bytes != tex_stride_in_bytes) { + // Probably irrelevant. Although, as we shall see soon, there are exceptions. + return false; + } + // Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture. // 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture. if (matchingClutFormat) { From a30896e21facb291357c72fd65207b1933983061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 15:08:47 +0200 Subject: [PATCH 090/110] Switch more texture matching calculations to use bytes for matching. --- GPU/Common/TextureCacheCommon.cpp | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 1e7b7137a8..94742aad19 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -883,6 +883,11 @@ bool TextureCacheCommon::MatchFramebuffer( return false; } + if (!fb_stride) { + // Hard to make decisions. + return false; + } + switch (entry.format) { case GE_TFMT_DXT1: case GE_TFMT_DXT3: @@ -947,23 +952,21 @@ bool TextureCacheCommon::MatchFramebuffer( (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) || (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) || (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || - (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); + (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16) || + (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT8); // Mixed byte size, format, reinterpret in depal! const int texBitsPerPixel = std::max(1U, (u32)textureBitsPerPixel[entry.format]); const int byteOffset = texaddr - addr; - if (byteOffset != 0) { - const int texelOffset = byteOffset * 8 / texBitsPerPixel; - - if (texelOffset > 0) { - matchInfo->yOffset = entry.bufw == 0 ? 0 : texelOffset / (int)entry.bufw; - matchInfo->xOffset = entry.bufw == 0 ? 0 : texelOffset % (int)entry.bufw; - } else if (texelOffset < 0) { - // We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround. - if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { - return false; - } - matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw); + if (byteOffset > 0) { + matchInfo->yOffset = byteOffset / fb_stride_in_bytes; + matchInfo->xOffset = 8 * (byteOffset % fb_stride_in_bytes) / texBitsPerPixel; + } else if (byteOffset < 0) { + int texelOffset = 8 * byteOffset / texBitsPerPixel; + // We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround. + if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) { + return false; } + matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw); } if (matchInfo->yOffset > 0 && matchInfo->yOffset + minSubareaHeight >= framebuffer->height) { From 3e7f6b57aaaffc2eef534aae3b786e8942475593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 16:17:38 +0200 Subject: [PATCH 091/110] Shadergen issues found by the test --- Common/GPU/ShaderWriter.cpp | 2 +- GPU/Common/FragmentShaderGenerator.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Common/GPU/ShaderWriter.cpp b/Common/GPU/ShaderWriter.cpp index 62d5760408..b260d05fc9 100644 --- a/Common/GPU/ShaderWriter.cpp +++ b/Common/GPU/ShaderWriter.cpp @@ -453,7 +453,7 @@ ShaderWriter &ShaderWriter::LoadTexture2D(const char *sampName, const char *uv, break; default: // Note: we ignore the sampler. make sure you bound samplers to the textures correctly. - F("texelFetch(%s, %s, %d)", lang_.texture, sampName, uv, level); + F("texelFetch(%s, %s, %d)", sampName, uv, level); break; } return *this; diff --git a/GPU/Common/FragmentShaderGenerator.cpp b/GPU/Common/FragmentShaderGenerator.cpp index d1aabac698..fe3d685f28 100644 --- a/GPU/Common/FragmentShaderGenerator.cpp +++ b/GPU/Common/FragmentShaderGenerator.cpp @@ -96,7 +96,10 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu if (texture3D) { shaderDepalMode = ShaderDepalMode::OFF; } - + if (!compat.bitwiseOps && shaderDepalMode != ShaderDepalMode::OFF) { + *errorString = "depal requires bitwise ops"; + return false; + } bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE); bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps; @@ -732,7 +735,7 @@ bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLangu break; case ShaderDepalMode::CLUT8_8888: // Not yet implemented. - WRITE(p, " t = vec4(0.0, 0.0, 0.0, 0.0);\n"); + WRITE(p, " vec4 t = vec4(0.0, 0.0, 0.0, 0.0);\n"); break; } From 2e3b73abaace9dbf10f467bd2f0443aba5923b49 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 08:22:37 -0700 Subject: [PATCH 092/110] softgpu: Restrict sprite fast path to throughmode. Its UV checks already should have generally, but let's be safe. It doesn't validate state like fog, etc. --- GPU/Software/RasterizerRectangle.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index 424c4549bd..c94e23beb6 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -267,8 +267,6 @@ static inline bool NoClampOrWrap(const RasterizerState &state, const Vec2f &tc) return false; if (state.samplerID.cached.sizes[0].w > 512 || state.samplerID.cached.sizes[0].h > 512) return false; - if (!state.throughMode) - return tc.x <= 1.0f && tc.y <= 1.0f; return tc.x <= state.samplerID.cached.sizes[0].w && tc.y <= state.samplerID.cached.sizes[0].h; } @@ -288,7 +286,7 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b // Currently only works for TL/BR, which is the most common but not required. bool orient_check = xdiff >= 0 && ydiff >= 0; // We already have a fast path for clear in ClearRectangle. - bool state_check = !state.pixelID.clearMode && !state.samplerID.hasAnyMips && NoClampOrWrap(state, v0.texturecoords) && NoClampOrWrap(state, v1.texturecoords); + bool state_check = state.throughMode && !state.pixelID.clearMode && !state.samplerID.hasAnyMips && NoClampOrWrap(state, v0.texturecoords) && NoClampOrWrap(state, v1.texturecoords); // This doesn't work well with offset drawing, see #15876. Through never has a subpixel offset. bool subpixel_check = ((v0.screenpos.x | v0.screenpos.y | v1.screenpos.x | v1.screenpos.y) & 0xF) == 0; if ((coord_check || !state.enableTextures) && orient_check && state_check && subpixel_check) { From b90fc7137f2ec58246294c68a5eb30a05ee9451d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 08:24:40 -0700 Subject: [PATCH 093/110] softgpu: Correct accuracy of fog calculation. This matches values from a PSP exactly, with the help of immediate mode vertex values (since this directly allows specifying the fog factor without any floating point math.) --- GPU/Math3D.h | 10 +++++----- GPU/Software/DrawPixel.cpp | 4 +++- GPU/Software/Rasterizer.cpp | 6 +++--- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/GPU/Math3D.h b/GPU/Math3D.h index dd1991f917..a87cce8318 100644 --- a/GPU/Math3D.h +++ b/GPU/Math3D.h @@ -228,11 +228,11 @@ public: Vec3() {} Vec3(const T a[3]) : x(a[0]), y(a[1]), z(a[2]) {} - Vec3(const T& _x, const T& _y, const T& _z) : x(_x), y(_y), z(_z) {} + constexpr Vec3(const T& _x, const T& _y, const T& _z) : x(_x), y(_y), z(_z) {} Vec3(const Vec2& _xy, const T& _z) : x(_xy.x), y(_xy.y), z(_z) {} #if defined(_M_SSE) - Vec3(const __m128 &_vec) : vec(_vec) {} - Vec3(const __m128i &_ivec) : ivec(_ivec) {} + constexpr Vec3(const __m128 &_vec) : vec(_vec) {} + constexpr Vec3(const __m128i &_ivec) : ivec(_ivec) {} Vec3(const Vec3Packed &_xyz) { vec = _mm_loadu_ps(_xyz.AsArray()); } @@ -249,7 +249,7 @@ public: #endif template - Vec3 Cast() const + constexpr Vec3 Cast() const { return Vec3((T2)x, (T2)y, (T2)z); } @@ -258,7 +258,7 @@ public: static Vec3 FromRGB(unsigned int rgb); unsigned int ToRGB() const; // alpha bits set to zero - static Vec3 AssignToAll(const T& f) + static constexpr Vec3 AssignToAll(const T& f) { return Vec3(f, f, f); } diff --git a/GPU/Software/DrawPixel.cpp b/GPU/Software/DrawPixel.cpp index ab244aacf8..2194c69e55 100644 --- a/GPU/Software/DrawPixel.cpp +++ b/GPU/Software/DrawPixel.cpp @@ -415,7 +415,9 @@ void SOFTRAST_CALL DrawSinglePixel(int x, int y, int z, int fog, Vec4IntArg colo // Fog is applied prior to color test. if (pixelID.applyFog && !clearMode) { Vec3 fogColor = Vec3::FromRGB(pixelID.cached.fogColor); - fogColor = (prim_color.rgb() * fog + fogColor * (255 - fog)) / 255; + // This is very similar to the BLEND texfunc, and simply always rounds up. + static constexpr Vec3 roundup = Vec3::AssignToAll(255); + fogColor = (prim_color.rgb() * fog + fogColor * (255 - fog) + roundup) / 256; prim_color.r() = fogColor.r(); prim_color.g() = fogColor.g(); prim_color.b() = fogColor.b(); diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index ed8848ce80..0348f6d57a 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -348,7 +348,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_adds_epi16(s, d), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return lhs + rhs; @@ -370,7 +370,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_max_epi16(_mm_subs_epi16(s, d), _mm_setzero_si128()), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return lhs - rhs; @@ -392,7 +392,7 @@ Vec3 AlphaBlendingResult(const PixelFuncID &pixelID, const Vec4 &sourc return Vec3(_mm_unpacklo_epi16(_mm_max_epi16(_mm_subs_epi16(d, s), _mm_setzero_si128()), _mm_setzero_si128())); #else - Vec3 half = Vec3::AssignToAll(1); + static constexpr Vec3 half = Vec3::AssignToAll(1); Vec3 lhs = ((source.rgb() * 2 + half) * (srcfactor * 2 + half)) / 1024; Vec3 rhs = ((dst.rgb() * 2 + half) * (dstfactor * 2 + half)) / 1024; return rhs - lhs; From e72309745eb330d3c04b4f13c6fd8ed957e869a3 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 08:50:07 -0700 Subject: [PATCH 094/110] softjit: Implement accurate fog color blending. --- GPU/Software/DrawPixel.cpp | 2 -- GPU/Software/DrawPixel.h | 2 -- GPU/Software/DrawPixelX86.cpp | 26 ++++++++++++-------------- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/GPU/Software/DrawPixel.cpp b/GPU/Software/DrawPixel.cpp index 2194c69e55..ee47c27b94 100644 --- a/GPU/Software/DrawPixel.cpp +++ b/GPU/Software/DrawPixel.cpp @@ -550,8 +550,6 @@ void PixelJitCache::Clear() { constBlendHalf_11_4s_ = nullptr; constBlendInvert_11_4s_ = nullptr; - const255_16s_ = nullptr; - constBy255i_ = nullptr; } std::string PixelJitCache::DescribeCodePtr(const u8 *ptr) { diff --git a/GPU/Software/DrawPixel.h b/GPU/Software/DrawPixel.h index 982ee27765..f813bf61c1 100644 --- a/GPU/Software/DrawPixel.h +++ b/GPU/Software/DrawPixel.h @@ -106,8 +106,6 @@ private: const u8 *constBlendHalf_11_4s_ = nullptr; const u8 *constBlendInvert_11_4s_ = nullptr; - const u8 *const255_16s_ = nullptr; - const u8 *constBy255i_ = nullptr; #if PPSSPP_ARCH(X86) || PPSSPP_ARCH(AMD64) void Discard(); diff --git a/GPU/Software/DrawPixelX86.cpp b/GPU/Software/DrawPixelX86.cpp index 8f006bece4..dc53be1c62 100644 --- a/GPU/Software/DrawPixelX86.cpp +++ b/GPU/Software/DrawPixelX86.cpp @@ -336,12 +336,6 @@ void PixelJitCache::WriteConstantPool(const PixelFuncID &id) { // This is used for shifted blend factors, to inverse them. WriteSimpleConst8x16(constBlendInvert_11_4s_, 0xFF << 4); - - // A set of 255s, used to inverse fog. - WriteSimpleConst8x16(const255_16s_, 0xFF); - - // This is used for a multiply that divides by 255 with shifting. - WriteSimpleConst8x16(constBy255i_, 0x8081); } bool PixelJitCache::Jit_ApplyDepthRange(const PixelFuncID &id) { @@ -535,7 +529,8 @@ bool PixelJitCache::Jit_ApplyFog(const PixelFuncID &id) { // Load a set of 255s at 16 bit into a reg for later... X64Reg invertReg = regCache_.Alloc(RegCache::VEC_TEMP2); - MOVDQA(invertReg, M(const255_16s_)); + PCMPEQW(invertReg, R(invertReg)); + PSRLW(invertReg, 8); // Expand (we clamped) color to 16 bit as well, so we can multiply with fog. X64Reg argColorReg = regCache_.Find(RegCache::VEC_ARG_COLOR); @@ -568,21 +563,24 @@ bool PixelJitCache::Jit_ApplyFog(const PixelFuncID &id) { // We can free up the actual fog reg now. regCache_.ForceRelease(RegCache::GEN_ARG_FOG); + // Our goal here is to calculate this formula: + // (argColor * fog + fogColor * (255 - fog) + 255) / 256 + // Now we multiply the existing color by fog... PMULLW(argColorReg, R(fogMultReg)); - // And then inverse the fog value using those 255s we loaded, and multiply by fog color. - PSUBUSW(invertReg, R(fogMultReg)); + // Before inversing, let's add that 255 we loaded in as well, since we have it. + PADDW(argColorReg, R(invertReg)); + // And then inverse the fog value using those 255s, and multiply by fog color. + PSUBW(invertReg, R(fogMultReg)); PMULLW(fogColorReg, R(invertReg)); // At this point, argColorReg and fogColorReg are multiplied at 16-bit, so we need to sum. - PADDUSW(argColorReg, R(fogColorReg)); + PADDW(argColorReg, R(fogColorReg)); regCache_.Release(fogColorReg, RegCache::VEC_TEMP1); regCache_.Release(invertReg, RegCache::VEC_TEMP2); regCache_.Release(fogMultReg, RegCache::VEC_TEMP3); - // Now to divide by 255, we use bit tricks: multiply by 0x8081, and shift right by 16+7. - PMULHUW(argColorReg, M(constBy255i_)); - // Now shift right by 7 (PMULHUW already did 16 of the shift.) - PSRLW(argColorReg, 7); + // Now we simply divide by 256, or in other words shift by 8. + PSRLW(argColorReg, 8); // Okay, put A back in, we'll shrink it to 8888 when needed. PINSRW(argColorReg, R(alphaReg), 3); From 8c55e18ea81ce7dde6c27a6010d3ebaf134f4ccb Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 08:54:34 -0700 Subject: [PATCH 095/110] softgpu: Switch vert continue buffer to members. Better this than static. May be easier to handle imm prims correctly. --- GPU/Software/TransformUnit.cpp | 123 ++++++++++++++++----------------- GPU/Software/TransformUnit.h | 6 ++ 2 files changed, 65 insertions(+), 64 deletions(-) diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index 2a8eeeffa6..28a91a7a8c 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -482,16 +482,11 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G VertexReader vreader(decoded_, vtxfmt, vertex_type); - static VertexData data[4]; // Normally max verts per prim is 3, but we temporarily need 4 to detect rectangles from strips. - // This is the index of the next vert in data (or higher, may need modulus.) - static int data_index = 0; - - static GEPrimitiveType prev_prim = GE_PRIM_POINTS; if (prim_type != GE_PRIM_KEEP_PREVIOUS) { - data_index = 0; - prev_prim = prim_type; + data_index_ = 0; + prev_prim_ = prim_type; } else { - prim_type = prev_prim; + prim_type = prev_prim_; } int vtcs_per_prim; @@ -530,14 +525,14 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[data_index++] = ReadVertex(vreader, transformState, outside_range_flag); - if (data_index < vtcs_per_prim) { + data_[data_index_++] = ReadVertex(vreader, transformState, outside_range_flag); + if (data_index_ < vtcs_per_prim) { // Keep reading. Note: an incomplete prim will stay read for GE_PRIM_KEEP_PREVIOUS. continue; } // Okay, we've got enough verts. Reset the index for next time. - data_index = 0; + data_index_ = 0; if (outside_range_flag) { // Cull the prim if it was outside, and move to the next prim. outside_range_flag = false; @@ -548,22 +543,22 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G case GE_PRIM_TRIANGLES: { if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[2], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[2], *binner_); + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[2], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[2], *binner_); } else if (cullType == CullType::CW) { - Clipper::ProcessTriangle(data[2], data[1], data[0], data[2], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[2], *binner_); } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[2], *binner_); + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[2], *binner_); } break; } case GE_PRIM_LINES: - Clipper::ProcessLine(data[0], data[1], *binner_); + Clipper::ProcessLine(data_[0], data_[1], *binner_); break; case GE_PRIM_POINTS: - Clipper::ProcessPoint(data[0], *binner_); + Clipper::ProcessPoint(data_[0], *binner_); break; default: @@ -581,45 +576,45 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[data_index++] = ReadVertex(vreader, transformState, outside_range_flag); + data_[data_index_++] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { outside_range_flag = false; // Note: this is the post increment index. If odd, we set the first vert. - if (data_index & 1) { + if (data_index_ & 1) { // Skip the next one and forget this one. vtx++; - data_index--; + data_index_--; } else { // Forget both of the last 2. - data_index -= 2; + data_index_ -= 2; } } - if (data_index == 4 && vreader.isThrough() && cullType == CullType::OFF) { - if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data)) { - data[1] = data[3]; - data_index = 2; + if (data_index_ == 4 && vreader.isThrough() && cullType == CullType::OFF) { + if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data_)) { + data_[1] = data_[3]; + data_index_ = 2; } } - if (data_index == 4) { - Clipper::ProcessRect(data[0], data[1], *binner_); - Clipper::ProcessRect(data[2], data[3], *binner_); - data_index = 0; + if (data_index_ == 4) { + Clipper::ProcessRect(data_[0], data_[1], *binner_); + Clipper::ProcessRect(data_[2], data_[3], *binner_); + data_index_ = 0; } } - if (data_index >= 2) { - Clipper::ProcessRect(data[0], data[1], *binner_); - data_index -= 2; + if (data_index_ >= 2) { + Clipper::ProcessRect(data_[0], data_[1], *binner_); + data_index_ -= 2; } break; case GE_PRIM_LINE_STRIP: { // Don't draw a line when loading the first vertex. - // If data_index is 1 or 2, etc., it means we're continuing a line strip. - int skip_count = data_index == 0 ? 1 : 0; + // If data_index_ is 1 or 2, etc., it means we're continuing a line strip. + int skip_count = data_index_ == 0 ? 1 : 0; for (int vtx = 0; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); @@ -627,7 +622,7 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - data[(data_index++) & 1] = ReadVertex(vreader, transformState, outside_range_flag); + data_[(data_index_++) & 1] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -638,8 +633,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G if (skip_count) { --skip_count; } else { - // We already incremented data_index, so data_index & 1 is previous one. - Clipper::ProcessLine(data[data_index & 1], data[(data_index & 1) ^ 1], *binner_); + // We already incremented data_index_, so data_index_ & 1 is previous one. + Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_); } } break; @@ -648,11 +643,11 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G case GE_PRIM_TRIANGLE_STRIP: { // Don't draw a triangle when loading the first two vertices. - int skip_count = data_index >= 2 ? 0 : 2 - data_index; + int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_; // If index count == 4, check if we can convert to a rectangle. // This is for Darkstalkers (and should speed up many 2D games). - if (data_index == 0 && vertex_count == 4 && cullType == CullType::OFF) { + if (data_index_ == 0 && vertex_count == 4 && cullType == CullType::OFF) { for (int vtx = 0; vtx < 4; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); @@ -660,13 +655,13 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G else { vreader.Goto(vtx); } - data[vtx] = ReadVertex(vreader, transformState, outside_range_flag); + data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); } // If a strip is effectively a rectangle, draw it as such! int tl = -1, br = -1; - if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data, &tl, &br)) { - Clipper::ProcessRect(data[tl], data[br], *binner_); + if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) { + Clipper::ProcessRect(data_[tl], data_[br], *binner_); break; } } @@ -679,8 +674,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - int provoking_index = (data_index++) % 3; - data[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); + int provoking_index = (data_index_++) % 3; + data_[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -694,14 +689,14 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G } if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index - 1) % 2)) { + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); + } else if ((!(int)cullType) ^ ((data_index_ - 1) % 2)) { // We need to reverse the vertex order for each second primitive, // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); } } break; @@ -711,18 +706,18 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G { // Don't draw a triangle when loading the first two vertices. // (this doesn't count the central one.) - int skip_count = data_index <= 1 ? 1 : 0; + int skip_count = data_index_ <= 1 ? 1 : 0; int start_vtx = 0; // Only read the central vertex if we're not continuing. - if (data_index == 0) { + if (data_index_ == 0) { if (indices) { vreader.Goto(ConvertIndex(0) - index_lower_bound); } else { vreader.Goto(0); } - data[0] = ReadVertex(vreader, transformState, outside_range_flag); - data_index++; + data_[0] = ReadVertex(vreader, transformState, outside_range_flag); + data_index_++; start_vtx = 1; // If the central vertex is outside range, all the points are toast. @@ -730,19 +725,19 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G break; } - if (data_index == 1 && vertex_count == 4 && cullType == CullType::OFF) { + if (data_index_ == 1 && vertex_count == 4 && cullType == CullType::OFF) { for (int vtx = start_vtx; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); } else { vreader.Goto(vtx); } - data[vtx] = ReadVertex(vreader, transformState, outside_range_flag); + data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); } int tl = -1, br = -1; - if (!outside_range_flag && Rasterizer::DetectRectangleFromFan(binner_->State(), data, vertex_count, &tl, &br)) { - Clipper::ProcessRect(data[tl], data[br], *binner_); + if (!outside_range_flag && Rasterizer::DetectRectangleFromFan(binner_->State(), data_, vertex_count, &tl, &br)) { + Clipper::ProcessRect(data_[tl], data_[br], *binner_); break; } } @@ -755,8 +750,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G vreader.Goto(vtx); } - int provoking_index = 2 - ((data_index++) % 2); - data[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); + int provoking_index = 2 - ((data_index_++) % 2); + data_[provoking_index] = ReadVertex(vreader, transformState, outside_range_flag); if (outside_range_flag) { // Drop all primitives containing the current vertex skip_count = 2; @@ -770,14 +765,14 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G } if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index - 1) % 2)) { + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); + } else if ((!(int)cullType) ^ ((data_index_ - 1) % 2)) { // We need to reverse the vertex order for each second primitive, // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data[2], data[1], data[0], data[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); } else { - Clipper::ProcessTriangle(data[0], data[1], data[2], data[provoking_index], *binner_); + Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); } } break; diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index 54f9fb5f5e..faa761639c 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -136,6 +136,12 @@ private: u8 *decoded_ = nullptr; BinManager *binner_ = nullptr; + + // Normally max verts per prim is 3, but we temporarily need 4 to detect rectangles from strips. + VertexData data_[4]; + // This is the index of the next vert in data (or higher, may need modulus.) + int data_index_ = 0; + GEPrimitiveType prev_prim_ = GE_PRIM_POINTS; }; class SoftwareDrawEngine : public DrawEngineCommon { From cf959a846774308cf5f8750188bf5ff856d5b4e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 11 Sep 2022 19:33:31 +0200 Subject: [PATCH 096/110] Remove CLUT matching case that shouldn't be there yet. --- GPU/Common/TextureCacheCommon.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index 94742aad19..ff8ff95098 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -952,8 +952,7 @@ bool TextureCacheCommon::MatchFramebuffer( (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) || (fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) || (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) || - (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16) || - (fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT8); // Mixed byte size, format, reinterpret in depal! + (fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16); const int texBitsPerPixel = std::max(1U, (u32)textureBitsPerPixel[entry.format]); const int byteOffset = texaddr - addr; From aa377662dd0ccf7fc9bca7f05d8b87af6fddb998 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 10:57:04 -0700 Subject: [PATCH 097/110] GE Debugger: Provide addrs in breakpoint conds. Easier to just refer to the full address. --- GPU/Common/GPUDebugInterface.cpp | 46 ++++++++++++++++++++++++++++++-- GPU/Debugger/GECommandTable.cpp | 22 +++++++-------- 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index d5d9c564db..a058d6cbf6 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -31,6 +31,18 @@ enum class GEReferenceIndex : uint32_t { BFLAG, OP, DATA, + CLUTADDR, + TRANSFERSRC, + TRANSFERDST, + + TEXADDR0, + TEXADDR1, + TEXADDR2, + TEXADDR3, + TEXADDR4, + TEXADDR5, + TEXADDR6, + TEXADDR7, BONE_MATRIX = 0x200, WORLD_MATRIX = 0x260, @@ -56,6 +68,17 @@ static constexpr ReferenceName referenceNames[] = { { GEReferenceIndex::BFLAG, "boundflag" }, { GEReferenceIndex::OP, "op" }, { GEReferenceIndex::DATA, "data" }, + { GEReferenceIndex::CLUTADDR, "clutaddr" }, + { GEReferenceIndex::TRANSFERSRC, "transfersrc" }, + { GEReferenceIndex::TRANSFERDST, "transferdst" }, + { GEReferenceIndex::TEXADDR0, "texaddr0" }, + { GEReferenceIndex::TEXADDR1, "texaddr1" }, + { GEReferenceIndex::TEXADDR2, "texaddr2" }, + { GEReferenceIndex::TEXADDR3, "texaddr3" }, + { GEReferenceIndex::TEXADDR4, "texaddr4" }, + { GEReferenceIndex::TEXADDR5, "texaddr5" }, + { GEReferenceIndex::TEXADDR6, "texaddr6" }, + { GEReferenceIndex::TEXADDR7, "texaddr7" }, }; class GEExpressionFunctions : public IExpressionFunctions { @@ -133,15 +156,15 @@ bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { } uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { + GPUgstate state = gpu_->GetGState(); if (referenceIndex < 0x100) { - uint32_t value = gpu_->GetGState().cmdmem[referenceIndex]; + uint32_t value = state.cmdmem[referenceIndex]; // TODO: Later, support float values and similar. return value & 0x00FFFFFF; } // We return the matrix value as float bits, which gets interpreted correctly in the parser. if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) { - GPUgstate state = gpu_->GetGState(); float value; if (referenceIndex >= (uint32_t)GEReferenceIndex::TGEN_MATRIX) { value = state.tgenMatrix[referenceIndex - (uint32_t)GEReferenceIndex::TGEN_MATRIX]; @@ -197,6 +220,25 @@ uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { } return 0; + case GEReferenceIndex::CLUTADDR: + return state.getClutAddress(); + + case GEReferenceIndex::TRANSFERSRC: + return state.getTransferSrcAddress(); + + case GEReferenceIndex::TRANSFERDST: + return state.getTransferDstAddress(); + + case GEReferenceIndex::TEXADDR0: + case GEReferenceIndex::TEXADDR1: + case GEReferenceIndex::TEXADDR2: + case GEReferenceIndex::TEXADDR3: + case GEReferenceIndex::TEXADDR4: + case GEReferenceIndex::TEXADDR5: + case GEReferenceIndex::TEXADDR6: + case GEReferenceIndex::TEXADDR7: + return state.getTextureAddress((int)ref - (int)GEReferenceIndex::TEXADDR0); + case GEReferenceIndex::BONE_MATRIX: case GEReferenceIndex::WORLD_MATRIX: case GEReferenceIndex::VIEW_MATRIX: diff --git a/GPU/Debugger/GECommandTable.cpp b/GPU/Debugger/GECommandTable.cpp index 16304b9d75..e0e9573211 100644 --- a/GPU/Debugger/GECommandTable.cpp +++ b/GPU/Debugger/GECommandTable.cpp @@ -188,14 +188,14 @@ static constexpr GECmdInfo geCmdInfo[] = { { GE_CMD_FRAMEBUFWIDTH, "fbstride", GECmdFormat::STRIDE }, { GE_CMD_ZBUFPTR, "zbptr", GECmdFormat::LOW_ADDR_ONLY }, { GE_CMD_ZBUFWIDTH, "zbstride", GECmdFormat::STRIDE }, - { GE_CMD_TEXADDR0, "texaddr0", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR1, "texaddr1", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR2, "texaddr2", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR3, "texaddr3", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR4, "texaddr4", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR5, "texaddr5", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR6, "texaddr6", GECmdFormat::LOW_ADDR }, - { GE_CMD_TEXADDR7, "texaddr7", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR0, "texaddr0low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR1, "texaddr1low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR2, "texaddr2low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR3, "texaddr3low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR4, "texaddr4low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR5, "texaddr5low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR6, "texaddr6low", GECmdFormat::LOW_ADDR }, + { GE_CMD_TEXADDR7, "texaddr7low", GECmdFormat::LOW_ADDR }, { GE_CMD_TEXBUFWIDTH0, "texbufw0", GECmdFormat::STRIDE_HIGH_ADDR }, { GE_CMD_TEXBUFWIDTH1, "texbufw1", GECmdFormat::STRIDE_HIGH_ADDR }, { GE_CMD_TEXBUFWIDTH2, "texbufw2", GECmdFormat::STRIDE_HIGH_ADDR }, @@ -204,11 +204,11 @@ static constexpr GECmdInfo geCmdInfo[] = { { GE_CMD_TEXBUFWIDTH5, "texbufw5", GECmdFormat::STRIDE_HIGH_ADDR }, { GE_CMD_TEXBUFWIDTH6, "texbufw6", GECmdFormat::STRIDE_HIGH_ADDR }, { GE_CMD_TEXBUFWIDTH7, "texbufw7", GECmdFormat::STRIDE_HIGH_ADDR }, - { GE_CMD_CLUTADDR, "clutaddr", GECmdFormat::LOW_ADDR }, + { GE_CMD_CLUTADDR, "clutaddrlow", GECmdFormat::LOW_ADDR }, { GE_CMD_CLUTADDRUPPER, "clutaddrhigh", GECmdFormat::HIGH_ADDR }, - { GE_CMD_TRANSFERSRC, "transfersrc", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERSRC, "transfersrclow", GECmdFormat::LOW_ADDR }, { GE_CMD_TRANSFERSRCW, "transfersrcstride", GECmdFormat::STRIDE_HIGH_ADDR }, - { GE_CMD_TRANSFERDST, "transferdst", GECmdFormat::LOW_ADDR }, + { GE_CMD_TRANSFERDST, "transferdstlow", GECmdFormat::LOW_ADDR }, { GE_CMD_TRANSFERDSTW, "transferdststride", GECmdFormat::STRIDE_HIGH_ADDR }, { GE_CMD_UNKNOWN_B6, "unknownb6", GECmdFormat::NONE }, { GE_CMD_UNKNOWN_B7, "unknownb7", GECmdFormat::NONE }, From 55c70332a1edbfc39ecb26baf3a9829d533f28db Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 11:05:30 -0700 Subject: [PATCH 098/110] GE Debugger: Eval breakpoints as if register set. --- GPU/Debugger/Breakpoints.cpp | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/GPU/Debugger/Breakpoints.cpp b/GPU/Debugger/Breakpoints.cpp index 225b25799d..97fbca57ee 100644 --- a/GPU/Debugger/Breakpoints.cpp +++ b/GPU/Debugger/Breakpoints.cpp @@ -171,7 +171,24 @@ bool IsRenderTargetCmdBreakpoint(u32 op) { return false; } -static bool HitAddressBreakpoint(u32 pc) { +static bool HitBreakpointCond(BreakpointInfo &bp, u32 op) { + u8 cmd = op >> 24; + + // Temporarily set the value while running the breakpoint. + // It makes more intuitive sense for the referenced data to already be set. + // Note this won't perform actions, like matrix uploads. + u32 diff = gstate.cmdmem[cmd] ^ op; + gstate.cmdmem[cmd] ^= diff; + + u32 result = 1; + if (!GPUDebugExecExpression(gpuDebug, bp.expression, result)) + result = 0; + + gstate.cmdmem[cmd] ^= diff; + return result != 0; +} + +static bool HitAddressBreakpoint(u32 pc, u32 op) { if (breakPCsCount == 0) return false; @@ -181,10 +198,7 @@ static bool HitAddressBreakpoint(u32 pc) { return false; if (entry->second.isConditional) { - u32 result = 1; - if (!GPUDebugExecExpression(gpuDebug, breakPCs[pc].expression, result)) - return false; - return result != 0; + return HitBreakpointCond(entry->second, op); } return true; } @@ -196,17 +210,14 @@ static bool HitOpBreakpoint(u32 op) { if (breakCmdsInfo[cmd].isConditional) { std::lock_guard guard(breaksLock); - u32 result = 1; - if (!GPUDebugExecExpression(gpuDebug, breakCmdsInfo[cmd].expression, result)) - return false; - return result != 0; + return HitBreakpointCond(breakCmdsInfo[cmd], op); } return true; } bool IsBreakpoint(u32 pc, u32 op) { - if (HitAddressBreakpoint(pc) || HitOpBreakpoint(op)) { + if (HitAddressBreakpoint(pc, op) || HitOpBreakpoint(op)) { return true; } From d25602f01bf58f32973e024946d95ecd057828b7 Mon Sep 17 00:00:00 2001 From: LunaMoo Date: Sun, 11 Sep 2022 21:47:07 +0200 Subject: [PATCH 099/110] Add Rewrite to DrawSyncEatCycles hack, softlocks without it --- assets/compat.ini | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/assets/compat.ini b/assets/compat.ini index 63a4f168f7..3d2846d377 100644 --- a/assets/compat.ini +++ b/assets/compat.ini @@ -325,6 +325,11 @@ UCJS18036 = true UCAS40292 = true UCJS18053 = true +# Rewrite +# fixes softlocks, see #15904 +ULJM06364 = true +ULJM06365 = true + # Crash Tag Team Racing used to need it to pass checking memory stick screen. # ULES00168 = true # ULES00169 = true From 7d07e4e75df8a80e8be261a8f8fda82a5bd89700 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 13:09:03 -0700 Subject: [PATCH 100/110] GE Debugger: Add fields to register expressions. This means a conditional breakpoint can now use, for example, vtype.through == 1 to check the through mode flag. No constants, but this makes it easier to get right. Would be nice to have an autocomplete of the field names, of course... --- GPU/Common/GPUDebugInterface.cpp | 454 ++++++++++++++++++++++++++++++- GPU/Debugger/GECommandTable.h | 2 +- 2 files changed, 452 insertions(+), 4 deletions(-) diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index a058d6cbf6..34cb050ffd 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -50,6 +50,9 @@ enum class GEReferenceIndex : uint32_t { PROJ_MATRIX = 0x278, TGEN_MATRIX = 0x288, MATRIX_END = 0x294, + + FIELD_START = 0x1000, + FIELD_END = 0xFF000, }; ENUM_CLASS_BITOPS(GEReferenceIndex); @@ -81,6 +84,228 @@ static constexpr ReferenceName referenceNames[] = { { GEReferenceIndex::TEXADDR7, "texaddr7" }, }; +enum class GECmdField : uint8_t { + DATA, // Alias for the entire data. + LOW_FLAG, + LOW_U2, + LOW_U4, + LOW_U7, + LOW_U8, + LOW_U10, + LOW_U10_P1, + LOW_U11, + LOW_U16, + MID_U8, + MID_U10, // At 10, 10 bits. + MID_U10_P1, // At 10, 10 bits (add 1 to value.) + TOP_U8, + FLAG_AFTER_1, // At 1, 1 bit. + FLAG_AFTER_2, // At 2, 1 bit. + FLAG_AFTER_8, // At 8, 1 bit. + FLAG_AFTER_9, // At 9, 1 bit. + FLAG_AFTER_10, // At 10, 1 bit. + FLAG_AFTER_11, // At 11, 1 bit. + FLAG_AFTER_16, // At 16, 1 bit. + FLAG_AFTER_18, // At 18, 1 bit. + FLAG_AFTER_19, // At 19, 1 bit. + FLAG_AFTER_20, // At 20, 1 bit. + FLAG_AFTER_21, // At 21, 1 bit. + FLAG_AFTER_22, // At 22, 1 bit. + FLAG_AFTER_23, // At 23, 1 bit. + U2_AFTER_8, // At 8, 2 bits. + U3_AFTER_16, // At 16, 3 bits. + U12_AFTER_4, // At 4, 12 bits. + PRIM_TYPE, // At 16, 3 bits. + SPLINE_UTYPE, // At 16, 2 bits. + SPLINE_VTYPE, // At 18, 2 bits. + SIGNAL_TYPE, // At 16, 8 bits. + VTYPE_TC, // At 0, 2 bits. + VTYPE_COL, // At 2, 3 bits. + VTYPE_NRM, // At 5, 2 bits. + VTYPE_POS, // At 7, 2 bits. + VTYPE_WEIGHTTYPE, // At 9, 2 bits. + VTYPE_INDEX, // At 11, 2 bits. + VTYPE_WEIGHTCOUNT, // At 14, 3 bits. + VTYPE_MORPHCOUNT, // At 18, 3 bits. + PATCH_PRIM_TYPE, // At 0, 2 bits. + LIGHT_COMP, // At 0, 2 bits. + LIGHT_TYPE, // At 8, 2 bits. + LIGHT_TYPE_SPECULAR, // 1 if comp is 1 (but not 3.) + HIGH_ADDR, // At 16, 8 bits moved left to top 8 bits. + TEX_W, // At 0, 4 bits - 1 to this power. + TEX_H, // At 8, 4 bits - 1 to this power. + UVGEN_TYPE, // At 0, 2 bits. + UVGEN_PROJ, // At 8, 2 bits. + TEX_FORMAT, // At 0, 4 bits. + TEX_MINFILTER, // At 0, 3 bits. + TEX_MAGFILTER, // At 8, 1 bit. + TEX_LEVEL_MODE, // At 0, 2 bits. + LOW_U12_4_FLOAT, // At 0, 12.4 converted to float. + HIGH_S4_4_FLOAT, // At 16, s.3.4 converted to float. + TEX_FUNC, // At 0, 3 bits. + CLUT_BYTES, // At 0, 6 bits, multiplied by 8. + CLUT_FORMAT, // At 0, 2 bits. + CLUT_SHIFT, // At 2, 5 bits. + CLUT_OFFSET, // At 16, 5 bits, multiplied by 16. + COMPARE_FUNC2, // At 0, 2 bits. + COMPARE_FUNC3, // At 0, 3 bits. + STENCIL_OP_AT_0, // At 0, 3 bits. + STENCIL_OP_AT_8, // At 8, 3 bits. + STENCIL_OP_AT_16, // At 16, 3 bits. + BLEND_SRC, // At 0, 4 bits. + BLEND_DST, // At 4, 4 bits. + BLEND_EQUATION, // At 8, 3 bits. + LOGIC_OP, // At 0, 4 bits. +}; + +struct FieldName { + GECmdFormat fmt; + GECmdField field; + const char *name; +}; + +static constexpr FieldName fieldNames[] = { + { GECmdFormat::PRIM, GECmdField::LOW_U16, "count" }, + { GECmdFormat::PRIM, GECmdField::PRIM_TYPE, "type" }, + { GECmdFormat::BEZIER, GECmdField::LOW_U8, "ucount" }, + { GECmdFormat::BEZIER, GECmdField::LOW_U8, "u" }, + { GECmdFormat::BEZIER, GECmdField::MID_U8, "vcount" }, + { GECmdFormat::BEZIER, GECmdField::MID_U8, "v" }, + { GECmdFormat::SPLINE, GECmdField::LOW_U8, "ucount" }, + { GECmdFormat::SPLINE, GECmdField::LOW_U8, "u" }, + { GECmdFormat::SPLINE, GECmdField::MID_U8, "vcount" }, + { GECmdFormat::SPLINE, GECmdField::MID_U8, "v" }, + { GECmdFormat::SPLINE, GECmdField::SPLINE_UTYPE, "utype" }, + { GECmdFormat::SPLINE, GECmdField::SPLINE_VTYPE, "vtype" }, + { GECmdFormat::SIGNAL, GECmdField::LOW_U16, "data" }, + { GECmdFormat::SIGNAL, GECmdField::SIGNAL_TYPE, "type" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_TC, "texcoord" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_TC, "tc" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_COL, "col" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_COL, "color" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_NRM, "normal" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_POS, "pos" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_POS, "position" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTTYPE, "weighttype" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTTYPE, "weight" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_INDEX, "index" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_WEIGHTCOUNT, "weightcount" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_MORPHCOUNT, "morphcount" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::FLAG_AFTER_23, "through" }, + { GECmdFormat::VERTEX_TYPE, GECmdField::FLAG_AFTER_23, "throughmode" }, + { GECmdFormat::X10_Y10, GECmdField::LOW_U10, "x" }, + { GECmdFormat::X10_Y10, GECmdField::MID_U10, "y" }, + { GECmdFormat::X10_Y10, GECmdField::LOW_U10_P1, "w" }, + { GECmdFormat::X10_Y10, GECmdField::MID_U10_P1, "h" }, + { GECmdFormat::FLAG, GECmdField::LOW_FLAG, "flag" }, + { GECmdFormat::BONE_NUM, GECmdField::LOW_U7, "num" }, + { GECmdFormat::MATRIX_NUM, GECmdField::LOW_U4, "num" }, + { GECmdFormat::FLOAT, GECmdField::DATA, "data" }, + { GECmdFormat::PATCH_DIVISION, GECmdField::LOW_U8, "u" }, + { GECmdFormat::PATCH_DIVISION, GECmdField::MID_U8, "v" }, + { GECmdFormat::PATCH_PRIM, GECmdField::PATCH_PRIM_TYPE, "type" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "frac" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "sub" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U4, "subpixels" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::U12_AFTER_4, "int" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::U12_AFTER_4, "integer" }, + { GECmdFormat::SUBPIXEL_COORD, GECmdField::LOW_U12_4_FLOAT, "pixels" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::LOW_FLAG, "ambient" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::FLAG_AFTER_1, "diffuse" }, + { GECmdFormat::MATERIAL_UPDATE, GECmdField::FLAG_AFTER_2, "specular" }, + { GECmdFormat::RGB, GECmdField::LOW_U8, "r" }, + { GECmdFormat::RGB, GECmdField::LOW_U8, "red" }, + { GECmdFormat::RGB, GECmdField::MID_U8, "g" }, + { GECmdFormat::RGB, GECmdField::MID_U8, "green" }, + { GECmdFormat::RGB, GECmdField::TOP_U8, "b" }, + { GECmdFormat::RGB, GECmdField::TOP_U8, "blue" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_COMP, "computation" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_TYPE, "type" }, + { GECmdFormat::LIGHT_TYPE, GECmdField::LIGHT_TYPE_SPECULAR, "specular" }, + { GECmdFormat::STRIDE, GECmdField::LOW_U11, "stride" }, + { GECmdFormat::STRIDE_HIGH_ADDR, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::HIGH_ADDR, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::HIGH_ADDR_ONLY, GECmdField::HIGH_ADDR, "highaddr" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_W, "w" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_W, "width" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_H, "h" }, + { GECmdFormat::TEX_SIZE, GECmdField::TEX_H, "height" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_TYPE, "type" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_TYPE, "uv" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_PROJ, "proj" }, + { GECmdFormat::TEX_MAP_MODE, GECmdField::UVGEN_PROJ, "factor" }, + { GECmdFormat::TEX_LIGHT_SRC, GECmdField::LOW_U2, "u" }, + { GECmdFormat::TEX_LIGHT_SRC, GECmdField::U2_AFTER_8, "v" }, + { GECmdFormat::TEX_MODE, GECmdField::LOW_FLAG, "swizzle" }, + { GECmdFormat::TEX_MODE, GECmdField::FLAG_AFTER_8, "separateclut" }, + { GECmdFormat::TEX_MODE, GECmdField::FLAG_AFTER_8, "separate" }, + { GECmdFormat::TEX_MODE, GECmdField::U3_AFTER_16, "maxlevel" }, + { GECmdFormat::TEX_MODE, GECmdField::U3_AFTER_16, "level" }, + { GECmdFormat::TEX_FORMAT, GECmdField::TEX_FORMAT, "format" }, + { GECmdFormat::TEX_FORMAT, GECmdField::TEX_FORMAT, "fmt" }, + { GECmdFormat::TEX_FORMAT, GECmdField::FLAG_AFTER_2, "indexed" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MINFILTER, "min" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MINFILTER, "minify" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MAGFILTER, "mag" }, + { GECmdFormat::TEX_FILTER, GECmdField::TEX_MAGFILTER, "magnify" }, + { GECmdFormat::TEX_CLAMP, GECmdField::LOW_FLAG, "s" }, + { GECmdFormat::TEX_CLAMP, GECmdField::FLAG_AFTER_8, "t" }, + { GECmdFormat::TEX_LEVEL_MODE, GECmdField::TEX_LEVEL_MODE, "mode" }, + { GECmdFormat::TEX_LEVEL_MODE, GECmdField::HIGH_S4_4_FLOAT, "bias" }, + { GECmdFormat::TEX_FUNC, GECmdField::TEX_FUNC, "func" }, + { GECmdFormat::TEX_FUNC, GECmdField::TEX_FUNC, "function" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_8, "alpha" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_8, "a" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_16, "double" }, + { GECmdFormat::TEX_FUNC, GECmdField::FLAG_AFTER_16, "doubling" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_FORMAT, "format" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_FORMAT, "fmt" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_SHIFT, "shift" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::MID_U8, "mask" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_OFFSET, "offset" }, + { GECmdFormat::CLUT_FORMAT, GECmdField::CLUT_OFFSET, "base" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "on" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "enable" }, + { GECmdFormat::CLEAR_MODE, GECmdField::LOW_FLAG, "flag" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_8, "color" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_9, "alpha" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_9, "stencil" }, + { GECmdFormat::CLEAR_MODE, GECmdField::FLAG_AFTER_10, "depth" }, + { GECmdFormat::COLOR_TEST_FUNC, GECmdField::COMPARE_FUNC2, "func" }, + { GECmdFormat::ALPHA_TEST, GECmdField::COMPARE_FUNC3, "func" }, + { GECmdFormat::ALPHA_TEST, GECmdField::MID_U8, "ref" }, + { GECmdFormat::ALPHA_TEST, GECmdField::MID_U8, "reference" }, + { GECmdFormat::ALPHA_TEST, GECmdField::TOP_U8, "mask" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_0, "sfail" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_8, "zfail" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_16, "zpass" }, + { GECmdFormat::STENCIL_OP, GECmdField::STENCIL_OP_AT_16, "pass" }, + { GECmdFormat::DEPTH_TEST_FUNC, GECmdField::COMPARE_FUNC3, "func" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_SRC, "src" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_SRC, "srcfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dst" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dstfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "dest" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_DST, "destfactor" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "eq" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "equation" }, + { GECmdFormat::BLEND_MODE, GECmdField::BLEND_EQUATION, "mode" }, + { GECmdFormat::LOGIC_OP, GECmdField::LOGIC_OP, "op" }, + { GECmdFormat::LOGIC_OP, GECmdField::LOGIC_OP, "mode" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::LOW_U8, "alpha" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::PRIM_TYPE, "type" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::PRIM_TYPE, "prim" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_11, "antialias" }, + // TODO: Clip bits? + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_18, "shading" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_18, "gouraud" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_19, "cull" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_20, "cullccw" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_21, "tex" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_22, "fog" }, + { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_23, "dither" }, +}; + class GEExpressionFunctions : public IExpressionFunctions { public: GEExpressionFunctions(GPUDebugInterface *gpu) : gpu_(gpu) {} @@ -92,6 +317,10 @@ public: bool getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) override; private: + bool parseFieldReference(const char *ref, const char *field, uint32_t &referenceIndex); + uint32_t getFieldValue(GECmdFormat fmt, GECmdField field, uint32_t value); + ExpressionType getFieldType(GECmdFormat fmt, GECmdField field); + GPUDebugInterface *gpu_; }; @@ -104,6 +333,15 @@ bool GEExpressionFunctions::parseReference(char *str, uint32_t &referenceIndex) return true; } + char *dot = strchr(str, '.'); + if (dot != nullptr) { + *dot = '\0'; + bool success = parseFieldReference(str, dot + 1, referenceIndex); + *dot = '.'; + if (success) + return true; + } + // Also allow non-register references. for (const auto &entry : referenceNames) { if (strcasecmp(str, entry.name) == 0) { @@ -150,6 +388,22 @@ bool GEExpressionFunctions::parseReference(char *str, uint32_t &referenceIndex) return false; } +bool GEExpressionFunctions::parseFieldReference(const char *ref, const char *field, uint32_t &referenceIndex) { + GECmdInfo info; + if (!GECmdInfoByName(ref, info)) { + return false; + } + + for (const auto &entry : fieldNames) { + if (entry.fmt == info.fmt && strcasecmp(field, entry.name) == 0) { + referenceIndex = (info.reg << 12) | (uint32_t)entry.field; + return true; + } + } + + return false; +} + bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { // Mainly useful for checking memory addresses. return g_symbolMap->GetLabelValue(str, symbolValue); @@ -158,11 +412,19 @@ bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { GPUgstate state = gpu_->GetGState(); if (referenceIndex < 0x100) { + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex)).fmt; uint32_t value = state.cmdmem[referenceIndex]; - // TODO: Later, support float values and similar. + if (fmt == GECmdFormat::FLOAT) + return value << 8; return value & 0x00FFFFFF; } + if (referenceIndex >= (uint32_t)GEReferenceIndex::FIELD_START && referenceIndex <= (uint32_t)GEReferenceIndex::FIELD_END) { + uint32_t value = state.cmdmem[referenceIndex >> 12] & 0x00FFFFFF; + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex >> 12)).fmt; + return getFieldValue(fmt, GECmdField(referenceIndex & 0xFF), value); + } + // We return the matrix value as float bits, which gets interpreted correctly in the parser. if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) { float value; @@ -209,7 +471,6 @@ uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { } return 0; case GEReferenceIndex::OP: - // TODO: Support fields under this as per the cmd format? if (gpu_->GetCurrentDisplayList(list)) { return Memory::Read_U32(list.pc); } @@ -245,6 +506,8 @@ uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { case GEReferenceIndex::PROJ_MATRIX: case GEReferenceIndex::TGEN_MATRIX: case GEReferenceIndex::MATRIX_END: + case GEReferenceIndex::FIELD_START: + case GEReferenceIndex::FIELD_END: // Shouldn't have gotten here. break; } @@ -253,17 +516,202 @@ uint32_t GEExpressionFunctions::getReferenceValue(uint32_t referenceIndex) { return 0; } +uint32_t GEExpressionFunctions::getFieldValue(GECmdFormat fmt, GECmdField field, uint32_t value) { + switch (field) { + case GECmdField::DATA: + return value; + case GECmdField::LOW_FLAG: + return value & 1; + case GECmdField::LOW_U2: + return value & 3; + case GECmdField::LOW_U4: + return value & 0xF; + case GECmdField::LOW_U7: + return value & 0x7F; + case GECmdField::LOW_U8: + return value & 0xFF; + case GECmdField::LOW_U10: + return value & 0x03FF; + case GECmdField::LOW_U10_P1: + return (value & 0x03FF) + 1; + case GECmdField::LOW_U11: + return value & 0x07FF; + case GECmdField::LOW_U16: + return value & 0xFFFF; + case GECmdField::MID_U8: + return (value >> 8) & 0xFF; + case GECmdField::MID_U10: + return (value >> 10) & 0x03FF; + case GECmdField::MID_U10_P1: + return ((value >> 10) & 0x03FF) + 1; + case GECmdField::TOP_U8: + return (value >> 16) & 0xFF; + case GECmdField::FLAG_AFTER_1: + return (value >> 1) & 1; + case GECmdField::FLAG_AFTER_2: + return (value >> 2) & 1; + case GECmdField::FLAG_AFTER_8: + return (value >> 8) & 1; + case GECmdField::FLAG_AFTER_9: + return (value >> 8) & 1; + case GECmdField::FLAG_AFTER_10: + return (value >> 10) & 1; + case GECmdField::FLAG_AFTER_11: + return (value >> 11) & 1; + case GECmdField::FLAG_AFTER_16: + return (value >> 16) & 1; + case GECmdField::FLAG_AFTER_18: + return (value >> 18) & 1; + case GECmdField::FLAG_AFTER_19: + return (value >> 19) & 1; + case GECmdField::FLAG_AFTER_20: + return (value >> 20) & 1; + case GECmdField::FLAG_AFTER_21: + return (value >> 21) & 1; + case GECmdField::FLAG_AFTER_22: + return (value >> 22) & 1; + case GECmdField::FLAG_AFTER_23: + return (value >> 23) & 1; + case GECmdField::U2_AFTER_8: + return (value >> 8) & 3; + case GECmdField::U3_AFTER_16: + return (value >> 16) & 7; + case GECmdField::U12_AFTER_4: + return (value >> 4) & 0x0FFF; + + // Below here are "typed" values, maybe they'll be exposed differently than integers someday. + + case GECmdField::PRIM_TYPE: + return (value >> 16) & 7; + case GECmdField::SPLINE_UTYPE: + return (value >> 16) & 3; + case GECmdField::SPLINE_VTYPE: + return (value >> 18) & 3; + case GECmdField::SIGNAL_TYPE: + return (value >> 16) & 0xFF; + case GECmdField::VTYPE_TC: + return value & 3; + case GECmdField::VTYPE_COL: + return (value >> 2) & 7; + case GECmdField::VTYPE_NRM: + return (value >> 5) & 3; + case GECmdField::VTYPE_POS: + return (value >> 7) & 3; + case GECmdField::VTYPE_WEIGHTTYPE: + return (value >> 9) & 3; + case GECmdField::VTYPE_INDEX: + return (value >> 11) & 3; + case GECmdField::VTYPE_WEIGHTCOUNT: + return ((value >> 14) & 7) + 1; + case GECmdField::VTYPE_MORPHCOUNT: + return ((value >> 18) & 7) + 1; + case GECmdField::PATCH_PRIM_TYPE: + return value & 3; + case GECmdField::LIGHT_COMP: + return value & 3; + case GECmdField::LIGHT_TYPE: + return (value >> 8) & 3; + case GECmdField::LIGHT_TYPE_SPECULAR: + return (value & 3) == 1; + case GECmdField::HIGH_ADDR: + return (value << 8) & 0xFF000000; + case GECmdField::TEX_W: + return 1 << (value & 0xF); + case GECmdField::TEX_H: + return 1 << ((value >> 8) & 0xF); + case GECmdField::UVGEN_TYPE: + return value & 3; + case GECmdField::UVGEN_PROJ: + return (value >> 8) & 3; + case GECmdField::TEX_FORMAT: + return value & 0xF; + case GECmdField::TEX_MINFILTER: + return value & 7; + case GECmdField::TEX_MAGFILTER: + return (value >> 8) & 1; + case GECmdField::TEX_LEVEL_MODE: + return value & 3; + case GECmdField::LOW_U12_4_FLOAT: + { + float f = (value & 0xFFFF) / 16.0f; + uint32_t result; + memcpy(&result, &f, sizeof(result)); + return result; + } + case GECmdField::HIGH_S4_4_FLOAT: // At 16, s.3.4 converted to float. + { + int value8 = (int)(s8)((value >> 16) & 0xFF); + float f = value8 / 16.0f; + uint32_t result; + memcpy(&result, &f, sizeof(result)); + return result; + } + case GECmdField::TEX_FUNC: + return value & 7; + case GECmdField::CLUT_BYTES: + return (value & 0x3F) * 8; + case GECmdField::CLUT_FORMAT: + return value & 3; + case GECmdField::CLUT_SHIFT: + return (value >> 2) & 0x1F; + case GECmdField::CLUT_OFFSET: + return ((value >> 16) & 0x1F) << 4; + case GECmdField::COMPARE_FUNC2: + return value & 3; + case GECmdField::COMPARE_FUNC3: + return value & 7; + case GECmdField::STENCIL_OP_AT_0: + return value & 7; + case GECmdField::STENCIL_OP_AT_8: + return (value >> 8) & 7; + case GECmdField::STENCIL_OP_AT_16: + return (value >> 16) & 7; + case GECmdField::BLEND_SRC: + return value & 0xF; + case GECmdField::BLEND_DST: + return (value >> 4) & 0xF; + case GECmdField::BLEND_EQUATION: + return (value >> 8) & 7; + case GECmdField::LOGIC_OP: + return value & 0xF; + } + + _assert_msg_(false, "Invalid field type"); + return 0; +} + ExpressionType GEExpressionFunctions::getReferenceType(uint32_t referenceIndex) { if (referenceIndex < 0x100) { - // TODO: Later, support float values and similar. + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex)).fmt; + if (fmt == GECmdFormat::FLOAT) + return EXPR_TYPE_FLOAT; return EXPR_TYPE_UINT; } + if (referenceIndex >= (uint32_t)GEReferenceIndex::FIELD_START && referenceIndex <= (uint32_t)GEReferenceIndex::FIELD_END) { + GECmdFormat fmt = GECmdInfoByCmd(GECommand(referenceIndex >> 12)).fmt; + return getFieldType(fmt, GECmdField(referenceIndex & 0xFF)); + } + if (referenceIndex >= (uint32_t)GEReferenceIndex::BONE_MATRIX && referenceIndex < (uint32_t)GEReferenceIndex::MATRIX_END) return EXPR_TYPE_FLOAT; return EXPR_TYPE_UINT; } +ExpressionType GEExpressionFunctions::getFieldType(GECmdFormat fmt, GECmdField field) { + switch (field) { + case GECmdField::LOW_U12_4_FLOAT: + case GECmdField::HIGH_S4_4_FLOAT: + return EXPR_TYPE_FLOAT; + + default: + // Almost all of these are uint, so not listing each one. + break; + } + + return EXPR_TYPE_UINT; +} + bool GEExpressionFunctions::getMemoryValue(uint32_t address, int size, uint32_t &dest, char *error) { if (!Memory::IsValidRange(address, size)) { sprintf(error, "Invalid address or size %08x + %d", address, size); diff --git a/GPU/Debugger/GECommandTable.h b/GPU/Debugger/GECommandTable.h index 95b4eddf0f..01d2059079 100644 --- a/GPU/Debugger/GECommandTable.h +++ b/GPU/Debugger/GECommandTable.h @@ -48,7 +48,7 @@ enum class GECmdFormat { STRIDE, // 11 bits. STRIDE_HIGH_ADDR, // 11 bits stride, 5 ignored, 8 bits high address. TEX_SIZE, // 4 bits width power, 4 bits ignored, 4 bits height power. - TEX_MAP_MODE, // 8 bits mode (2 bits), 2 bits environment factor. + TEX_MAP_MODE, // 8 bits mode (2 bits), 2 bits matrix factor. TEX_LIGHT_SRC, // 8 bits lightu (2 bits), 2 bits lightv. TEX_MODE, // 8 bits swizzle (1 bit), 8 bits separate clut4 (1 bit), 3 bits max level. TEX_FORMAT, // 4 bits format. From f02e6b8e399b34ec2392be6e454844a08243852d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 13:51:10 -0700 Subject: [PATCH 101/110] GE Debugger: Add some constants to expressions. Hard to remember, but at least can be copy/pasted. Allows for things like "alphatest.func == GREATER". --- GPU/Common/GPUDebugInterface.cpp | 221 +++++++++++++++++++++++++++++-- 1 file changed, 212 insertions(+), 9 deletions(-) diff --git a/GPU/Common/GPUDebugInterface.cpp b/GPU/Common/GPUDebugInterface.cpp index 34cb050ffd..1f7d04369e 100644 --- a/GPU/Common/GPUDebugInterface.cpp +++ b/GPU/Common/GPUDebugInterface.cpp @@ -106,6 +106,7 @@ enum class GECmdField : uint8_t { FLAG_AFTER_10, // At 10, 1 bit. FLAG_AFTER_11, // At 11, 1 bit. FLAG_AFTER_16, // At 16, 1 bit. + FLAG_AFTER_17, // At 17, 1 bit. FLAG_AFTER_18, // At 18, 1 bit. FLAG_AFTER_19, // At 19, 1 bit. FLAG_AFTER_20, // At 20, 1 bit. @@ -116,8 +117,6 @@ enum class GECmdField : uint8_t { U3_AFTER_16, // At 16, 3 bits. U12_AFTER_4, // At 4, 12 bits. PRIM_TYPE, // At 16, 3 bits. - SPLINE_UTYPE, // At 16, 2 bits. - SPLINE_VTYPE, // At 18, 2 bits. SIGNAL_TYPE, // At 16, 8 bits. VTYPE_TC, // At 0, 2 bits. VTYPE_COL, // At 2, 3 bits. @@ -175,8 +174,10 @@ static constexpr FieldName fieldNames[] = { { GECmdFormat::SPLINE, GECmdField::LOW_U8, "u" }, { GECmdFormat::SPLINE, GECmdField::MID_U8, "vcount" }, { GECmdFormat::SPLINE, GECmdField::MID_U8, "v" }, - { GECmdFormat::SPLINE, GECmdField::SPLINE_UTYPE, "utype" }, - { GECmdFormat::SPLINE, GECmdField::SPLINE_VTYPE, "vtype" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_16, "ufirstopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_17, "ulastopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_18, "vfirstopen" }, + { GECmdFormat::SPLINE, GECmdField::FLAG_AFTER_19, "vlastopen" }, { GECmdFormat::SIGNAL, GECmdField::LOW_U16, "data" }, { GECmdFormat::SIGNAL, GECmdField::SIGNAL_TYPE, "type" }, { GECmdFormat::VERTEX_TYPE, GECmdField::VTYPE_TC, "texcoord" }, @@ -306,6 +307,202 @@ static constexpr FieldName fieldNames[] = { { GECmdFormat::ALPHA_PRIM, GECmdField::FLAG_AFTER_23, "dither" }, }; +struct GECmdConstant { + const char *name; + uint32_t value; +}; + +// TODO: It would be nice if these were somehow typed... +static constexpr GECmdConstant constantNames[] = { + { "GE_PRIM_POINTS", GE_PRIM_POINTS }, + { "GE_PRIM_LINES", GE_PRIM_LINES }, + { "GE_PRIM_LINE_STRIP", GE_PRIM_LINE_STRIP }, + { "GE_PRIM_TRIANGLES", GE_PRIM_TRIANGLES }, + { "GE_PRIM_TRIANGLE_STRIP", GE_PRIM_TRIANGLE_STRIP }, + { "GE_PRIM_TRIANGLE_FAN", GE_PRIM_TRIANGLE_FAN }, + { "GE_PRIM_RECTANGLES", GE_PRIM_RECTANGLES }, + { "GE_PRIM_KEEP_PREVIOUS", GE_PRIM_KEEP_PREVIOUS }, + { "POINTS", GE_PRIM_POINTS }, + { "LINES", GE_PRIM_LINES }, + { "LINE_STRIP", GE_PRIM_LINE_STRIP }, + { "TRIANGLES", GE_PRIM_TRIANGLES }, + { "TRIANGLE_STRIP", GE_PRIM_TRIANGLE_STRIP }, + { "TRIANGLE_FAN", GE_PRIM_TRIANGLE_FAN }, + { "RECTANGLES", GE_PRIM_RECTANGLES }, + { "SPRITES", GE_PRIM_RECTANGLES }, + { "KEEP_PREVIOUS", GE_PRIM_KEEP_PREVIOUS }, + { "CONTINUE", GE_PRIM_KEEP_PREVIOUS }, + { "GE_PATCHPRIM_TRIANGLES", GE_PATCHPRIM_TRIANGLES, }, + { "GE_PATCHPRIM_LINES", GE_PATCHPRIM_LINES, }, + { "GE_PATCHPRIM_POINTS", GE_PATCHPRIM_POINTS, }, + { "GE_SIGNAL_NONE", PSP_GE_SIGNAL_NONE }, + { "GE_SIGNAL_HANDLER_SUSPEND", PSP_GE_SIGNAL_HANDLER_SUSPEND }, + { "GE_SIGNAL_HANDLER_CONTINUE", PSP_GE_SIGNAL_HANDLER_CONTINUE }, + { "GE_SIGNAL_HANDLER_PAUSE", PSP_GE_SIGNAL_HANDLER_PAUSE }, + { "GE_SIGNAL_SYNC", PSP_GE_SIGNAL_SYNC }, + { "GE_SIGNAL_JUMP", PSP_GE_SIGNAL_JUMP }, + { "GE_SIGNAL_CALL", PSP_GE_SIGNAL_CALL }, + { "GE_SIGNAL_RET", PSP_GE_SIGNAL_RET }, + { "GE_SIGNAL_RJUMP", PSP_GE_SIGNAL_RJUMP }, + { "GE_SIGNAL_RCALL", PSP_GE_SIGNAL_RCALL }, + { "GE_SIGNAL_OJUMP", PSP_GE_SIGNAL_OJUMP }, + { "GE_SIGNAL_OCALL", PSP_GE_SIGNAL_OCALL }, + { "GE_VTYPE_TC_NONE", GE_VTYPE_TC_NONE >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_8BIT", GE_VTYPE_TC_8BIT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_16BIT", GE_VTYPE_TC_16BIT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_TC_FLOAT", GE_VTYPE_TC_FLOAT >> GE_VTYPE_TC_SHIFT }, + { "GE_VTYPE_COL_NONE", GE_VTYPE_COL_NONE >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_565", GE_VTYPE_COL_565 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_5650", GE_VTYPE_COL_565 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_5551", GE_VTYPE_COL_5551 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_4444", GE_VTYPE_COL_4444 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_COL_8888", GE_VTYPE_COL_8888 >> GE_VTYPE_COL_SHIFT }, + { "GE_VTYPE_NRM_NONE", GE_VTYPE_NRM_NONE >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_8BIT", GE_VTYPE_NRM_8BIT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_16BIT", GE_VTYPE_NRM_16BIT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_NRM_FLOAT", GE_VTYPE_NRM_FLOAT >> GE_VTYPE_NRM_SHIFT }, + { "GE_VTYPE_POS_8BIT", GE_VTYPE_POS_8BIT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_POS_16BIT", GE_VTYPE_POS_16BIT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_POS_FLOAT", GE_VTYPE_POS_FLOAT >> GE_VTYPE_POS_SHIFT }, + { "GE_VTYPE_WEIGHT_NONE", GE_VTYPE_WEIGHT_NONE >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_8BIT", GE_VTYPE_WEIGHT_8BIT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_16BIT", GE_VTYPE_WEIGHT_16BIT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_WEIGHT_FLOAT", GE_VTYPE_WEIGHT_FLOAT >> GE_VTYPE_WEIGHT_SHIFT }, + { "GE_VTYPE_IDX_NONE", GE_VTYPE_IDX_NONE >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_8BIT", GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_16BIT", GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_VTYPE_IDX_32BIT", GE_VTYPE_IDX_32BIT >> GE_VTYPE_IDX_SHIFT }, + { "GE_LIGHTCOMP_ONLYDIFFUSE", GE_LIGHTCOMP_ONLYDIFFUSE }, + { "GE_LIGHTCOMP_BOTH", GE_LIGHTCOMP_BOTH }, + { "GE_LIGHTCOMP_ONLYPOWDIFFUSE", GE_LIGHTCOMP_ONLYPOWDIFFUSE }, + { "GE_LIGHTTYPE_DIRECTIONAL", GE_LIGHTTYPE_DIRECTIONAL }, + { "GE_LIGHTTYPE_POINT", GE_LIGHTTYPE_POINT }, + { "GE_LIGHTTYPE_SPOT", GE_LIGHTTYPE_SPOT }, + { "GE_TEXMAP_TEXTURE_COORDS", GE_TEXMAP_TEXTURE_COORDS }, + { "GE_TEXMAP_TEXTURE_MATRIX", GE_TEXMAP_TEXTURE_MATRIX }, + { "GE_TEXMAP_ENVIRONMENT_MAP", GE_TEXMAP_ENVIRONMENT_MAP }, + { "GE_PROJMAP_POSITION", GE_PROJMAP_POSITION }, + { "GE_PROJMAP_UV", GE_PROJMAP_UV }, + { "GE_PROJMAP_NORMALIZED_NORMAL", GE_PROJMAP_NORMALIZED_NORMAL }, + { "GE_PROJMAP_NORMAL", GE_PROJMAP_NORMAL }, + { "GE_TFMT_565", GE_TFMT_5650 }, + { "GE_TFMT_5650", GE_TFMT_5650 }, + { "GE_TFMT_5551", GE_TFMT_5551 }, + { "GE_TFMT_4444", GE_TFMT_4444 }, + { "GE_TFMT_8888", GE_TFMT_8888 }, + { "GE_TFMT_CLUT4", GE_TFMT_CLUT4 }, + { "GE_TFMT_CLUT8", GE_TFMT_CLUT8 }, + { "GE_TFMT_CLUT16", GE_TFMT_CLUT16 }, + { "GE_TFMT_CLUT32", GE_TFMT_CLUT32 }, + { "GE_TFMT_DXT1", GE_TFMT_DXT1 }, + { "GE_TFMT_DXT3", GE_TFMT_DXT3 }, + { "GE_TFMT_DXT5", GE_TFMT_DXT5 }, + { "GE_CMODE_16BIT_BGR5650", GE_CMODE_16BIT_BGR5650 }, + { "GE_CMODE_16BIT_ABGR5551", GE_CMODE_16BIT_ABGR5551 }, + { "GE_CMODE_16BIT_ABGR4444", GE_CMODE_16BIT_ABGR4444 }, + { "GE_CMODE_32BIT_ABGR8888", GE_CMODE_32BIT_ABGR8888 }, + { "GE_TFILT_NEAREST", GE_TFILT_NEAREST }, + { "GE_TFILT_LINEAR", GE_TFILT_LINEAR }, + { "GE_TFILT_NEAREST_MIPMAP_NEAREST", GE_TFILT_NEAREST_MIPMAP_NEAREST }, + { "GE_TFILT_LINEAR_MIPMAP_NEAREST", GE_TFILT_LINEAR_MIPMAP_NEAREST }, + { "GE_TFILT_NEAREST_MIPMAP_LINEAR", GE_TFILT_NEAREST_MIPMAP_LINEAR }, + { "GE_TFILT_LINEAR_MIPMAP_LINEAR", GE_TFILT_LINEAR_MIPMAP_LINEAR }, + { "NEAREST", GE_TFILT_NEAREST }, + { "LINEAR", GE_TFILT_LINEAR }, + { "GE_TEXLEVEL_MODE_AUTO", GE_TEXLEVEL_MODE_AUTO }, + { "GE_TEXLEVEL_MODE_CONST", GE_TEXLEVEL_MODE_CONST }, + { "GE_TEXLEVEL_MODE_SLOPE", GE_TEXLEVEL_MODE_SLOPE }, + { "GE_TEXFUNC_MODULATE", GE_TEXFUNC_MODULATE }, + { "GE_TEXFUNC_DECAL", GE_TEXFUNC_DECAL }, + { "GE_TEXFUNC_BLEND", GE_TEXFUNC_BLEND }, + { "GE_TEXFUNC_REPLACE", GE_TEXFUNC_REPLACE }, + { "GE_TEXFUNC_ADD", GE_TEXFUNC_ADD }, + { "GE_COMP_NEVER", GE_COMP_NEVER }, + { "GE_COMP_ALWAYS", GE_COMP_ALWAYS }, + { "GE_COMP_EQUAL", GE_COMP_EQUAL }, + { "GE_COMP_NOTEQUAL", GE_COMP_NOTEQUAL }, + { "GE_COMP_LESS", GE_COMP_LESS }, + { "GE_COMP_LEQUAL", GE_COMP_LEQUAL }, + { "GE_COMP_GREATER", GE_COMP_GREATER }, + { "GE_COMP_GEQUAL", GE_COMP_GEQUAL }, + { "NEVER", GE_COMP_NEVER }, + { "ALWAYS", GE_COMP_ALWAYS }, + { "EQUAL", GE_COMP_EQUAL }, + { "NOTEQUAL", GE_COMP_NOTEQUAL }, + { "LESS", GE_COMP_LESS }, + { "LEQUAL", GE_COMP_LEQUAL }, + { "LESSEQUAL", GE_COMP_LEQUAL }, + { "GREATER", GE_COMP_GREATER }, + { "GEQUAL", GE_COMP_GEQUAL }, + { "GREATEREQUAL", GE_COMP_GEQUAL }, + { "GE_STENCILOP_KEEP", GE_STENCILOP_KEEP }, + { "GE_STENCILOP_ZERO", GE_STENCILOP_ZERO }, + { "GE_STENCILOP_REPLACE", GE_STENCILOP_REPLACE }, + { "GE_STENCILOP_INVERT", GE_STENCILOP_INVERT }, + { "GE_STENCILOP_INCR", GE_STENCILOP_INCR }, + { "GE_STENCILOP_DECR", GE_STENCILOP_DECR }, + { "GE_BLENDMODE_MUL_AND_ADD", GE_BLENDMODE_MUL_AND_ADD }, + { "GE_BLENDMODE_MUL_AND_SUBTRACT", GE_BLENDMODE_MUL_AND_SUBTRACT }, + { "GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE", GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE }, + { "GE_BLENDMODE_MIN", GE_BLENDMODE_MIN }, + { "GE_BLENDMODE_MAX", GE_BLENDMODE_MAX }, + { "GE_BLENDMODE_ABSDIFF", GE_BLENDMODE_ABSDIFF }, + { "ADD", GE_BLENDMODE_MUL_AND_ADD }, + { "SUBTRACT", GE_BLENDMODE_MUL_AND_SUBTRACT }, + { "SUBTRACT_REVERSE", GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE }, + { "MIN", GE_BLENDMODE_MIN }, + { "MAX", GE_BLENDMODE_MAX }, + { "ABSDIFF", GE_BLENDMODE_ABSDIFF }, + { "GE_SRCBLEND_DSTCOLOR", GE_SRCBLEND_DSTCOLOR }, + { "GE_SRCBLEND_INVDSTCOLOR", GE_SRCBLEND_INVDSTCOLOR }, + { "GE_SRCBLEND_SRCALPHA", GE_SRCBLEND_SRCALPHA }, + { "GE_SRCBLEND_INVSRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "GE_SRCBLEND_DSTALPHA", GE_SRCBLEND_DSTALPHA }, + { "GE_SRCBLEND_INVDSTALPHA", GE_SRCBLEND_INVDSTALPHA }, + { "GE_SRCBLEND_DOUBLESRCALPHA", GE_SRCBLEND_DOUBLESRCALPHA }, + { "GE_SRCBLEND_DOUBLEINVSRCALPHA", GE_SRCBLEND_DOUBLEINVSRCALPHA }, + { "GE_SRCBLEND_DOUBLEDSTALPHA", GE_SRCBLEND_DOUBLEDSTALPHA }, + { "GE_SRCBLEND_DOUBLEINVDSTALPHA", GE_SRCBLEND_DOUBLEINVDSTALPHA }, + { "GE_SRCBLEND_FIXA", GE_SRCBLEND_FIXA }, + { "GE_DSTBLEND_SRCCOLOR", GE_DSTBLEND_SRCCOLOR }, + { "GE_DSTBLEND_INVSRCCOLOR", GE_DSTBLEND_INVSRCCOLOR }, + { "GE_DSTBLEND_SRCALPHA", GE_DSTBLEND_SRCALPHA }, + { "GE_DSTBLEND_INVSRCALPHA", GE_DSTBLEND_INVSRCALPHA }, + { "GE_DSTBLEND_DSTALPHA", GE_DSTBLEND_DSTALPHA }, + { "GE_DSTBLEND_INVDSTALPHA", GE_DSTBLEND_INVDSTALPHA }, + { "GE_DSTBLEND_DOUBLESRCALPHA", GE_DSTBLEND_DOUBLESRCALPHA }, + { "GE_DSTBLEND_DOUBLEINVSRCALPHA", GE_DSTBLEND_DOUBLEINVSRCALPHA }, + { "GE_DSTBLEND_DOUBLEDSTALPHA", GE_DSTBLEND_DOUBLEDSTALPHA }, + { "GE_DSTBLEND_DOUBLEINVDSTALPHA", GE_DSTBLEND_DOUBLEINVDSTALPHA }, + { "GE_DSTBLEND_FIXB", GE_DSTBLEND_FIXB }, + { "SRCALPHA", GE_SRCBLEND_SRCALPHA }, + { "INVSRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "INVERSESRCALPHA", GE_SRCBLEND_INVSRCALPHA }, + { "DSTALPHA", GE_DSTBLEND_DSTALPHA }, + { "INVDSTALPHA", GE_DSTBLEND_INVDSTALPHA }, + { "DOUBLESRCALPHA", GE_DSTBLEND_DOUBLESRCALPHA }, + { "DOUBLEINVSRCALPHA", GE_DSTBLEND_DOUBLEINVSRCALPHA }, + { "DOUBLEDSTALPHA", GE_DSTBLEND_DOUBLEDSTALPHA }, + { "DOUBLEINVDSTALPHA", GE_DSTBLEND_DOUBLEINVDSTALPHA }, + { "FIXED", GE_DSTBLEND_FIXB }, + { "GE_LOGIC_CLEAR", GE_LOGIC_CLEAR }, + { "GE_LOGIC_AND", GE_LOGIC_AND }, + { "GE_LOGIC_AND_REVERSE", GE_LOGIC_AND_REVERSE }, + { "GE_LOGIC_COPY", GE_LOGIC_COPY }, + { "GE_LOGIC_AND_INVERTED", GE_LOGIC_AND_INVERTED }, + { "GE_LOGIC_NOOP", GE_LOGIC_NOOP }, + { "GE_LOGIC_XOR", GE_LOGIC_XOR }, + { "GE_LOGIC_OR", GE_LOGIC_OR }, + { "GE_LOGIC_NOR", GE_LOGIC_NOR }, + { "GE_LOGIC_EQUIV", GE_LOGIC_EQUIV }, + { "GE_LOGIC_INVERTED", GE_LOGIC_INVERTED }, + { "GE_LOGIC_OR_REVERSE", GE_LOGIC_OR_REVERSE }, + { "GE_LOGIC_COPY_INVERTED", GE_LOGIC_COPY_INVERTED }, + { "GE_LOGIC_OR_INVERTED", GE_LOGIC_OR_INVERTED }, + { "GE_LOGIC_NAND", GE_LOGIC_NAND }, + { "GE_LOGIC_SET", GE_LOGIC_SET }, +}; + class GEExpressionFunctions : public IExpressionFunctions { public: GEExpressionFunctions(GPUDebugInterface *gpu) : gpu_(gpu) {} @@ -405,7 +602,15 @@ bool GEExpressionFunctions::parseFieldReference(const char *ref, const char *fie } bool GEExpressionFunctions::parseSymbol(char *str, uint32_t &symbolValue) { - // Mainly useful for checking memory addresses. + // Mainly useful for checking memory addresses and constants. + + for (const auto &entry : constantNames) { + if (strcasecmp(str, entry.name) == 0) { + symbolValue = entry.value; + return true; + } + } + return g_symbolMap->GetLabelValue(str, symbolValue); } @@ -560,6 +765,8 @@ uint32_t GEExpressionFunctions::getFieldValue(GECmdFormat fmt, GECmdField field, return (value >> 11) & 1; case GECmdField::FLAG_AFTER_16: return (value >> 16) & 1; + case GECmdField::FLAG_AFTER_17: + return (value >> 17) & 1; case GECmdField::FLAG_AFTER_18: return (value >> 18) & 1; case GECmdField::FLAG_AFTER_19: @@ -583,10 +790,6 @@ uint32_t GEExpressionFunctions::getFieldValue(GECmdFormat fmt, GECmdField field, case GECmdField::PRIM_TYPE: return (value >> 16) & 7; - case GECmdField::SPLINE_UTYPE: - return (value >> 16) & 3; - case GECmdField::SPLINE_VTYPE: - return (value >> 18) & 3; case GECmdField::SIGNAL_TYPE: return (value >> 16) & 0xFF; case GECmdField::VTYPE_TC: From 41c6c81eadead4c747cee3bd8eb60d250ad8d054 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 14:38:27 -0700 Subject: [PATCH 102/110] README: Move some older releases to history. --- README.md | 218 ---------------------------------------------------- history.md | 219 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 218 insertions(+), 219 deletions(-) diff --git a/README.md b/README.md index fbf49d359a..8a9a7bc744 100644 --- a/README.md +++ b/README.md @@ -166,110 +166,6 @@ Adhoc/Network: * Reduce HLE delays due to multiplayer performance regressions (ie. Ys vs. Sora no Kiseki) ([#14513]) * Fix socket error 10014 on Windows when hosting a game of Vulcanus Seek and Destroy ([#14849]) -What's new in 1.11.3 -==================== -* Fix for graphics glitches in the on-screen keyboard - -What's new in 1.11.2 -==================== -* An additional few crash fixes ([#14129], [#14134], [#14132]) - -What's new in 1.11.1 -==================== -* A few crash fixes ([#14085], [#14089], [#14091], [#14092]), a few adhoc fixes -* Glitchy menu audio on some devices ([#14101]), in-game UI font memory leak ([#14078]) -* Couple of adhoc fixes ([#14106], [#14117]) - -What's new in 1.11.0 -==================== -* Lots of minor bug fixes, crash fixes, and performance fixes and improvements. -* New Browse... button to allow opening SD cards on Android 11 -* Countless AdHoc networking fixes by ANR2ME, for example Dragon Ball Shin Budokai, PowerStone, - Bleach Heat The Soul 7, Kingdom Hearts, GTA: VCS and many more. -* Graphics issue with car reflections fixed in Outrun, Dirt 2 ([#13636], [#13640], [#13760]) -* Cut-off cards in Yu Gi Oh fixed ([#7124]). -* Numerous fixes to the builtin fonts by nassau-tk -* Added exception handler so PPSSPP stays alive if a game crashes ([#11795]/[#13092]) -* Desktop: Support for multiple instance multiplayer ([#13172], ...) -* Workaround for rendering bugs with flat shading in iOS 14 -* Multiple fixes to the IR interpreter ([#13897], ...) -* UI: New fullscreen button on desktop platforms, optional navigation sounds ([#13239]) -* Audio and multiple hangs fixes in UWP version ([#13792], ...) -* Partial microphone support ([#12336], ...) -* Workaround for wacky action mirroring bug in Hitman Reborn Battle Arena 2 ([#13706], [#13526]) -* Hardware texture upscaling for Vulkan, mipmap generation ([#13235], [#13514]) -* Added MMPX Vulkan texture upscaling shader ([#13986]) -* Depth texturing support in Vulkan and D3D11 ([#13262], [#13556], ...) -* Performance fix for Test Drive Unlimited ([#13355], ...) -* Allow rewind on mobile ([#13866]) -* Added option to disable on-screen messages ([#13695]) -* Added "Lower resolution for effects" on libretro ([#13654]) -* Allow chaining multiple post-processing shaders ([#12924]) -* Support for loading game-specific plugins ([#13335]) -* Fixed Assassin's Creed: Bloodlines Save issue on Android ([#12761]) -* Hanayaka Nari Wa ga Ichizoku: mono voices fixed ([#5213]) -* Additional fixed games: - * Namco Museum - Battle Collection, Vol 2 ([#9523], [#13297], [#13298]) - * Dream Club Portable (graphics bugs, GL and Vulkan) ([#6025]) - * Capcom Classic Collection Reloaded (stuck in return game) ([#4671]) - * Xyanide Resurrection (freezing) ([#8526]) - * Dissidia Final Fantasy Chinese (patched game, invalid address) ([#13204]) - * Crazy Taxi ([#13368]) - * Spiderman: Friend or Foe ([#13969]) - * Downstream Panic (US) (New Game crash) ([#13633]) - -What's new in 1.10.3 --------------------- -* Fix for control layout editor ([#13125]) - -What's new in 1.10.2 --------------------- -* More crashfixes ([#13094], [#13093]) -* Improve download performance and cancel behavior ([#13095]) -* Restore the removed I/O on Thread option ([#13096]) - -What's new in 1.10.1 --------------------- -* Fixes for common crashes ([#13077], [#13076], see [#13057]) -* Fix for offset rendering in D3D9 ([#13071]) - -What's new in 1.10.0 --------------------- -* Graphics and compatibility fixes ([#12800], [#12670], [#12635], [#12857], [#12941], [#11898], [#12695], more) -* Assorted minor performance improvements, game load speedup ([#12462], [#12652]) -* Screen inset (notch) support on Android ([#12779]) -* Analog stick support for menu navigation ([#12685]) -* Fixed audio glitches in SDL builds ([#12916], [#12920]) -* Support more languages in in-game dialogs ([#12702]). Croatian language added to PPSSPP. -* Simple multiplayer chat ([#12667]) -* More advanced postprocessing (multipass, parameters) ([#12905], [#12901]) -* Add PPSSPP-specific CWCheat ([#12816], [#12912]) -* Reintroduce Cardboard VR, allow more resolutions ([#12449], [#8714]) -* Fix some crashes ([#12908], [#12876]) -* Ghost in the Shell graphics fixed (JIT inaccuracy with inf * 0) ([#12519]) -* Mac build now supports Vulkan on top of MoltenVK ([#12583]) -* Raspberry Pi 4 EGL crash fixed ([#12474]) -* VSync now supported on all backends, frame duplication option added for 30 Hz games ([#12659], [#12602]) -* Camera supported on Windows, Linux and Mac (still no microphone though) ([#12572], [#12580], [#12607]) -* Darkstalkers fixed and working through software rendering. SW rendering fixed on GLES 2.0 ([#12443], [#12898]) -* Hot Shots Golf slowdown and flicker on Vulkan fixed ([#12873], [#12746]) -* Pangya Golf crashes and hangs fixed ([#12718]) -* Allow rebinding of right touch screen analog ([#12486]) -* Add option to prevent mipmaps from being dumped ([#12818]) -* Tilt control now have a base radius to help with deadzone ([#12756]) -* Mappable auto rotating analog stick to pass some game checks ([#12749]) -* Touch control position can now be snapped to a grid ([#12517]) -* HiDPI retina display support ([#12552]) -* Rapid-fire on touch control ([#12601]) -* Toggle mute button ([#12643]) -* Add option to resize game icons and more ([#12646], [#12637]) -* Frames in-flight now configurable to reduce input lag at the cost of speed ([#12660]) -* Add toggle mode to combo button ([#12623]) -* SDL mouse support, Qt menu upgrades ([#12612], [#12817]) -* Real support for Chinese patched version of Hatsune Miku Project Diva Extend ([#13007]) -* Some minor kernel module support ([#13028], [#12225], [#13026], [#13004], [#13038], [#13023]) -* Fixed fullscreen toggling with Vulkan in SDL builds ([#11974]) - Looking for [older news](history.md)? @@ -287,120 +183,6 @@ Credit goes to: [comment]: # (LINK_LIST_BEGIN_HERE) -[#13125]: https://github.com/hrydgard/ppsspp/issues/13125 "Refactor and fix touch control layout screen for notch" -[#13094]: https://github.com/hrydgard/ppsspp/issues/13094 "Camera initialization crash fix" -[#13093]: https://github.com/hrydgard/ppsspp/issues/13093 "Add a try/catch to Android camera device listing." -[#13095]: https://github.com/hrydgard/ppsspp/issues/13095 "http: Check cancel flag more often" -[#13096]: https://github.com/hrydgard/ppsspp/issues/13096 "Revert \"Remove the I/O on Thread option - treat it as always on.\"" -[#13077]: https://github.com/hrydgard/ppsspp/issues/13077 "SaveState: Make sure to default init net data" -[#13076]: https://github.com/hrydgard/ppsspp/issues/13076 "Add some excessive null checks to GameScreen::render()" -[#13057]: https://github.com/hrydgard/ppsspp/issues/13057 "The 1.10 Android mystery crash thread!" -[#13071]: https://github.com/hrydgard/ppsspp/issues/13071 "D3D9: Fix a sign mistake generating the projection matrix." -[#12800]: https://github.com/hrydgard/ppsspp/issues/12800 "x86jit: Force INF * 0 to +NAN" -[#12670]: https://github.com/hrydgard/ppsspp/issues/12670 "Attempts to replace 0 frame width with valid frame width.(sceMpegAvcCsc)" -[#12635]: https://github.com/hrydgard/ppsspp/issues/12635 "Kernel: Delay better in sceKernelReferThreadStatus" -[#12857]: https://github.com/hrydgard/ppsspp/issues/12857 "Mumbo Jumbo games freeze on loading screen since v1.6" -[#12941]: https://github.com/hrydgard/ppsspp/issues/12941 "Vulkan: Deal with the reformat clear better" -[#11898]: https://github.com/hrydgard/ppsspp/issues/11898 "Strike Witches - Hakugin no Tsubasa missing intro video" -[#12695]: https://github.com/hrydgard/ppsspp/issues/12695 "New heuristic for getting rid of unnecessary \"antialias-lines\"." -[#12462]: https://github.com/hrydgard/ppsspp/issues/12462 "Vulkan: Enable renderpass merging for all games" -[#12652]: https://github.com/hrydgard/ppsspp/issues/12652 "ScanForFunctions: Speed up game loading" -[#12779]: https://github.com/hrydgard/ppsspp/issues/12779 "Support drawing around notches on Android displays. Fixes #12261" -[#12685]: https://github.com/hrydgard/ppsspp/issues/12685 "UI: Simple joystick navigation. Fixes #10996." -[#12916]: https://github.com/hrydgard/ppsspp/issues/12916 "More audio buffering fixes (primarily affects SDL)" -[#12920]: https://github.com/hrydgard/ppsspp/issues/12920 "Remove the Audio Resampling setting (now always on)." -[#12702]: https://github.com/hrydgard/ppsspp/issues/12702 "PPGe: Use TextDrawer for save UI if available" -[#12667]: https://github.com/hrydgard/ppsspp/issues/12667 "Chat feature based on Adenovan's Rechat branch" -[#12905]: https://github.com/hrydgard/ppsspp/issues/12905 "Allow chained post-processing shaders" -[#12901]: https://github.com/hrydgard/ppsspp/issues/12901 "Post shader setting uniform" -[#12816]: https://github.com/hrydgard/ppsspp/issues/12816 "Implement Xinput vibration CWCheat (PPSSPP specific 0xA code type)" -[#12912]: https://github.com/hrydgard/ppsspp/issues/12912 "Add CWCHEAT for postprocessing" -[#12449]: https://github.com/hrydgard/ppsspp/issues/12449 "Reintroduce Cardboard VR" -[#8714]: https://github.com/hrydgard/ppsspp/issues/8714 "Allow > 5x PSP resolution for devices like iPad Pro 12.9" -[#12908]: https://github.com/hrydgard/ppsspp/issues/12908 "Fix \"Improved compatibility of sceGeListEnQueue: verify that stackDepth < 256\"" -[#12876]: https://github.com/hrydgard/ppsspp/issues/12876 "Windows: Add safety checks to WASAPI code" -[#12519]: https://github.com/hrydgard/ppsspp/issues/12519 "Ghost In The Shell - Stand Alone Complex (ULUS10020) - Black Textures and missing screens." -[#12583]: https://github.com/hrydgard/ppsspp/issues/12583 "macOS: Initial support for vulkan on macOS ( MoltenVK )" -[#12474]: https://github.com/hrydgard/ppsspp/issues/12474 "Egl bug on rpi4 with master mesa?" -[#12659]: https://github.com/hrydgard/ppsspp/issues/12659 "Support vsync in all hardware backends, support runtime update" -[#12602]: https://github.com/hrydgard/ppsspp/issues/12602 "Add option to improve frame pacing through duplicate frames if below 60hz." -[#12572]: https://github.com/hrydgard/ppsspp/issues/12572 "Add camera support for windows." -[#12580]: https://github.com/hrydgard/ppsspp/issues/12580 "Add camera support for linux (V4L2)" -[#12607]: https://github.com/hrydgard/ppsspp/issues/12607 "QT API for camera (Linux/macOS)" -[#12443]: https://github.com/hrydgard/ppsspp/issues/12443 "Darkstalkers Chronicle: Add specializations and speedhacks to get it kinda playable" -[#12898]: https://github.com/hrydgard/ppsspp/issues/12898 "[Android] [Mali GPU] [OpenGL] Lastest build blackscreen on buffered rendering mode" -[#12873]: https://github.com/hrydgard/ppsspp/issues/12873 "Vulkan: Framebuffer manager: Use an allocator for \"MakePixelTexture\" images." -[#12746]: https://github.com/hrydgard/ppsspp/issues/12746 "GPU: Assume a scissor of 481x273 is a mistake" -[#12718]: https://github.com/hrydgard/ppsspp/issues/12718 "Vpl: Correct allocation order when splitting block" -[#12486]: https://github.com/hrydgard/ppsspp/issues/12486 "Rebindable touch right analog" -[#12818]: https://github.com/hrydgard/ppsspp/issues/12818 "Add option to prevent Mipmaps from being dumped" -[#12756]: https://github.com/hrydgard/ppsspp/issues/12756 "Skip deadzone option on tilt" -[#12749]: https://github.com/hrydgard/ppsspp/issues/12749 "Auto rotating analog" -[#12517]: https://github.com/hrydgard/ppsspp/issues/12517 "Touch control grid snap" -[#12552]: https://github.com/hrydgard/ppsspp/issues/12552 "Qt/macOS: enable HiDPI ( retina display ) support" -[#12601]: https://github.com/hrydgard/ppsspp/issues/12601 "Add rapid fire to touch control" -[#12643]: https://github.com/hrydgard/ppsspp/issues/12643 "Toggle mute button" -[#12646]: https://github.com/hrydgard/ppsspp/issues/12646 "Resizable game icons" -[#12637]: https://github.com/hrydgard/ppsspp/issues/12637 "Region flag and game ID on game selection screen" -[#12660]: https://github.com/hrydgard/ppsspp/issues/12660 "GPU: Add setting to control inflight frame usage" -[#12623]: https://github.com/hrydgard/ppsspp/issues/12623 "Add toggle flag to combo button" -[#12612]: https://github.com/hrydgard/ppsspp/issues/12612 "SDL analog mouse input" -[#12817]: https://github.com/hrydgard/ppsspp/issues/12817 "Unification of the menu of Linux and Windows versions" -[#13007]: https://github.com/hrydgard/ppsspp/issues/13007 "Real support \"Hatsune Miku Project Diva Extend\" chinese patched version" -[#13028]: https://github.com/hrydgard/ppsspp/issues/13028 "Real support Code Geass: Lost Colors chinese patched version" -[#12225]: https://github.com/hrydgard/ppsspp/issues/12225 "Rebased: Wrap some SysMemForKernel's nids, fixing #7960" -[#13026]: https://github.com/hrydgard/ppsspp/issues/13026 "Add some ThreadManForKernel nids" -[#13004]: https://github.com/hrydgard/ppsspp/issues/13004 "Warp some ThreadManForKernel and sceKernelExitVSHKernel" -[#13038]: https://github.com/hrydgard/ppsspp/issues/13038 "Add sysclib_strncmp,sysclib_memmove" -[#13023]: https://github.com/hrydgard/ppsspp/issues/13023 "Add sysclib_strstr" -[#11974]: https://github.com/hrydgard/ppsspp/issues/11974 "[Linux] [Vulkan] Toggle fullscreen doesn't update display properly" -[#13636]: https://github.com/hrydgard/ppsspp/issues/13636 "Reinterpret framebuffer formats as needed. Outrun reflections partial fix" -[#13640]: https://github.com/hrydgard/ppsspp/issues/13640 "Fix car reflections in Outrun" -[#13760]: https://github.com/hrydgard/ppsspp/issues/13760 "Fix car lighting issues in DiRT 2." -[#7124]: https://github.com/hrydgard/ppsspp/issues/7124 "Yu-Gi-Oh! GX Tag Force Card summoning (card cut-off / cropped)" -[#11795]: https://github.com/hrydgard/ppsspp/issues/11795 "Exception handler - catch bad memory accesses" -[#13092]: https://github.com/hrydgard/ppsspp/issues/13092 "Bad memory access handling improvements" -[#13172]: https://github.com/hrydgard/ppsspp/issues/13172 "Generalized multi-instance" -[#13897]: https://github.com/hrydgard/ppsspp/issues/13897 "LittleBigPlanet - Game Not Loading, Blue Screen (iOS, Unplayable)" -[#13239]: https://github.com/hrydgard/ppsspp/issues/13239 "Add sound effects for PPSSPP interface navigation" -[#13792]: https://github.com/hrydgard/ppsspp/issues/13792 "Fix UWP audio and a hang bug" -[#12336]: https://github.com/hrydgard/ppsspp/issues/12336 "Microphone support" -[#13706]: https://github.com/hrydgard/ppsspp/issues/13706 "Add back the old implementation of vfpu_sin/cos/sincos." -[#13526]: https://github.com/hrydgard/ppsspp/issues/13526 "VFPU: Compute sines and cosines in double precision." -[#13235]: https://github.com/hrydgard/ppsspp/issues/13235 "Vulkan: Allow custom texture upscaling shaders" -[#13514]: https://github.com/hrydgard/ppsspp/issues/13514 "Vulkan: Automatically generate mipmaps for replaced/scaled textures" -[#13986]: https://github.com/hrydgard/ppsspp/issues/13986 "Vulkan: Add MMPX upscaling texture shader" -[#13355]: https://github.com/hrydgard/ppsspp/issues/13355 "Refactor framebuffer attachment. Fixes Test Drive Unlimited performance" -[#13866]: https://github.com/hrydgard/ppsspp/issues/13866 "SaveState: Allow rewind on mobile" -[#13695]: https://github.com/hrydgard/ppsspp/issues/13695 "Add developer setting \"Show on-screen messages\". Uncheck to hide them." -[#13654]: https://github.com/hrydgard/ppsspp/issues/13654 "Expose the \"Lower resolution for effects\" setting in libretro." -[#12924]: https://github.com/hrydgard/ppsspp/issues/12924 "Postprocessing: User chain support" -[#13335]: https://github.com/hrydgard/ppsspp/issues/13335 "Support for loading game-specific plugins" -[#12761]: https://github.com/hrydgard/ppsspp/issues/12761 "[Android][OpenGL&Vulkan][Save issue] Assassin's Creed : Bloodlines (ULJM05571)" -[#5213]: https://github.com/hrydgard/ppsspp/issues/5213 "Hanayaka Nari Wa ga Ichizoku strange MP3 mono voice" -[#9523]: https://github.com/hrydgard/ppsspp/issues/9523 "Namco Museum - Battle Collection - ULUS100035 loading problem" -[#13297]: https://github.com/hrydgard/ppsspp/issues/13297 "Namco Museum Vol. 2 - ULJS00047 infinite loading in some game" -[#13298]: https://github.com/hrydgard/ppsspp/issues/13298 "Fix sceKernelExitThread" -[#6025]: https://github.com/hrydgard/ppsspp/issues/6025 "Dream Club Portable crash after select girl" -[#4671]: https://github.com/hrydgard/ppsspp/issues/4671 "Capcom Classic Collection Reloaded stuck in return game" -[#8526]: https://github.com/hrydgard/ppsspp/issues/8526 "Xyanide Resurrection freezing" -[#13204]: https://github.com/hrydgard/ppsspp/issues/13204 "Dissidia Final Fantasy Chinese patch invalid address" -[#13368]: https://github.com/hrydgard/ppsspp/issues/13368 "Reschedule after resuming thread from suspend." -[#13969]: https://github.com/hrydgard/ppsspp/issues/13969 "Io: Don't allow async close while async busy" -[#13633]: https://github.com/hrydgard/ppsspp/issues/13633 "Downstream Panic (US) New Game crashes" -[#13262]: https://github.com/hrydgard/ppsspp/issues/13262 "Implement texturing from depth buffers (Vulkan only so far)" -[#13556]: https://github.com/hrydgard/ppsspp/issues/13556 "D3D11 depth texture support" -[#14085]: https://github.com/hrydgard/ppsspp/issues/14085 "Handle exec addr errors better - don't let IgnoreBadMemoryAccesses skip dispatcher exceptions" -[#14089]: https://github.com/hrydgard/ppsspp/issues/14089 "GL: Call CreateDeviceObjects *after* updating render_." -[#14091]: https://github.com/hrydgard/ppsspp/issues/14091 "Only allow sceMpegGetAvcAu warmup for God Eater Series" -[#14092]: https://github.com/hrydgard/ppsspp/issues/14092 "SaveState: Prevent crash on bad cookie marker" -[#14101]: https://github.com/hrydgard/ppsspp/issues/14101 "Menu audio glitchfix" -[#14078]: https://github.com/hrydgard/ppsspp/issues/14078 "PPGe: Decimate text images properly" -[#14106]: https://github.com/hrydgard/ppsspp/issues/14106 "[Adhoc] Fix frozen (0 FPS) issue on Kao Challengers and Asterix & Obelix XX" -[#14117]: https://github.com/hrydgard/ppsspp/issues/14117 "[Adhoc] Fix lob" -[#14129]: https://github.com/hrydgard/ppsspp/issues/14129 "GPU: Force reinterpret off without copy image" -[#14134]: https://github.com/hrydgard/ppsspp/issues/14134 "Android: Ensure shutdown waits for render" -[#14132]: https://github.com/hrydgard/ppsspp/issues/14132 "Io: Truncate reads/writes to valid memory" [#11997]: https://github.com/hrydgard/ppsspp/issues/11997 "Android 12 scoped storage hell" [#5099]: https://github.com/hrydgard/ppsspp/issues/5099 "IOS touch controls problems." [#14053]: https://github.com/hrydgard/ppsspp/issues/14053 "Toggle screenshot minor issue." diff --git a/history.md b/history.md index b40eaba158..2191439617 100644 --- a/history.md +++ b/history.md @@ -1,5 +1,109 @@ This is history moved out from README.md, which was getting a bit long. +What's new in 1.11.3 +==================== +* Fix for graphics glitches in the on-screen keyboard + +What's new in 1.11.2 +==================== +* An additional few crash fixes ([#14129], [#14134], [#14132]) + +What's new in 1.11.1 +==================== +* A few crash fixes ([#14085], [#14089], [#14091], [#14092]), a few adhoc fixes +* Glitchy menu audio on some devices ([#14101]), in-game UI font memory leak ([#14078]) +* Couple of adhoc fixes ([#14106], [#14117]) + +What's new in 1.11.0 +==================== +* Lots of minor bug fixes, crash fixes, and performance fixes and improvements. +* New Browse... button to allow opening SD cards on Android 11 +* Countless AdHoc networking fixes by ANR2ME, for example Dragon Ball Shin Budokai, PowerStone, + Bleach Heat The Soul 7, Kingdom Hearts, GTA: VCS and many more. +* Graphics issue with car reflections fixed in Outrun, Dirt 2 ([#13636], [#13640], [#13760]) +* Cut-off cards in Yu Gi Oh fixed ([#7124]). +* Numerous fixes to the builtin fonts by nassau-tk +* Added exception handler so PPSSPP stays alive if a game crashes ([#11795]/[#13092]) +* Desktop: Support for multiple instance multiplayer ([#13172], ...) +* Workaround for rendering bugs with flat shading in iOS 14 +* Multiple fixes to the IR interpreter ([#13897], ...) +* UI: New fullscreen button on desktop platforms, optional navigation sounds ([#13239]) +* Audio and multiple hangs fixes in UWP version ([#13792], ...) +* Partial microphone support ([#12336], ...) +* Workaround for wacky action mirroring bug in Hitman Reborn Battle Arena 2 ([#13706], [#13526]) +* Hardware texture upscaling for Vulkan, mipmap generation ([#13235], [#13514]) +* Added MMPX Vulkan texture upscaling shader ([#13986]) +* Depth texturing support in Vulkan and D3D11 ([#13262], [#13556], ...) +* Performance fix for Test Drive Unlimited ([#13355], ...) +* Allow rewind on mobile ([#13866]) +* Added option to disable on-screen messages ([#13695]) +* Added "Lower resolution for effects" on libretro ([#13654]) +* Allow chaining multiple post-processing shaders ([#12924]) +* Support for loading game-specific plugins ([#13335]) +* Fixed Assassin's Creed: Bloodlines Save issue on Android ([#12761]) +* Hanayaka Nari Wa ga Ichizoku: mono voices fixed ([#5213]) +* Additional fixed games: + * Namco Museum - Battle Collection, Vol 2 ([#9523], [#13297], [#13298]) + * Dream Club Portable (graphics bugs, GL and Vulkan) ([#6025]) + * Capcom Classic Collection Reloaded (stuck in return game) ([#4671]) + * Xyanide Resurrection (freezing) ([#8526]) + * Dissidia Final Fantasy Chinese (patched game, invalid address) ([#13204]) + * Crazy Taxi ([#13368]) + * Spiderman: Friend or Foe ([#13969]) + * Downstream Panic (US) (New Game crash) ([#13633]) + +What's new in 1.10.3 +-------------------- +* Fix for control layout editor ([#13125]) + +What's new in 1.10.2 +-------------------- +* More crashfixes ([#13094], [#13093]) +* Improve download performance and cancel behavior ([#13095]) +* Restore the removed I/O on Thread option ([#13096]) + +What's new in 1.10.1 +-------------------- +* Fixes for common crashes ([#13077], [#13076], see [#13057]) +* Fix for offset rendering in D3D9 ([#13071]) + +What's new in 1.10.0 +-------------------- +* Graphics and compatibility fixes ([#12800], [#12670], [#12635], [#12857], [#12941], [#11898], [#12695], more) +* Assorted minor performance improvements, game load speedup ([#12462], [#12652]) +* Screen inset (notch) support on Android ([#12779]) +* Analog stick support for menu navigation ([#12685]) +* Fixed audio glitches in SDL builds ([#12916], [#12920]) +* Support more languages in in-game dialogs ([#12702]). Croatian language added to PPSSPP. +* Simple multiplayer chat ([#12667]) +* More advanced postprocessing (multipass, parameters) ([#12905], [#12901]) +* Add PPSSPP-specific CWCheat ([#12816], [#12912]) +* Reintroduce Cardboard VR, allow more resolutions ([#12449], [#8714]) +* Fix some crashes ([#12908], [#12876]) +* Ghost in the Shell graphics fixed (JIT inaccuracy with inf * 0) ([#12519]) +* Mac build now supports Vulkan on top of MoltenVK ([#12583]) +* Raspberry Pi 4 EGL crash fixed ([#12474]) +* VSync now supported on all backends, frame duplication option added for 30 Hz games ([#12659], [#12602]) +* Camera supported on Windows, Linux and Mac (still no microphone though) ([#12572], [#12580], [#12607]) +* Darkstalkers fixed and working through software rendering. SW rendering fixed on GLES 2.0 ([#12443], [#12898]) +* Hot Shots Golf slowdown and flicker on Vulkan fixed ([#12873], [#12746]) +* Pangya Golf crashes and hangs fixed ([#12718]) +* Allow rebinding of right touch screen analog ([#12486]) +* Add option to prevent mipmaps from being dumped ([#12818]) +* Tilt control now have a base radius to help with deadzone ([#12756]) +* Mappable auto rotating analog stick to pass some game checks ([#12749]) +* Touch control position can now be snapped to a grid ([#12517]) +* HiDPI retina display support ([#12552]) +* Rapid-fire on touch control ([#12601]) +* Toggle mute button ([#12643]) +* Add option to resize game icons and more ([#12646], [#12637]) +* Frames in-flight now configurable to reduce input lag at the cost of speed ([#12660]) +* Add toggle mode to combo button ([#12623]) +* SDL mouse support, Qt menu upgrades ([#12612], [#12817]) +* Real support for Chinese patched version of Hatsune Miku Project Diva Extend ([#13007]) +* Some minor kernel module support ([#13028], [#12225], [#13026], [#13004], [#13038], [#13023]) +* Fixed fullscreen toggling with Vulkan in SDL builds ([#11974]) + What's new in 1.9.0/1.9.3 ------------------------- * Sizing/touch fixes on Android @@ -565,4 +669,117 @@ go to see there http://forums.ppsspp.org/showthread.php?tid=3595&pid=59241#pid59 [#11307]: https://github.com/hrydgard/ppsspp/issues/11307 "Enable Discord integration for Mac and Linux." [#10909]: https://github.com/hrydgard/ppsspp/issues/10909 "WebSocket based debugger interface" [#11447]: https://github.com/hrydgard/ppsspp/issues/11447 "Avoid calling any GL calls during shutdown on Android. Should help #11063" -[#11350]: https://github.com/hrydgard/ppsspp/issues/11350 "TexCache: Optimize DXT3/DXT5 decode to single pass" \ No newline at end of file +[#11350]: https://github.com/hrydgard/ppsspp/issues/11350 "TexCache: Optimize DXT3/DXT5 decode to single pass" +[#13023]: https://github.com/hrydgard/ppsspp/issues/13023 "Add sysclib_strstr" +[#13038]: https://github.com/hrydgard/ppsspp/issues/13038 "Add sysclib_strncmp,sysclib_memmove" +[#13004]: https://github.com/hrydgard/ppsspp/issues/13004 "Warp some ThreadManForKernel and sceKernelExitVSHKernel" +[#13026]: https://github.com/hrydgard/ppsspp/issues/13026 "Add some ThreadManForKernel nids" +[#12225]: https://github.com/hrydgard/ppsspp/issues/12225 "Rebased: Wrap some SysMemForKernel's nids, fixing #7960" +[#13028]: https://github.com/hrydgard/ppsspp/issues/13028 "Real support Code Geass: Lost Colors chinese patched version" +[#13007]: https://github.com/hrydgard/ppsspp/issues/13007 "Real support \"Hatsune Miku Project Diva Extend\" chinese patched version" +[#12817]: https://github.com/hrydgard/ppsspp/issues/12817 "Unification of the menu of Linux and Windows versions" +[#12612]: https://github.com/hrydgard/ppsspp/issues/12612 "SDL analog mouse input" +[#12623]: https://github.com/hrydgard/ppsspp/issues/12623 "Add toggle flag to combo button" +[#12660]: https://github.com/hrydgard/ppsspp/issues/12660 "GPU: Add setting to control inflight frame usage" +[#12637]: https://github.com/hrydgard/ppsspp/issues/12637 "Region flag and game ID on game selection screen" +[#12646]: https://github.com/hrydgard/ppsspp/issues/12646 "Resizable game icons" +[#12643]: https://github.com/hrydgard/ppsspp/issues/12643 "Toggle mute button" +[#12601]: https://github.com/hrydgard/ppsspp/issues/12601 "Add rapid fire to touch control" +[#12552]: https://github.com/hrydgard/ppsspp/issues/12552 "Qt/macOS: enable HiDPI ( retina display ) support" +[#12517]: https://github.com/hrydgard/ppsspp/issues/12517 "Touch control grid snap" +[#12749]: https://github.com/hrydgard/ppsspp/issues/12749 "Auto rotating analog" +[#12756]: https://github.com/hrydgard/ppsspp/issues/12756 "Skip deadzone option on tilt" +[#12818]: https://github.com/hrydgard/ppsspp/issues/12818 "Add option to prevent Mipmaps from being dumped" +[#12486]: https://github.com/hrydgard/ppsspp/issues/12486 "Rebindable touch right analog" +[#12718]: https://github.com/hrydgard/ppsspp/issues/12718 "Vpl: Correct allocation order when splitting block" +[#12746]: https://github.com/hrydgard/ppsspp/issues/12746 "GPU: Assume a scissor of 481x273 is a mistake" +[#12873]: https://github.com/hrydgard/ppsspp/issues/12873 "Vulkan: Framebuffer manager: Use an allocator for \"MakePixelTexture\" images." +[#12898]: https://github.com/hrydgard/ppsspp/issues/12898 "[Android] [Mali GPU] [OpenGL] Lastest build blackscreen on buffered rendering mode" +[#12443]: https://github.com/hrydgard/ppsspp/issues/12443 "Darkstalkers Chronicle: Add specializations and speedhacks to get it kinda playable" +[#12607]: https://github.com/hrydgard/ppsspp/issues/12607 "QT API for camera (Linux/macOS)" +[#12580]: https://github.com/hrydgard/ppsspp/issues/12580 "Add camera support for linux (V4L2)" +[#12572]: https://github.com/hrydgard/ppsspp/issues/12572 "Add camera support for windows." +[#12602]: https://github.com/hrydgard/ppsspp/issues/12602 "Add option to improve frame pacing through duplicate frames if below 60hz." +[#12659]: https://github.com/hrydgard/ppsspp/issues/12659 "Support vsync in all hardware backends, support runtime update" +[#12474]: https://github.com/hrydgard/ppsspp/issues/12474 "Egl bug on rpi4 with master mesa?" +[#12583]: https://github.com/hrydgard/ppsspp/issues/12583 "macOS: Initial support for vulkan on macOS ( MoltenVK )" +[#12519]: https://github.com/hrydgard/ppsspp/issues/12519 "Ghost In The Shell - Stand Alone Complex (ULUS10020) - Black Textures and missing screens." +[#12876]: https://github.com/hrydgard/ppsspp/issues/12876 "Windows: Add safety checks to WASAPI code" +[#12908]: https://github.com/hrydgard/ppsspp/issues/12908 "Fix \"Improved compatibility of sceGeListEnQueue: verify that stackDepth < 256\"" +[#8714]: https://github.com/hrydgard/ppsspp/issues/8714 "Allow > 5x PSP resolution for devices like iPad Pro 12.9" +[#12449]: https://github.com/hrydgard/ppsspp/issues/12449 "Reintroduce Cardboard VR" +[#12912]: https://github.com/hrydgard/ppsspp/issues/12912 "Add CWCHEAT for postprocessing" +[#12816]: https://github.com/hrydgard/ppsspp/issues/12816 "Implement Xinput vibration CWCheat (PPSSPP specific 0xA code type)" +[#12901]: https://github.com/hrydgard/ppsspp/issues/12901 "Post shader setting uniform" +[#12905]: https://github.com/hrydgard/ppsspp/issues/12905 "Allow chained post-processing shaders" +[#12667]: https://github.com/hrydgard/ppsspp/issues/12667 "Chat feature based on Adenovan's Rechat branch" +[#12702]: https://github.com/hrydgard/ppsspp/issues/12702 "PPGe: Use TextDrawer for save UI if available" +[#12920]: https://github.com/hrydgard/ppsspp/issues/12920 "Remove the Audio Resampling setting (now always on)." +[#12916]: https://github.com/hrydgard/ppsspp/issues/12916 "More audio buffering fixes (primarily affects SDL)" +[#12685]: https://github.com/hrydgard/ppsspp/issues/12685 "UI: Simple joystick navigation. Fixes #10996." +[#12779]: https://github.com/hrydgard/ppsspp/issues/12779 "Support drawing around notches on Android displays. Fixes #12261" +[#12652]: https://github.com/hrydgard/ppsspp/issues/12652 "ScanForFunctions: Speed up game loading" +[#12462]: https://github.com/hrydgard/ppsspp/issues/12462 "Vulkan: Enable renderpass merging for all games" +[#12695]: https://github.com/hrydgard/ppsspp/issues/12695 "New heuristic for getting rid of unnecessary \"antialias-lines\"." +[#11898]: https://github.com/hrydgard/ppsspp/issues/11898 "Strike Witches - Hakugin no Tsubasa missing intro video" +[#12941]: https://github.com/hrydgard/ppsspp/issues/12941 "Vulkan: Deal with the reformat clear better" +[#12857]: https://github.com/hrydgard/ppsspp/issues/12857 "Mumbo Jumbo games freeze on loading screen since v1.6" +[#12635]: https://github.com/hrydgard/ppsspp/issues/12635 "Kernel: Delay better in sceKernelReferThreadStatus" +[#12670]: https://github.com/hrydgard/ppsspp/issues/12670 "Attempts to replace 0 frame width with valid frame width.(sceMpegAvcCsc)" +[#12800]: https://github.com/hrydgard/ppsspp/issues/12800 "x86jit: Force INF * 0 to +NAN" +[#13071]: https://github.com/hrydgard/ppsspp/issues/13071 "D3D9: Fix a sign mistake generating the projection matrix." +[#13076]: https://github.com/hrydgard/ppsspp/issues/13076 "Add some excessive null checks to GameScreen::render()" +[#13057]: https://github.com/hrydgard/ppsspp/issues/13057 "The 1.10 Android mystery crash thread!" +[#13077]: https://github.com/hrydgard/ppsspp/issues/13077 "SaveState: Make sure to default init net data" +[#13096]: https://github.com/hrydgard/ppsspp/issues/13096 "Revert \"Remove the I/O on Thread option - treat it as always on.\"" +[#13095]: https://github.com/hrydgard/ppsspp/issues/13095 "http: Check cancel flag more often" +[#13093]: https://github.com/hrydgard/ppsspp/issues/13093 "Add a try/catch to Android camera device listing." +[#13094]: https://github.com/hrydgard/ppsspp/issues/13094 "Camera initialization crash fix" +[#13125]: https://github.com/hrydgard/ppsspp/issues/13125 "Refactor and fix touch control layout screen for notch" +[#13633]: https://github.com/hrydgard/ppsspp/issues/13633 "Downstream Panic (US) New Game crashes" +[#13969]: https://github.com/hrydgard/ppsspp/issues/13969 "Io: Don't allow async close while async busy" +[#13368]: https://github.com/hrydgard/ppsspp/issues/13368 "Reschedule after resuming thread from suspend." +[#13204]: https://github.com/hrydgard/ppsspp/issues/13204 "Dissidia Final Fantasy Chinese patch invalid address" +[#8526]: https://github.com/hrydgard/ppsspp/issues/8526 "Xyanide Resurrection freezing" +[#4671]: https://github.com/hrydgard/ppsspp/issues/4671 "Capcom Classic Collection Reloaded stuck in return game" +[#6025]: https://github.com/hrydgard/ppsspp/issues/6025 "Dream Club Portable crash after select girl" +[#13298]: https://github.com/hrydgard/ppsspp/issues/13298 "Fix sceKernelExitThread" +[#13297]: https://github.com/hrydgard/ppsspp/issues/13297 "Namco Museum Vol. 2 - ULJS00047 infinite loading in some game" +[#9523]: https://github.com/hrydgard/ppsspp/issues/9523 "Namco Museum - Battle Collection - ULUS100035 loading problem" +[#5213]: https://github.com/hrydgard/ppsspp/issues/5213 "Hanayaka Nari Wa ga Ichizoku strange MP3 mono voice" +[#12761]: https://github.com/hrydgard/ppsspp/issues/12761 "[Android][OpenGL&Vulkan][Save issue] Assassin's Creed : Bloodlines (ULJM05571)" +[#13335]: https://github.com/hrydgard/ppsspp/issues/13335 "Support for loading game-specific plugins" +[#12924]: https://github.com/hrydgard/ppsspp/issues/12924 "Postprocessing: User chain support" +[#13654]: https://github.com/hrydgard/ppsspp/issues/13654 "Expose the \"Lower resolution for effects\" setting in libretro." +[#13695]: https://github.com/hrydgard/ppsspp/issues/13695 "Add developer setting \"Show on-screen messages\". Uncheck to hide them." +[#13866]: https://github.com/hrydgard/ppsspp/issues/13866 "SaveState: Allow rewind on mobile" +[#13355]: https://github.com/hrydgard/ppsspp/issues/13355 "Refactor framebuffer attachment. Fixes Test Drive Unlimited performance" +[#13556]: https://github.com/hrydgard/ppsspp/issues/13556 "D3D11 depth texture support" +[#13262]: https://github.com/hrydgard/ppsspp/issues/13262 "Implement texturing from depth buffers (Vulkan only so far)" +[#13986]: https://github.com/hrydgard/ppsspp/issues/13986 "Vulkan: Add MMPX upscaling texture shader" +[#13514]: https://github.com/hrydgard/ppsspp/issues/13514 "Vulkan: Automatically generate mipmaps for replaced/scaled textures" +[#13235]: https://github.com/hrydgard/ppsspp/issues/13235 "Vulkan: Allow custom texture upscaling shaders" +[#13526]: https://github.com/hrydgard/ppsspp/issues/13526 "VFPU: Compute sines and cosines in double precision." +[#13706]: https://github.com/hrydgard/ppsspp/issues/13706 "Add back the old implementation of vfpu_sin/cos/sincos." +[#12336]: https://github.com/hrydgard/ppsspp/issues/12336 "Microphone support" +[#13792]: https://github.com/hrydgard/ppsspp/issues/13792 "Fix UWP audio and a hang bug" +[#13239]: https://github.com/hrydgard/ppsspp/issues/13239 "Add sound effects for PPSSPP interface navigation" +[#13897]: https://github.com/hrydgard/ppsspp/issues/13897 "LittleBigPlanet - Game Not Loading, Blue Screen (iOS, Unplayable)" +[#13172]: https://github.com/hrydgard/ppsspp/issues/13172 "Generalized multi-instance" +[#13092]: https://github.com/hrydgard/ppsspp/issues/13092 "Bad memory access handling improvements" +[#11795]: https://github.com/hrydgard/ppsspp/issues/11795 "Exception handler - catch bad memory accesses" +[#7124]: https://github.com/hrydgard/ppsspp/issues/7124 "Yu-Gi-Oh! GX Tag Force Card summoning (card cut-off / cropped)" +[#13760]: https://github.com/hrydgard/ppsspp/issues/13760 "Fix car lighting issues in DiRT 2." +[#13640]: https://github.com/hrydgard/ppsspp/issues/13640 "Fix car reflections in Outrun" +[#13636]: https://github.com/hrydgard/ppsspp/issues/13636 "Reinterpret framebuffer formats as needed. Outrun reflections partial fix" +[#14117]: https://github.com/hrydgard/ppsspp/issues/14117 "[Adhoc] Fix lob" +[#14106]: https://github.com/hrydgard/ppsspp/issues/14106 "[Adhoc] Fix frozen (0 FPS) issue on Kao Challengers and Asterix & Obelix XX" +[#14078]: https://github.com/hrydgard/ppsspp/issues/14078 "PPGe: Decimate text images properly" +[#14101]: https://github.com/hrydgard/ppsspp/issues/14101 "Menu audio glitchfix" +[#14092]: https://github.com/hrydgard/ppsspp/issues/14092 "SaveState: Prevent crash on bad cookie marker" +[#14091]: https://github.com/hrydgard/ppsspp/issues/14091 "Only allow sceMpegGetAvcAu warmup for God Eater Series" +[#14089]: https://github.com/hrydgard/ppsspp/issues/14089 "GL: Call CreateDeviceObjects *after* updating render_." +[#14085]: https://github.com/hrydgard/ppsspp/issues/14085 "Handle exec addr errors better - don't let IgnoreBadMemoryAccesses skip dispatcher exceptions" +[#14132]: https://github.com/hrydgard/ppsspp/issues/14132 "Io: Truncate reads/writes to valid memory" +[#14134]: https://github.com/hrydgard/ppsspp/issues/14134 "Android: Ensure shutdown waits for render" +[#14129]: https://github.com/hrydgard/ppsspp/issues/14129 "GPU: Force reinterpret off without copy image" From 5f2e20d8ca63fc60c3cbddebd8a1176cd511f734 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 18:39:14 -0700 Subject: [PATCH 103/110] softgpu: Reduce some minor bin item field sizes. --- GPU/Software/BinManager.cpp | 4 ++-- GPU/Software/BinManager.h | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GPU/Software/BinManager.cpp b/GPU/Software/BinManager.cpp index faaf7b03a8..9c1c1ff3ef 100644 --- a/GPU/Software/BinManager.cpp +++ b/GPU/Software/BinManager.cpp @@ -166,7 +166,7 @@ void BinManager::UpdateState(bool throughMode) { if (HasDirty(SoftDirty::PIXEL_ALL | SoftDirty::SAMPLER_ALL | SoftDirty::RAST_ALL)) { if (states_.Full()) Flush("states"); - stateIndex_ = (int)states_.Push(RasterizerState()); + stateIndex_ = (uint16_t)states_.Push(RasterizerState()); ComputeRasterizerState(&states_[stateIndex_], throughMode); states_[stateIndex_].samplerID.cached.clut = cluts_[clutIndex_].readable; @@ -312,7 +312,7 @@ void BinManager::UpdateClut(const void *src) { PROFILE_THIS_SCOPE("bin_clut"); if (cluts_.Full()) Flush("cluts"); - clutIndex_ = (int)cluts_.Push(BinClut()); + clutIndex_ = (uint16_t)cluts_.Push(BinClut()); memcpy(cluts_[clutIndex_].readable, src, sizeof(BinClut)); } diff --git a/GPU/Software/BinManager.h b/GPU/Software/BinManager.h index 1d628aa8e4..79146eae1d 100644 --- a/GPU/Software/BinManager.h +++ b/GPU/Software/BinManager.h @@ -24,7 +24,7 @@ struct BinWaitable; class DrawBinItemsTask; -enum class BinItemType { +enum class BinItemType : uint8_t { TRIANGLE, CLEAR_RECT, RECT, @@ -48,7 +48,7 @@ struct BinCoords { struct BinItem { BinItemType type; - int stateIndex; + uint16_t stateIndex; BinCoords range; VertexData v0; VertexData v1; @@ -237,9 +237,9 @@ protected: private: BinStateQueue states_; - int stateIndex_; BinClutQueue cluts_; - int clutIndex_; + uint16_t stateIndex_; + uint16_t clutIndex_; BinCoords scissor_; BinItemQueue queue_; BinCoords queueRange_; From 8a2115be463cacedace4d63c07a5f35c73a0a123 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 18:39:39 -0700 Subject: [PATCH 104/110] softgpu: Enable early Z tests a bit more often. This helps in cases where sfail doesn't matter. --- GPU/Software/FuncId.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index 0471114caa..f66064f0cf 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -93,13 +93,6 @@ void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { if (gstate.FrameBufFormat() != GE_FORMAT_565 && gstate.getStencilOpZPass() <= GE_STENCILOP_DECR) id->zPass = gstate.getStencilOpZPass(); - // Always treat zPass/zFail the same if there's no depth test. - if (!gstate.isDepthTestEnabled() || gstate.getDepthTestFunction() == GE_COMP_ALWAYS) - id->zFail = id->zPass; - // And same for sFail if there's no stencil test. - if (id->StencilTestFunc() == GE_COMP_ALWAYS) - id->sFail = id->zPass; - // Normalize REPLACE 00 to ZERO, especially if using a mask. if (gstate.getStencilTestRef() == 0) { if (id->SFail() == GE_STENCILOP_REPLACE) @@ -120,6 +113,13 @@ void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->zPass = GE_STENCILOP_ZERO; } + // Always treat zPass/zFail the same if there's no depth test. + if (!gstate.isDepthTestEnabled() || gstate.getDepthTestFunction() == GE_COMP_ALWAYS) + id->zFail = id->zPass; + // And same for sFail if there's no stencil test. Prefer KEEP, though. + if (id->StencilTestFunc() == GE_COMP_ALWAYS) + id->sFail = id->ZFail() == GE_STENCILOP_KEEP ? GE_STENCILOP_KEEP : id->zPass; + // Turn off stencil testing if it's doing nothing. if (id->SFail() == GE_STENCILOP_KEEP && id->ZFail() == GE_STENCILOP_KEEP && id->ZPass() == GE_STENCILOP_KEEP) { if (id->StencilTestFunc() == GE_COMP_ALWAYS) From 8a6e8066bfe3ef2b961bdd2fc1174bc75e5df48d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 18:41:06 -0700 Subject: [PATCH 105/110] softgpu: Store vertex colors as packed RGBA8. No need to keep it expanded at 4x the space for both colors. --- GPU/Software/Lighting.cpp | 8 +++--- GPU/Software/Rasterizer.cpp | 42 ++++++++++++++++++---------- GPU/Software/RasterizerRectangle.cpp | 17 +++++------ GPU/Software/TransformUnit.cpp | 18 ++---------- GPU/Software/TransformUnit.h | 10 +++---- 5 files changed, 48 insertions(+), 47 deletions(-) diff --git a/GPU/Software/Lighting.cpp b/GPU/Software/Lighting.cpp index 262811318f..32596989fe 100644 --- a/GPU/Software/Lighting.cpp +++ b/GPU/Software/Lighting.cpp @@ -276,12 +276,12 @@ void Process(VertexData &vertex, const WorldCoords &worldpos, const WorldCoords } if (state.setColor1) { - vertex.color0 = final_color.Clamp(0, 255); - vertex.color1 = specular_color.Clamp(0, 255).rgb(); + vertex.color0 = final_color.Clamp(0, 255).ToRGBA(); + vertex.color1 = specular_color.Clamp(0, 255).rgb().ToRGB(); } else if (state.addColor1) { - vertex.color0 = (final_color + specular_color).Clamp(0, 255); + vertex.color0 = (final_color + specular_color).Clamp(0, 255).ToRGBA(); } else { - vertex.color0 = final_color.Clamp(0, 255); + vertex.color0 = final_color.Clamp(0, 255).ToRGBA(); } } diff --git a/GPU/Software/Rasterizer.cpp b/GPU/Software/Rasterizer.cpp index 0348f6d57a..a47ed9b0da 100644 --- a/GPU/Software/Rasterizer.cpp +++ b/GPU/Software/Rasterizer.cpp @@ -721,6 +721,13 @@ void DrawTriangleSlice( std::string ztag = StringFromFormat("DisplayListTZ_%08x", state.listPC); #endif + const Vec4 v0_c0 = Vec4::FromRGBA(v0.color0); + const Vec4 v1_c0 = Vec4::FromRGBA(v1.color0); + const Vec4 v2_c0 = Vec4::FromRGBA(v2.color0); + const Vec3 v0_c1 = Vec3::FromRGB(v0.color1); + const Vec3 v1_c1 = Vec3::FromRGB(v1.color1); + const Vec3 v2_c1 = Vec3::FromRGB(v2.color1); + for (int64_t curY = minY; curY <= maxY; curY += SCREEN_SCALE_FACTOR * 2, w0_base = e0.StepY(w0_base), w1_base = e1.StepY(w1_base), @@ -790,22 +797,22 @@ void DrawTriangleSlice( if (!flatColor0) { for (int i = 0; i < 4; ++i) { if (mask[i] >= 0) - prim_color[i] = Interpolate(v0.color0, v1.color0, v2.color0, w0[i], w1[i], w2[i], wsum_recip[i]); + prim_color[i] = Interpolate(v0_c0, v1_c0, v2_c0, w0[i], w1[i], w2[i], wsum_recip[i]); } } else { for (int i = 0; i < 4; ++i) { - prim_color[i] = v2.color0; + prim_color[i] = v2_c0; } } Vec3 sec_color[4]; if (!flatColor1) { for (int i = 0; i < 4; ++i) { if (mask[i] >= 0) - sec_color[i] = Interpolate(v0.color1, v1.color1, v2.color1, w0[i], w1[i], w2[i], wsum_recip[i]); + sec_color[i] = Interpolate(v0_c1, v1_c1, v2_c1, w0[i], w1[i], w2[i], wsum_recip[i]); } } else { for (int i = 0; i < 4; ++i) { - sec_color[i] = v2.color1; + sec_color[i] = v2_c1; } } @@ -965,9 +972,10 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & const Vec4f tto4(0.0f, 0.5f * stx.t(), 0.5f * sty.t(), 0.5f * stx.t() + 0.5f * sty.t()); ScreenCoords pprime(minX, minY, 0); - Vec4 fog = Vec4::AssignToAll(ClampFogDepth(v1.fogdepth)); - Vec4 z = Vec4::AssignToAll(v1.screenpos.z); - Vec3 sec_color = v1.color1; + const Vec4 fog = Vec4::AssignToAll(ClampFogDepth(v1.fogdepth)); + const Vec4 z = Vec4::AssignToAll(v1.screenpos.z); + const Vec4 c0 = Vec4::FromRGBA(v1.color0); + const Vec3 sec_color = Vec3::FromRGB(v1.color1); if (state.pixelID.applyDepthRange) { // We can bail early since the Z is flat. @@ -997,7 +1005,7 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & Vec4 prim_color[4]; for (int i = 0; i < 4; ++i) { - prim_color[i] = v1.color0; + prim_color[i] = c0; } if (state.pixelID.earlyZChecks) { @@ -1073,8 +1081,8 @@ void DrawRectangle(const VertexData &v0, const VertexData &v1, const BinCoords & void DrawPoint(const VertexData &v0, const BinCoords &range, const RasterizerState &state) { ScreenCoords pos = v0.screenpos; - Vec4 prim_color = v0.color0; - Vec3 sec_color = v0.color1; + Vec4 prim_color = Vec4::FromRGBA(v0.color0); + Vec3 sec_color = Vec3::FromRGB(v0.color1); auto &pixelID = state.pixelID; auto &samplerID = state.samplerID; @@ -1218,7 +1226,7 @@ void ClearRectangle(const VertexData &v0, const VertexData &v1, const BinCoords keepOldMask |= pixelID.cached.colorWriteMask; } - const u32 new_color = v1.color0.ToRGBA(); + const u32 new_color = v1.color0; u16 new_color16; switch (pixelID.FBFormat()) { case GE_FORMAT_565: @@ -1343,6 +1351,10 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range auto &samplerID = state.samplerID; const bool interpolateColor = !state.shadeGouraud || (v0.color0 == v1.color0 && v0.color1 == v1.color1); + const Vec4 v0_c0 = Vec4::FromRGBA(v0.color0); + const Vec4 v1_c0 = Vec4::FromRGBA(v1.color0); + const Vec3 v0_c1 = Vec3::FromRGB(v0.color1); + const Vec3 v1_c1 = Vec3::FromRGB(v1.color1); #if defined(SOFTGPU_MEMORY_TAGGING_DETAILED) || defined(SOFTGPU_MEMORY_TAGGING_BASIC) std::string tag = StringFromFormat("DisplayListL_%08x", state.listPC); @@ -1375,11 +1387,11 @@ void DrawLine(const VertexData &v0, const VertexData &v1, const BinCoords &range Vec4 prim_color; Vec3 sec_color; if (interpolateColor) { - prim_color = (v0.color0 * (steps - i) + v1.color0 * i) / steps1; - sec_color = (v0.color1 * (steps - i) + v1.color1 * i) / steps1; + prim_color = (v0_c0 * (steps - i) + v1_c0 * i) / steps1; + sec_color = (v0_c1 * (steps - i) + v1_c1 * i) / steps1; } else { - prim_color = v1.color0; - sec_color = v1.color1; + prim_color = v1_c0; + sec_color = v1_c1; } u8 fog = 255; diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index c94e23beb6..6d3d490ae4 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -119,7 +119,7 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran int z = v1.screenpos.z; int fog = 255; - bool isWhite = v1.color0 == Vec4(255, 255, 255, 255); + bool isWhite = v1.color0 == 0xFFFFFFFF; if (state.enableTextures) { // 1:1 (but with mirror support) texture mapping! @@ -176,11 +176,12 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran } } else { int t = t_start; + const Vec4 c0 = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { int s = s_start; u16 *pixel = fb.Get16Ptr(pos0.x, y, pixelID.cached.framebufStride); for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; + Vec4 prim_color = c0; Vec4 tex_color = fetchFunc(s, t, texptr, texbufw, 0, state.samplerID); prim_color = Vec4(ModulateRGBA(ToVec4IntArg(prim_color), ToVec4IntArg(tex_color), state.samplerID)); if (prim_color.a() > 0) { @@ -202,11 +203,12 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran float tf_start = t_start * (1.0f / (float)(1 << state.samplerID.height0Shift)); float t = tf_start; + const Vec4 c0 = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { float s = sf_start; // Not really that fast but faster than triangle. for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = state.nearest(s, t, xoff, yoff, ToVec4IntArg(v1.color0), &texptr, &texbufw, 0, 0, state.samplerID); + Vec4 prim_color = state.nearest(s, t, xoff, yoff, ToVec4IntArg(c0), &texptr, &texbufw, 0, 0, state.samplerID); state.drawPixel(x, y, z, 255, ToVec4IntArg(prim_color), pixelID); s += dsf; } @@ -227,21 +229,20 @@ void DrawSprite(const VertexData &v0, const VertexData &v1, const BinCoords &ran AlphaTestIsNeedless(pixelID) && !pixelID.applyColorWriteMask && pixelID.FBFormat() == GE_FORMAT_5551) { - if (v1.color0.a() == 0) + if (Vec4::FromRGBA(v1.color0).a() == 0) return; for (int y = pos0.y; y < pos1.y; y++) { u16 *pixel = fb.Get16Ptr(pos0.x, y, pixelID.cached.framebufStride); for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; - DrawSinglePixel5551(pixel, prim_color.ToRGBA(), pixelID); + DrawSinglePixel5551(pixel, v1.color0, pixelID); pixel++; } } } else { + const Vec4 prim_color = Vec4::FromRGBA(v1.color0); for (int y = pos0.y; y < pos1.y; y++) { for (int x = pos0.x; x < pos1.x; x++) { - Vec4 prim_color = v1.color0; state.drawPixel(x, y, z, fog, ToVec4IntArg(prim_color), pixelID); } } @@ -311,7 +312,7 @@ bool RectangleFastPath(const VertexData &v0, const VertexData &v1, BinManager &b // Afterwards, we also need to clear the actual destination. Can do a fast rectfill. gstate.textureMapEnable &= ~1; VertexData newV1 = v1; - newV1.color0 = Vec4(0, 0, 0, 255); + newV1.color0 = 0xFF000000; binner.AddSprite(v0, newV1); gstate.textureMapEnable |= 1; } diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index 28a91a7a8c..2c9a96221d 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -317,24 +317,12 @@ VertexData TransformUnit::ReadVertex(VertexReader &vreader, const TransformState } if (vreader.hasColor0()) { -#ifdef _M_SSE - vreader.ReadColor0_8888((u8 *)vertex.color0.AsArray()); - vertex.color0.ivec = _mm_unpacklo_epi8(vertex.color0.ivec, _mm_setzero_si128()); - vertex.color0.ivec = _mm_unpacklo_epi16(vertex.color0.ivec, _mm_setzero_si128()); -#else - float col[4]; - vreader.ReadColor0(col); - vertex.color0 = Vec4(col[0]*255, col[1]*255, col[2]*255, col[3]*255); -#endif + vreader.ReadColor0_8888((u8 *)&vertex.color0); } else { - vertex.color0 = Vec4::FromRGBA(gstate.getMaterialAmbientRGBA()); + vertex.color0 = gstate.getMaterialAmbientRGBA(); } -#ifdef _M_SSE - vertex.color1 = _mm_setzero_si128(); -#else - vertex.color1 = Vec3(0, 0, 0); -#endif + vertex.color1 = 0; if (state.enableTransform) { WorldCoords worldpos; diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index faa761639c..283273b2c2 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -79,15 +79,15 @@ struct VertexData { texturecoords = ::Lerp(a.texturecoords, b.texturecoords, t); fogdepth = ::Lerp(a.fogdepth, b.fogdepth, t); - u16 t_int = (u16)(t*256); - color0 = LerpInt,256>(a.color0, b.color0, t_int); - color1 = LerpInt,256>(a.color1, b.color1, t_int); + u16 t_int = (u16)(t * 256); + color0 = LerpInt, 256>(Vec4::FromRGBA(a.color0), Vec4::FromRGBA(b.color0), t_int).ToRGBA(); + color1 = LerpInt, 256>(Vec3::FromRGB(a.color1), Vec3::FromRGB(b.color1), t_int).ToRGB(); } ClipCoords clippos; Vec2 texturecoords; - Vec4 color0; - Vec3 color1; + uint32_t color0; + uint32_t color1; ScreenCoords screenpos; // TODO: Shouldn't store this ? float fogdepth; }; From ce4fee737352f2d23122d5f269d306bf7d4a4a09 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 21:14:47 -0700 Subject: [PATCH 106/110] softgpu: Refactor triangle cull processing. --- GPU/Software/TransformUnit.cpp | 54 ++++++++++++---------------------- GPU/Software/TransformUnit.h | 7 +++++ 2 files changed, 25 insertions(+), 36 deletions(-) diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index 28a91a7a8c..aa31e3edf6 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -447,12 +447,6 @@ SoftDirty TransformUnit::GetDirty() { return binner_->GetDirty(); } -enum class CullType { - CW, - CCW, - OFF, -}; - void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, GEPrimitiveType prim_type, int vertex_count, u32 vertex_type, int *bytesRead, SoftwareDrawEngine *drawEngine) { VertexDecoder &vdecoder = *drawEngine->FindVertexDecoder(vertex_type); @@ -541,17 +535,8 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G switch (prim_type) { case GE_PRIM_TRIANGLES: - { - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[2], *binner_); - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[2], *binner_); - } else if (cullType == CullType::CW) { - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[2], *binner_); - } else { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[2], *binner_); - } + SendTriangle(cullType, &data_[0]); break; - } case GE_PRIM_LINES: Clipper::ProcessLine(data_[0], data_[1], *binner_); @@ -688,16 +673,9 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G continue; } - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index_ - 1) % 2)) { - // We need to reverse the vertex order for each second primitive, - // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); - } else { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); - } + int wind = (data_index_ - 1) % 2; + CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind); + SendTriangle(altCullType, &data_[0], provoking_index); } break; } @@ -764,16 +742,9 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G continue; } - if (cullType == CullType::OFF) { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); - } else if ((!(int)cullType) ^ ((data_index_ - 1) % 2)) { - // We need to reverse the vertex order for each second primitive, - // but we additionally need to do that for every primitive if CCW cullmode is used. - Clipper::ProcessTriangle(data_[2], data_[1], data_[0], data_[provoking_index], *binner_); - } else { - Clipper::ProcessTriangle(data_[0], data_[1], data_[2], data_[provoking_index], *binner_); - } + int wind = (data_index_ - 1) % 2; + CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind); + SendTriangle(altCullType, &data_[0], provoking_index); } break; } @@ -784,6 +755,17 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G } } +void TransformUnit::SendTriangle(CullType cullType, const VertexData *verts, int provoking) { + if (cullType == CullType::OFF) { + Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_); + Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_); + } else if (cullType == CullType::CW) { + Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_); + } else { + Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_); + } +} + void TransformUnit::Flush(const char *reason) { binner_->Flush(reason); GPUDebug::NotifyDraw(); diff --git a/GPU/Software/TransformUnit.h b/GPU/Software/TransformUnit.h index faa761639c..ec5883e8e2 100644 --- a/GPU/Software/TransformUnit.h +++ b/GPU/Software/TransformUnit.h @@ -37,6 +37,12 @@ typedef Vec4 ClipCoords; // Range: -w <= x/y/z <= w class BinManager; struct TransformState; +enum class CullType { + CW = 0, + CCW = 1, + OFF = 2, +}; + struct ScreenCoords { ScreenCoords() {} @@ -133,6 +139,7 @@ public: private: VertexData ReadVertex(VertexReader &vreader, const TransformState &lstate, bool &outside_range_flag); + void SendTriangle(CullType cullType, const VertexData *verts, int provoking = 2); u8 *decoded_ = nullptr; BinManager *binner_ = nullptr; From 288d18447d1b16698db4c6c016956ad162d877e2 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 21:15:21 -0700 Subject: [PATCH 107/110] softgpu: Detect full triangles as rectangles. Seen in a dump from Infected, improves FPS ~25% there. --- GPU/Software/RasterizerRectangle.cpp | 47 +++++++++++++++++++++++ GPU/Software/RasterizerRectangle.h | 1 + GPU/Software/TransformUnit.cpp | 57 ++++++++++++++++++++++++++++ 3 files changed, 105 insertions(+) diff --git a/GPU/Software/RasterizerRectangle.cpp b/GPU/Software/RasterizerRectangle.cpp index c94e23beb6..92f167cdda 100644 --- a/GPU/Software/RasterizerRectangle.cpp +++ b/GPU/Software/RasterizerRectangle.cpp @@ -447,6 +447,53 @@ bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data return false; } +bool DetectRectangleFromPair(const RasterizerState &state, const VertexData data[6], int *tlIndex, int *brIndex) { + // Color and Z must be flat. Also find the TL and BR meanwhile. + int tl = 0, br = 0; + for (int i = 1; i < 6; ++i) { + if (!AreCoordsRectangleCompatible(state, data[i], data[0])) + return false; + + if (data[i].screenpos.x <= data[tl].screenpos.x && data[i].screenpos.y <= data[tl].screenpos.y) + tl = i; + if (data[i].screenpos.x >= data[br].screenpos.x && data[i].screenpos.y >= data[br].screenpos.y) + br = i; + } + + *tlIndex = tl; + *brIndex = br; + + auto xat = [&](int i) { return data[i].screenpos.x; }; + auto yat = [&](int i) { return data[i].screenpos.y; }; + auto uat = [&](int i) { return data[i].texturecoords.x; }; + auto vat = [&](int i) { return data[i].texturecoords.y; }; + + // A likely order would be: TL, TR, BR, TL, BR, BL. We'd have the last index of each. + // TODO: Make more generic. + if (tl == 3 && br == 4) { + bool x1_match = xat(0) == xat(3) && xat(0) == xat(5); + bool x2_match = xat(1) == xat(2) && xat(1) == xat(4); + bool y1_match = yat(0) == yat(1) && yat(0) == yat(3); + bool y2_match = yat(2) == yat(4) && yat(2) == yat(5); + if (x1_match && y1_match && x2_match && y2_match) { + // Do we need to think about rotation or UVs? + if (!state.enableTextures) + return true; + + x1_match = uat(0) == uat(3) && uat(0) == uat(5); + x2_match = uat(1) == uat(2) && uat(1) == uat(4); + y1_match = vat(0) == vat(1) && vat(0) == vat(3); + y2_match = vat(2) == vat(4) && vat(2) == vat(5); + if (x1_match && y1_match && x2_match && y2_match) { + // Double check rotation direction. + return vat(tl) < vat(br) && yat(tl) < yat(br) && uat(tl) < uat(br) && xat(tl) < xat(br); + } + } + } + + return false; +} + bool DetectRectangleThroughModeSlices(const RasterizerState &state, const VertexData data[4]) { // Color and Z must be flat. for (int i = 1; i < 4; ++i) { diff --git a/GPU/Software/RasterizerRectangle.h b/GPU/Software/RasterizerRectangle.h index 4407b10a01..6842215338 100644 --- a/GPU/Software/RasterizerRectangle.h +++ b/GPU/Software/RasterizerRectangle.h @@ -22,5 +22,6 @@ namespace Rasterizer { bool DetectRectangleFromStrip(const RasterizerState &state, const VertexData data[4], int *tlIndex, int *brIndex); bool DetectRectangleFromFan(const RasterizerState &state, const VertexData *data, int c, int *tlIndex, int *brIndex); + bool DetectRectangleFromPair(const RasterizerState &state, const VertexData data[6], int *tlIndex, int *brIndex); bool DetectRectangleThroughModeSlices(const RasterizerState &state, const VertexData data[4]); } diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index aa31e3edf6..f19459606f 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -507,6 +507,63 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G const CullType cullType = skipCull ? CullType::OFF : (gstate.getCullMode() ? CullType::CCW : CullType::CW); bool outside_range_flag = false; + + if (vreader.isThrough() && cullType == CullType::OFF && prim_type == GE_PRIM_TRIANGLES && data_index_ + vertex_count >= 6 && ((data_index_ + vertex_count) % 6) == 0) { + // Some games send rectangles as a series of regular triangles. + // We look for this, but only in throughmode. + VertexData buf[6]; + int buf_index = data_index_; + for (int i = 0; i < data_index_; ++i) { + buf[i] = data_[i]; + } + + for (int vtx = 0; vtx < vertex_count; ++vtx) { + if (indices) { + vreader.Goto(ConvertIndex(vtx) - index_lower_bound); + } else { + vreader.Goto(vtx); + } + + buf[buf_index++] = ReadVertex(vreader, transformState, outside_range_flag); + if (buf_index >= 3 && outside_range_flag) { + // Cull, just pretend it didn't happen. + buf_index -= 3; + outside_range_flag = false; + continue; + } + + if (buf_index < 6) + continue; + + int tl = -1, br = -1; + if (Rasterizer::DetectRectangleFromPair(binner_->State(), buf, &tl, &br)) { + Clipper::ProcessRect(buf[tl], buf[br], *binner_); + } else { + SendTriangle(cullType, &buf[0]); + SendTriangle(cullType, &buf[3]); + } + + buf_index = 0; + } + + if (buf_index >= 3) { + SendTriangle(cullType, &buf[0]); + data_index_ = 0; + for (int i = 3; i < buf_index; ++i) { + data_[data_index_++] = buf[i]; + } + } else if (buf_index > 0) { + for (int i = 0; i < buf_index; ++i) { + data_[i] = buf[i]; + } + data_index_ = buf_index; + } else { + data_index_ = 0; + } + + return; + } + switch (prim_type) { case GE_PRIM_POINTS: case GE_PRIM_LINES: From 151727ee01a80c8cd07b2915ebe65b64e7b79f65 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 21:49:37 -0700 Subject: [PATCH 108/110] softgpu: Detect longer strips of rectangles. Could maybe even combine these into one large rectangle, but the main benefit is avoiding triangles. --- GPU/Software/TransformUnit.cpp | 44 ++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/GPU/Software/TransformUnit.cpp b/GPU/Software/TransformUnit.cpp index f19459606f..158cccf3b8 100644 --- a/GPU/Software/TransformUnit.cpp +++ b/GPU/Software/TransformUnit.cpp @@ -686,30 +686,44 @@ void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, G { // Don't draw a triangle when loading the first two vertices. int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_; + int start_vtx = 0; // If index count == 4, check if we can convert to a rectangle. // This is for Darkstalkers (and should speed up many 2D games). - if (data_index_ == 0 && vertex_count == 4 && cullType == CullType::OFF) { - for (int vtx = 0; vtx < 4; ++vtx) { - if (indices) { - vreader.Goto(ConvertIndex(vtx) - index_lower_bound); + if (data_index_ == 0 && vertex_count >= 4 && (vertex_count & 1) == 0 && cullType == CullType::OFF) { + for (int base = 0; base < vertex_count - 2; base += 2) { + for (int vtx = base == 0 ? 0 : 2; vtx < 4; ++vtx) { + if (indices) { + vreader.Goto(ConvertIndex(base + vtx) - index_lower_bound); + } else { + vreader.Goto(base + vtx); + } + data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); } - else { - vreader.Goto(vtx); - } - data_[vtx] = ReadVertex(vreader, transformState, outside_range_flag); - } - // If a strip is effectively a rectangle, draw it as such! - int tl = -1, br = -1; - if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) { - Clipper::ProcessRect(data_[tl], data_[br], *binner_); - break; + // If a strip is effectively a rectangle, draw it as such! + int tl = -1, br = -1; + if (!outside_range_flag && Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) { + Clipper::ProcessRect(data_[tl], data_[br], *binner_); + start_vtx += 2; + if (base + 4 >= vertex_count) { + start_vtx = vertex_count; + break; + } + + // Just copy the first two so we can detect easier. + // TODO: Maybe should give detection two halves? + data_[0] = data_[2]; + data_[1] = data_[3]; + } else { + // Go into triangle mode. Unfortunately, we re-read the verts. + break; + } } } outside_range_flag = false; - for (int vtx = 0; vtx < vertex_count; ++vtx) { + for (int vtx = start_vtx; vtx < vertex_count; ++vtx) { if (indices) { vreader.Goto(ConvertIndex(vtx) - index_lower_bound); } else { From 1f6870798b66f05f663d01180d3b0508c7dd517d Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 21:57:22 -0700 Subject: [PATCH 109/110] softgpu: Include early Z in func description. --- GPU/Software/FuncId.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index 0471114caa..fe0b62be43 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -279,6 +279,8 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { desc = "INVALID:" + desc; } + if (id.earlyZChecks) + desc += "ZEarly:"; if (id.DepthTestFunc() != GE_COMP_ALWAYS) { if (id.clearMode) desc = "INVALID:" + desc; From 3c9372fb751eb354e7414638757cdc88789353e8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sun, 11 Sep 2022 22:11:15 -0700 Subject: [PATCH 110/110] softgpu: Ignore stencil test mask in ALWAYS mode. Small codegen improvement since we can directly use ref and avoid loading the unmasked reference. --- GPU/Software/FuncId.cpp | 53 ++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/GPU/Software/FuncId.cpp b/GPU/Software/FuncId.cpp index f66064f0cf..d0979bf631 100644 --- a/GPU/Software/FuncId.cpp +++ b/GPU/Software/FuncId.cpp @@ -79,6 +79,7 @@ void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->stencilTest = gstate.isStencilTestEnabled(); } id->depthWrite = gstate.isDepthTestEnabled() && gstate.isDepthWriteEnabled(); + id->depthTestFunc = gstate.isDepthTestEnabled() ? gstate.getDepthTestFunction() : GE_COMP_ALWAYS; if (id->stencilTest) { id->stencilTestRef = gstate.getStencilTestRef() & gstate.getStencilTestMask(); @@ -113,21 +114,27 @@ void ComputePixelFuncID(PixelFuncID *id, bool throughMode) { id->zPass = GE_STENCILOP_ZERO; } - // Always treat zPass/zFail the same if there's no depth test. - if (!gstate.isDepthTestEnabled() || gstate.getDepthTestFunction() == GE_COMP_ALWAYS) - id->zFail = id->zPass; // And same for sFail if there's no stencil test. Prefer KEEP, though. - if (id->StencilTestFunc() == GE_COMP_ALWAYS) - id->sFail = id->ZFail() == GE_STENCILOP_KEEP ? GE_STENCILOP_KEEP : id->zPass; + if (id->StencilTestFunc() == GE_COMP_ALWAYS) { + if (id->DepthTestFunc() == GE_COMP_ALWAYS) + id->zFail = GE_STENCILOP_KEEP; + id->sFail = GE_STENCILOP_KEEP; + // Always doesn't need a mask. + id->stencilTestRef = gstate.getStencilTestRef(); + id->hasStencilTestMask = false; - // Turn off stencil testing if it's doing nothing. - if (id->SFail() == GE_STENCILOP_KEEP && id->ZFail() == GE_STENCILOP_KEEP && id->ZPass() == GE_STENCILOP_KEEP) { - if (id->StencilTestFunc() == GE_COMP_ALWAYS) + // Turn off stencil testing if it's doing nothing. + if (id->SFail() == GE_STENCILOP_KEEP && id->ZFail() == GE_STENCILOP_KEEP && id->ZPass() == GE_STENCILOP_KEEP) { id->stencilTest = false; + id->stencilTestFunc = 0; + id->stencilTestRef = 0; + } + } else if (id->DepthTestFunc() == GE_COMP_ALWAYS) { + // Always treat zPass/zFail the same if there's no depth test. + id->zFail = id->zPass; } } - id->depthTestFunc = gstate.isDepthTestEnabled() ? gstate.getDepthTestFunction() : GE_COMP_ALWAYS; id->alphaTestFunc = gstate.isAlphaTestEnabled() ? gstate.getAlphaTestFunction() : GE_COMP_ALWAYS; if (id->AlphaTestFunc() != GE_COMP_ALWAYS) { id->alphaTestRef = gstate.getAlphaTestRef() & gstate.getAlphaTestMask(); @@ -312,7 +319,8 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { } if (id.hasStencilTestMask) desc += "Msk"; - desc += StringFromFormat("%02X:", id.stencilTestRef); + if (id.StencilTestFunc() != GE_COMP_ALWAYS || id.DepthTestFunc() != GE_COMP_ALWAYS) + desc += StringFromFormat("%02X:", id.stencilTestRef); } else if (id.hasStencilTestMask || id.stencilTestRef != 0 || id.stencilTestFunc != 0) { desc = "INVALID:" + desc; } @@ -333,13 +341,24 @@ std::string DescribePixelFuncID(const PixelFuncID &id) { case GE_STENCILOP_INCR: desc += "ZTstFInc:"; break; case GE_STENCILOP_DECR: desc += "ZTstFDec:"; break; } - switch (id.ZPass()) { - case GE_STENCILOP_KEEP: break; - case GE_STENCILOP_ZERO: desc += "ZTstT0:"; break; - case GE_STENCILOP_REPLACE: desc += "ZTstTRpl:"; break; - case GE_STENCILOP_INVERT: desc += "ZTstTXor:"; break; - case GE_STENCILOP_INCR: desc += "ZTstTInc:"; break; - case GE_STENCILOP_DECR: desc += "ZTstTDec:"; break; + if (id.StencilTestFunc() == GE_COMP_ALWAYS && id.DepthTestFunc() == GE_COMP_ALWAYS) { + switch (id.ZPass()) { + case GE_STENCILOP_KEEP: break; + case GE_STENCILOP_ZERO: desc += "Zero:"; break; + case GE_STENCILOP_REPLACE: desc += StringFromFormat("Rpl%02X:", id.stencilTestRef); break; + case GE_STENCILOP_INVERT: desc += "Xor:"; break; + case GE_STENCILOP_INCR: desc += "Inc:"; break; + case GE_STENCILOP_DECR: desc += "Dec:"; break; + } + } else { + switch (id.ZPass()) { + case GE_STENCILOP_KEEP: break; + case GE_STENCILOP_ZERO: desc += "ZTstT0:"; break; + case GE_STENCILOP_REPLACE: desc += "ZTstTRpl:"; break; + case GE_STENCILOP_INVERT: desc += "ZTstTXor:"; break; + case GE_STENCILOP_INCR: desc += "ZTstTInc:"; break; + case GE_STENCILOP_DECR: desc += "ZTstTDec:"; break; + } } if (!id.stencilTest || id.clearMode) { if (id.sFail != 0 || id.zFail != 0 || id.zPass != 0)