From 37712734e24d8f2968b2086a1bfb7db3c8f314c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 13 May 2025 13:05:21 +0200 Subject: [PATCH 01/11] Avoid doing unnecessary UI work during shutdown, add a sanity check --- UI/EmuScreen.cpp | 40 +++++++++++++++++++++++++++++----------- UI/PauseScreen.cpp | 2 +- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index 9089e131e5..b909706e8c 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -210,8 +210,9 @@ void EmuScreen::ProcessGameBoot(const Path &filename) { return; } - if (Achievements::IsBlockingExecution()) { - // Keep waiting. + if (!root_) { + // Views not created yet, wait until they are. Not sure if this can actually happen + // but crash reports seem to indicate it. return; } @@ -220,6 +221,11 @@ void EmuScreen::ProcessGameBoot(const Path &filename) { return; } + if (Achievements::IsBlockingExecution()) { + // Keep waiting. + return; + } + std::string error_string = "(unknown error)"; BootState state = PSP_InitUpdate(&error_string); @@ -456,11 +462,17 @@ EmuScreen::~EmuScreen() { } void EmuScreen::dialogFinished(const Screen *dialog, DialogResult result) { - if (std::string_view(dialog->tag()) == "TextEditPopup") { + std::string_view tag = dialog->tag(); + if (tag == "TextEditPopup") { // Chat message finished. return; } + // Returning to the PauseScreen, unless we're stepping, means we should go back to controls. + if (Core_IsActive()) { + UI::EnableFocusMovement(false); + } + // TODO: improve the way with which we got commands from PauseMenu. // DR_CANCEL/DR_BACK means clicked on "continue", DR_OK means clicked on "back to menu", // DR_YES means a message sent to PauseMenu by System_PostUIMessage. @@ -468,11 +480,10 @@ void EmuScreen::dialogFinished(const Screen *dialog, DialogResult result) { _dbg_assert_(!bootPending_); screenManager()->switchScreen(new MainScreen()); quit_ = false; + } else { + RecreateViews(); } - // Returning to the PauseScreen, unless we're stepping, means we should go back to controls. - if (Core_IsActive()) - UI::EnableFocusMovement(false); - RecreateViews(); + SetExtraAssertInfo(extraAssertInfoStr_.c_str()); // Make sure we re-enable keyboard mode if it was disabled by the dialog, and if needed. @@ -523,7 +534,6 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { } PSP_Shutdown(true); Achievements::UnloadGame(); - bootPending_ = false; System_Notify(SystemNotification::DISASSEMBLY); } else if (message == UIMessage::REQUEST_GAME_RESET) { if (bootPending_) { @@ -532,7 +542,10 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { } PSP_Shutdown(true); Achievements::UnloadGame(); + + // Restart the boot process bootPending_ = true; + RecreateViews(); _dbg_assert_(coreState == CORE_POWERDOWN); if (!PSP_InitStart(PSP_CoreParameter())) { ERROR_LOG(Log::Loader, "Error resetting"); @@ -602,6 +615,10 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { UI::EventParams e{}; OnChatMenu.Trigger(e); } + } else if (!g_Config.bEnableNetworkChat) { + if (chatButton_) { + RecreateViews(); + } } } else if (message == UIMessage::APP_RESUMED && screenManager()->topScreen() == this) { if (System_GetPropertyInt(SYSPROP_DEVICE_TYPE) == DEVICE_TYPE_TV) { @@ -1222,6 +1239,8 @@ void EmuScreen::CreateViews() { cardboardDisableButton_->SetVisibility(V_GONE); cardboardDisableButton_->SetScale(0.65f); // make it smaller - this button can be in the way otherwise. + chatButton_ = nullptr; + chatMenu_ = nullptr; if (g_Config.bEnableNetworkChat) { if (g_Config.iChatButtonPosition != 8) { auto n = GetI18NCategory(I18NCat::NETWORKING); @@ -1232,9 +1251,6 @@ void EmuScreen::CreateViews() { } chatMenu_ = root_->Add(new ChatMenu(GetRequesterToken(), screenManager()->getUIContext()->GetBounds(), screenManager(), new LayoutParams(FILL_PARENT, FILL_PARENT))); chatMenu_->SetVisibility(UI::V_GONE); - } else { - chatButton_ = nullptr; - chatMenu_ = nullptr; } saveStatePreview_ = new AsyncImageFileView(Path(), IS_FIXED, new AnchorLayoutParams(bounds.centerX(), 100, NONE, NONE, true)); @@ -1339,7 +1355,9 @@ int GetChatMessageCount(); void EmuScreen::update() { using namespace UI; + // This is where views are recreated. UIScreen::update(); + resumeButton_->SetVisibility(coreState == CoreState::CORE_RUNTIME_ERROR && Memory::MemFault_MayBeResumable() ? V_VISIBLE : V_GONE); resetButton_->SetVisibility(coreState == CoreState::CORE_RUNTIME_ERROR ? V_VISIBLE : V_GONE); backButton_->SetVisibility(coreState == CoreState::CORE_RUNTIME_ERROR ? V_VISIBLE : V_GONE); diff --git a/UI/PauseScreen.cpp b/UI/PauseScreen.cpp index 83fc6b0788..541ac53bf0 100644 --- a/UI/PauseScreen.cpp +++ b/UI/PauseScreen.cpp @@ -603,7 +603,7 @@ void GamePauseScreen::dialogFinished(const Screen *dialog, DialogResult dr) { } else { if (tag == "Game") { g_BackgroundAudio.SetGame(Path()); - } else if (tag != "ContextMenuPopup") { + } else if (tag != "Prompt" && tag != "ContextMenuPopup") { // There may have been changes to our savestates, so let's recreate. RecreateViews(); } From 80147f318e6cad0c56ebf10d28e1c309c443137d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 13 May 2025 13:58:18 +0200 Subject: [PATCH 02/11] Remove PSP_CancelBoot, assorted cleanup --- Core/HLE/sceAudiocodec.cpp | 3 ++- Core/System.cpp | 29 ++++++++++++++++----------- Core/System.h | 2 -- UI/DebugOverlay.cpp | 41 ++++++++++++++++++++++++-------------- UI/EmuScreen.cpp | 7 +++---- libretro/libretro.cpp | 3 ++- 6 files changed, 50 insertions(+), 35 deletions(-) diff --git a/Core/HLE/sceAudiocodec.cpp b/Core/HLE/sceAudiocodec.cpp index 168f06ab57..bb3ad5022e 100644 --- a/Core/HLE/sceAudiocodec.cpp +++ b/Core/HLE/sceAudiocodec.cpp @@ -147,7 +147,8 @@ static int __AudioCodecInitCommon(u32 ctxPtr, int codec, bool mono) { // Special actions for some codecs. switch (audioType) { case PSP_CODEC_MP3: - _dbg_assert_(ctx->inited == 1); + // Not seeing inited in Kurok (homebrew) + // _dbg_assert_(ctx->inited == 1); ctx->mp3_9999 = 9999; break; case PSP_CODEC_AAC: diff --git a/Core/System.cpp b/Core/System.cpp index 5c4b9f5d51..3c35f02848 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -583,6 +583,7 @@ bool PSP_InitStart(const CoreParameter &coreParam) { BootState PSP_InitUpdate(std::string *error_string) { if (g_bootState == BootState::Booting || g_bootState == BootState::Off) { // Nothing to do right now. + _dbg_assert_(g_bootState == BootState::Booting || !g_loadingThread.joinable()); return g_bootState; } @@ -596,7 +597,8 @@ BootState PSP_InitUpdate(std::string *error_string) { // Failed! (Note: PSP_Shutdown was already called on the loader thread). Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); *error_string = g_CoreParameter.errorString; - return g_bootState; + g_bootState = BootState::Off; + return BootState::Failed; } // Ok, async boot completed, let's finish up things on the main thread. @@ -608,8 +610,8 @@ BootState PSP_InitUpdate(std::string *error_string) { if (!success) { *error_string = "Unable to initialize rendering engine."; PSP_Shutdown(false); - g_bootState = BootState::Failed; - return g_bootState; + g_bootState = BootState::Off; + return BootState::Failed; } } @@ -617,19 +619,25 @@ BootState PSP_InitUpdate(std::string *error_string) { if (!GPU_IsStarted()) { *error_string = "Unable to initialize rendering engine."; PSP_Shutdown(false); - g_bootState = BootState::Failed; + g_bootState = BootState::Off; + Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); + return BootState::Failed; } Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); - return g_bootState; + // The thread should have set it at this point. + _dbg_assert_(g_bootState == BootState::Complete); + return BootState::Complete; } // Most platforms should not use this one, they should call PSP_InitStart and then do their thing // while repeatedly calling PSP_InitUpdate. This is basically just for libretro convenience. BootState PSP_Init(const CoreParameter &coreParam, std::string *error_string) { // InitStart doesn't really fail anymore. - if (!PSP_InitStart(coreParam)) + if (!PSP_InitStart(coreParam)) { + g_bootState = BootState::Off; return BootState::Failed; + } while (true) { BootState state = PSP_InitUpdate(error_string); @@ -649,6 +657,8 @@ void PSP_Shutdown(bool success) { return; } + _assert_(g_bootState != BootState::Failed); + Core_Stop(); if (g_Config.bFuncHashMap) { @@ -659,6 +669,7 @@ void PSP_Shutdown(bool success) { // This should only happen during failures. Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); } + Core_NotifyLifecycle(CoreLifecycle::STOPPING); CPU_Shutdown(success); @@ -677,12 +688,6 @@ void PSP_Shutdown(bool success) { } } -// Call this after handling BootState::Failed. -void PSP_CancelBoot() { - _dbg_assert_(g_bootState == BootState::Failed); - g_bootState = BootState::Off; -} - BootState PSP_Reboot(std::string *error_string) { if (g_bootState != BootState::Complete) { return g_bootState; diff --git a/Core/System.h b/Core/System.h index a3e9aa1178..db3078eab7 100644 --- a/Core/System.h +++ b/Core/System.h @@ -96,8 +96,6 @@ BootState PSP_InitUpdate(std::string *error_string); // Should be avoided/removed eventually. // Returns either BootState::Complete or BootState::Failed. BootState PSP_Init(const CoreParameter &coreParam, std::string *error_string); -// Call this after handling BootState::Failed from PSP_Init. -void PSP_CancelBoot(); void PSP_Shutdown(bool success); BootState PSP_Reboot(std::string *error_string); diff --git a/UI/DebugOverlay.cpp b/UI/DebugOverlay.cpp index 0a93a7eeb9..0ca818a930 100644 --- a/UI/DebugOverlay.cpp +++ b/UI/DebugOverlay.cpp @@ -295,25 +295,36 @@ void DrawCrashDump(UIContext *ctx, const Path &gamePath) { bool checkingISO = false; bool isoOK = false; - char crcStr[50]{}; - if (Reporting::HasCRC(gamePath)) { - u32 crc = Reporting::RetrieveCRC(gamePath); - std::vector dbInfos; - if (g_gameDB.GetGameInfos(discID, &dbInfos)) { - for (auto &dbInfo : dbInfos) { - if (dbInfo.crc == crc) { - isoOK = true; + + switch (PSP_CoreParameter().fileType) { + case IdentifiedFileType::PSP_ISO: + case IdentifiedFileType::PSP_ISO_NP: + { + if (Reporting::HasCRC(gamePath)) { + u32 crc = Reporting::RetrieveCRC(gamePath); + std::vector dbInfos; + if (g_gameDB.GetGameInfos(discID, &dbInfos)) { + for (auto &dbInfo : dbInfos) { + if (dbInfo.crc == crc) { + isoOK = true; + } } } + snprintf(crcStr, sizeof(crcStr), "CRC: %08x %s\n", crc, isoOK ? "(Known good!)" : "(not identified)"); + } else { + // Queue it for calculation, we want it! + // It's OK to call this repeatedly until we have it, which is natural here. + Reporting::QueueCRC(gamePath); + checkingISO = true; } - snprintf(crcStr, sizeof(crcStr), "CRC: %08x %s\n", crc, isoOK ? "(Known good!)" : "(not identified)"); - } else { - // Queue it for calculation, we want it! - // It's OK to call this repeatedly until we have it, which is natural here. - Reporting::QueueCRC(gamePath); - checkingISO = true; + break; } + default: + // Don't show ISO warning for other file types. + isoOK = true; + break; + }; // TODO: Draw a lot more information. Full register set, and so on. @@ -423,7 +434,7 @@ Invalid / Unknown (%d) } if (checkingISO) { tips += "* (waiting for CRC...)\n"; - } else if (!isoOK) { // TODO: Should check that it actually is an ISO and not a homebrew + } else if (!isoOK) { tips += "* Verify and possibly re-dump your ISO\n (CRC not recognized)\n"; } if (g_paramSFO.GetValueString("DISC_VERSION").empty()) { diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index b909706e8c..daf1dc58d7 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -235,7 +235,6 @@ void EmuScreen::ProcessGameBoot(const Path &filename) { return; case BootState::Failed: // Failure. - PSP_CancelBoot(); _dbg_assert_(!error_string.empty()); g_BackgroundAudio.SetGame(Path()); bootPending_ = false; @@ -529,7 +528,7 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { } else if (message == UIMessage::REQUEST_GAME_STOP) { // We will push MainScreen in update(). if (bootPending_) { - ERROR_LOG(Log::Loader, "Can't stop during a pending boot"); + WARN_LOG(Log::Loader, "Can't stop during a pending boot"); return; } PSP_Shutdown(true); @@ -537,7 +536,7 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { System_Notify(SystemNotification::DISASSEMBLY); } else if (message == UIMessage::REQUEST_GAME_RESET) { if (bootPending_) { - ERROR_LOG(Log::Loader, "Can't reset during a pending boot"); + WARN_LOG(Log::Loader, "Can't reset during a pending boot"); return; } PSP_Shutdown(true); @@ -548,7 +547,7 @@ void EmuScreen::sendMessage(UIMessage message, const char *value) { RecreateViews(); _dbg_assert_(coreState == CORE_POWERDOWN); if (!PSP_InitStart(PSP_CoreParameter())) { - ERROR_LOG(Log::Loader, "Error resetting"); + WARN_LOG(Log::Loader, "Error resetting"); screenManager()->switchScreen(new MainScreen()); return; } diff --git a/libretro/libretro.cpp b/libretro/libretro.cpp index 222cc98915..727012b5b8 100644 --- a/libretro/libretro.cpp +++ b/libretro/libretro.cpp @@ -1505,8 +1505,9 @@ bool retro_load_game(const struct retro_game_info *game) // Launch the init process. if (!PSP_InitStart(coreParam)) { g_bootErrorString = coreParam.errorString; - // Can't really fail, the errors happen later during InitUpdate + // Can't really fail, the errors normally happen later during InitUpdate ERROR_LOG(Log::Boot, "%s", g_bootErrorString.c_str()); + g_pendingBoot = false; return false; } From e2bfc48886057faa07651823e80bf5504fddbb6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 00:37:49 +0200 Subject: [PATCH 03/11] Sanity checks in Vulkan backend, PSPDialog --- Common/GPU/Vulkan/VulkanRenderManager.cpp | 10 ++++++++-- Core/Dialog/PSPDialog.cpp | 14 +++++++------- Core/Dialog/PSPDialog.h | 8 +++++--- Core/HLE/sceUtility.cpp | 4 ++-- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/Common/GPU/Vulkan/VulkanRenderManager.cpp b/Common/GPU/Vulkan/VulkanRenderManager.cpp index 5a117a6db3..e28efceba7 100644 --- a/Common/GPU/Vulkan/VulkanRenderManager.cpp +++ b/Common/GPU/Vulkan/VulkanRenderManager.cpp @@ -799,6 +799,7 @@ VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipe }; VKRRenderPass *compatibleRenderPass = queueRunner_.GetRenderPass(key); std::unique_lock lock(compileQueueMutex_); + _dbg_assert_(runCompileThread_); bool needsCompile = false; for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) { if (!(variantBitmask & (1 << i))) @@ -820,8 +821,11 @@ VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipe sampleCount = VK_SAMPLE_COUNT_1_BIT; } - pipeline->pipeline[i] = Promise::CreateEmpty(); - compileQueue_.emplace_back(pipeline, compatibleRenderPass->Get(vulkan_, rpType, sampleCount), rpType, sampleCount); + // Sanity check + if (runCompileThread_) { + pipeline->pipeline[i] = Promise::CreateEmpty(); + compileQueue_.emplace_back(pipeline, compatibleRenderPass->Get(vulkan_, rpType, sampleCount), rpType, sampleCount); + } needsCompile = true; } if (needsCompile) @@ -834,6 +838,8 @@ void VulkanRenderManager::EndCurRenderStep() { if (!curRenderStep_) return; + _dbg_assert_(runCompileThread_); + RPKey key{ curRenderStep_->render.colorLoad, curRenderStep_->render.depthLoad, curRenderStep_->render.stencilLoad, curRenderStep_->render.colorStore, curRenderStep_->render.depthStore, curRenderStep_->render.stencilStore, diff --git a/Core/Dialog/PSPDialog.cpp b/Core/Dialog/PSPDialog.cpp index b643a53b6e..d4a59f99b3 100644 --- a/Core/Dialog/PSPDialog.cpp +++ b/Core/Dialog/PSPDialog.cpp @@ -259,12 +259,6 @@ void PSPDialog::DoState(PointerWrap &p) { } } -pspUtilityDialogCommon *PSPDialog::GetCommonParam() -{ - // FIXME - return 0; -} - void PSPDialog::UpdateButtons() { lastButtons = __CtrlPeekButtons(); @@ -323,7 +317,13 @@ void PSPDialog::DisplayButtons(int flags, std::string_view caption) { auto di = GetI18NCategory(I18NCat::DIALOG); float x1 = 183.5f, x2 = 261.5f; - if (GetCommonParam()->buttonSwap == 1) { + + const pspUtilityDialogCommon *commonParams = GetCommonParam(); + if (!commonParams) { + return; + } + + if (commonParams->buttonSwap == 1) { x1 = 261.5f; x2 = 183.5f; } diff --git a/Core/Dialog/PSPDialog.h b/Core/Dialog/PSPDialog.h index a165b37e31..bfe032aff5 100644 --- a/Core/Dialog/PSPDialog.h +++ b/Core/Dialog/PSPDialog.h @@ -29,8 +29,7 @@ class PointerWrap; #define SCE_UTILITY_DIALOG_RESULT_CANCEL 1 #define SCE_UTILITY_DIALOG_RESULT_ABORT 2 -struct pspUtilityDialogCommon -{ +struct pspUtilityDialogCommon { u32_le size; /** Size of the structure */ s32_le language; /** Language */ s32_le buttonSwap; /** Set to 1 for X/O button swap */ @@ -50,7 +49,10 @@ public: virtual int Update(int animSpeed) = 0; virtual int Shutdown(bool force = false); virtual void DoState(PointerWrap &p); - virtual pspUtilityDialogCommon *GetCommonParam(); + virtual pspUtilityDialogCommon *GetCommonParam() { + // This is returned properly by the derived classes (or should be...). + return nullptr; + } enum DialogStatus { SCE_UTILITY_STATUS_NONE = 0, diff --git a/Core/HLE/sceUtility.cpp b/Core/HLE/sceUtility.cpp index cde1c660dd..3222774d96 100644 --- a/Core/HLE/sceUtility.cpp +++ b/Core/HLE/sceUtility.cpp @@ -484,10 +484,10 @@ static int sceUtilitySavedataGetStatus() { } static int sceUtilitySavedataUpdate(int animSpeed) { - if (currentDialogType != UtilityDialogType::SAVEDATA) { + if (currentDialogType != UtilityDialogType::SAVEDATA || !saveDialog) { return hleLogWarning(Log::sceUtility, SCE_ERROR_UTILITY_WRONG_TYPE, "wrong dialog type"); } - + int result = hleLogDebug(Log::sceUtility, saveDialog->Update(animSpeed)); if (result >= 0) return hleDelayResult(result, "savedata update", 300); From c9b5f5b33a81cebaab0251c0c0ba809cd8b396b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 00:39:56 +0200 Subject: [PATCH 04/11] Add crashfix for dialog value returns if the views were recreated --- Common/UI/Screen.h | 3 +++ Common/UI/UIScreen.cpp | 3 +++ 2 files changed, 6 insertions(+) diff --git a/Common/UI/Screen.h b/Common/UI/Screen.h index d81412c8e1..cd8fd09031 100644 --- a/Common/UI/Screen.h +++ b/Common/UI/Screen.h @@ -108,6 +108,9 @@ public: protected: int GetRequesterToken(); + void WipeRequesterToken() { + token_ = -1; + } private: ScreenManager *screenManager_; diff --git a/Common/UI/UIScreen.cpp b/Common/UI/UIScreen.cpp index ee5a5c1b76..cbecb5e194 100644 --- a/Common/UI/UIScreen.cpp +++ b/Common/UI/UIScreen.cpp @@ -62,6 +62,9 @@ void UIScreen::DoRecreateViews() { root_->SubviewFocused(focused); } } + + // NOTE: We also wipe the requester token. It's possible that views were created with the old token, so any pending requests from them must be invalidated. + WipeRequesterToken(); } void UIScreen::touch(const TouchInput &touch) { From ff37cbe18497886e185a79d91de4c17929bd2af4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 00:41:39 +0200 Subject: [PATCH 05/11] Minor memory safety fixes --- Core/Debugger/DisassemblyManager.cpp | 24 ++++++++++++++---------- Core/Debugger/DisassemblyManager.h | 2 +- Core/MIPS/MIPSInt.cpp | 4 +--- Core/MemMap.cpp | 2 +- Core/System.cpp | 1 + UI/DeveloperToolsScreen.cpp | 19 +++++++++++++++++++ UI/DeveloperToolsScreen.h | 2 ++ UI/EmuScreen.cpp | 1 - UI/ImDebugger/ImDisasmView.cpp | 10 +++++----- UI/ImDebugger/ImDisasmView.h | 2 +- Windows/Debugger/CtrlDisAsmView.cpp | 6 +++--- 11 files changed, 48 insertions(+), 25 deletions(-) diff --git a/Core/Debugger/DisassemblyManager.cpp b/Core/Debugger/DisassemblyManager.cpp index b14d3984e3..5e2a8f7891 100644 --- a/Core/Debugger/DisassemblyManager.cpp +++ b/Core/Debugger/DisassemblyManager.cpp @@ -1093,7 +1093,11 @@ bool DisassemblyComment::disassemble(u32 address, DisassemblyLineInfo &dest, boo return true; } -bool GetDisasmAddressText(u32 address, char* dest, bool abbreviateLabels, bool showData, bool displaySymbols) { +bool GetDisasmAddressText(u32 address, char *dest, size_t bufSize, bool abbreviateLabels, bool showData, bool displaySymbols) { + if (!Memory::IsValid4AlignedAddress(address)) { + snprintf(dest, bufSize, "(bad address!)"); + return true; + } if (displaySymbols) { const std::string addressSymbol = g_symbolMap->GetLabelString(address); if (!addressSymbol.empty()) { @@ -1109,15 +1113,15 @@ bool GetDisasmAddressText(u32 address, char* dest, bool abbreviateLabels, bool s *dest = 0; return true; } else { - sprintf(dest," %08X",address); + snprintf(dest, bufSize, " %08X",address); return false; } } else { if (showData) { - u32 encoding = Memory::IsValidAddress(address) ? Memory::Read_Instruction(address, true).encoding : 0; - sprintf(dest, "%08X %08X", address, encoding); + const u32 encoding = Memory::Read_Instruction(address, true).encoding; + snprintf(dest, bufSize, "%08X %08X", address, encoding); } else { - sprintf(dest, "%08X", address); + snprintf(dest, bufSize, "%08X", address); } return false; } @@ -1147,28 +1151,28 @@ std::string DisassembleRange(u32 start, u32 size, bool displaySymbols, MIPSDebug char addressText[64], buffer[512]; g_disassemblyManager.getLine(disAddress, displaySymbols, line, debugger); - bool isLabel = GetDisasmAddressText(disAddress, addressText, false, line.type == DISTYPE_OPCODE, displaySymbols); + bool isLabel = GetDisasmAddressText(disAddress, addressText, sizeof(addressText), false, line.type == DISTYPE_OPCODE, displaySymbols); if (isLabel) { if (!previousLabel) result += "\r\n"; - sprintf(buffer, "%s\r\n\r\n", addressText); + snprintf(buffer, sizeof(buffer), "%s\r\n\r\n", addressText); result += buffer; } else if (branchAddresses.find(disAddress) != branchAddresses.end()) { if (!previousLabel) result += "\r\n"; - sprintf(buffer, "pos_%08X:\r\n\r\n", disAddress); + snprintf(buffer, sizeof(buffer), "pos_%08X:\r\n\r\n", disAddress); result += buffer; } if (line.info.isBranch && !line.info.isBranchToRegister && g_symbolMap->GetLabelString(line.info.branchTarget).empty() && branchAddresses.find(line.info.branchTarget) != branchAddresses.end()) { - sprintf(buffer, "pos_%08X", line.info.branchTarget); + snprintf(buffer, sizeof(buffer), "pos_%08X", line.info.branchTarget); line.params = line.params.substr(0, line.params.find("0x")) + buffer; } - sprintf(buffer, "\t%s\t%s\r\n", line.name.c_str(), line.params.c_str()); + snprintf(buffer, sizeof(buffer), "\t%s\t%s\r\n", line.name.c_str(), line.params.c_str()); result += buffer; previousLabel = isLabel; disAddress += line.totalSize; diff --git a/Core/Debugger/DisassemblyManager.h b/Core/Debugger/DisassemblyManager.h index b2e028e070..ecfde48f81 100644 --- a/Core/Debugger/DisassemblyManager.h +++ b/Core/Debugger/DisassemblyManager.h @@ -228,4 +228,4 @@ bool isInInterval(u32 start, u32 size, u32 value); bool IsLikelyStringAt(uint32_t addr); std::string DisassembleRange(u32 start, u32 size, bool displaySymbols, MIPSDebugInterface *debugger); -bool GetDisasmAddressText(u32 address, char* dest, bool abbreviateLabels, bool showData, bool displaySymbols); +bool GetDisasmAddressText(u32 address, char *dest, size_t bufSize, bool abbreviateLabels, bool showData, bool displaySymbols); diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index 0896a169ab..e4a14d80f1 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -1045,7 +1045,7 @@ namespace MIPSInt void Int_Emuhack(MIPSOpcode op) { if (((op >> 24) & 3) != EMUOP_CALL_REPLACEMENT) { - _dbg_assert_msg_(false,"Trying to interpret emuhack instruction that can't be interpreted"); + _dbg_assert_msg_(false, "Trying to interpret emuhack instruction that can't be interpreted"); } // It's a replacement func! int index = op.encoding & 0xFFFFFF; @@ -1071,6 +1071,4 @@ namespace MIPSInt MIPSInterpret(Memory::Read_Instruction(PC, true)); } } - - } diff --git a/Core/MemMap.cpp b/Core/MemMap.cpp index 6cd14d01d2..0d0cfbe990 100644 --- a/Core/MemMap.cpp +++ b/Core/MemMap.cpp @@ -496,7 +496,7 @@ void Memset(const u32 _Address, const u8 _iValue, const u32 _iLength, const char // TODO: This mainly seems to be produced by GPUCommon::PerformMemorySet, called from // Replace_memset_jak(). Strangely, this managed to crash in Write_U8(). for (size_t i = 0; i < _iLength; i++) { - if (Memory::IsValidAddress(_Address + i)) { + if (Memory::IsValidAddress(_Address + (u32)i)) { WriteUnchecked_U8(_iValue, (u32)(_Address + i)); } } diff --git a/Core/System.cpp b/Core/System.cpp index 3c35f02848..4ca9d52a01 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -342,6 +342,7 @@ static bool CPU_Init(FileLoader *fileLoader, IdentifiedFileType type, std::strin auto sc = GetI18NCategory(I18NCat::SCREEN); + _dbg_assert_(!g_symbolMap); g_symbolMap = new SymbolMap(); MIPSAnalyst::Reset(); diff --git a/UI/DeveloperToolsScreen.cpp b/UI/DeveloperToolsScreen.cpp index 5509ee29d4..56d62d1ede 100644 --- a/UI/DeveloperToolsScreen.cpp +++ b/UI/DeveloperToolsScreen.cpp @@ -222,6 +222,13 @@ void DeveloperToolsScreen::CreateTestsTab(UI::LinearLayout *list) { if (g_Config.iGPUBackend == (int)GPUBackend::VULKAN || g_Config.iGPUBackend == (int)GPUBackend::OPENGL) { list->Add(new Choice(dev->T("GPU Driver Test")))->OnClick.Handle(this, &DeveloperToolsScreen::OnGPUDriverTest); } + + auto memmapTest = list->Add(new Choice(dev->T("Memory map test"))); + memmapTest->OnClick.Add([this](UI::EventParams &e) { + MemoryMapTest(); + return UI::EVENT_DONE; + }); + memmapTest->SetEnabled(PSP_IsInited()); } void DeveloperToolsScreen::CreateDumpFileTab(UI::LinearLayout *list) { @@ -613,6 +620,18 @@ void DeveloperToolsScreen::update() { canAllowDebugger_ = !WebServerStopping(WebServerFlags::DEBUGGER); } +void DeveloperToolsScreen::MemoryMapTest() { + int sum = 0; + for (uint64_t addr = 0; addr < 0x100000000ULL; addr += 0x1000) { + const u32 addr32 = (u32)addr; + if (Memory::IsValidAddress(addr32)) { + sum += Memory::ReadUnchecked_U32(addr32); + } + } + // Just to force the compiler to do things properly. + INFO_LOG(Log::JIT, "Total sum: %08x", sum); +} + static bool RunMemstickTest(std::string *error) { Path testRoot = GetSysDirectory(PSPDirectories::DIRECTORY_CACHE) / "test"; diff --git a/UI/DeveloperToolsScreen.h b/UI/DeveloperToolsScreen.h index 4aaaa6b47d..bb1fd67101 100644 --- a/UI/DeveloperToolsScreen.h +++ b/UI/DeveloperToolsScreen.h @@ -42,6 +42,8 @@ private: UI::EventReturn OnTouchscreenTest(UI::EventParams &e); UI::EventReturn OnCopyStatesToRoot(UI::EventParams &e); + void MemoryMapTest(); + bool allowDebugger_ = false; bool canAllowDebugger_ = true; enum class HasIni { diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index daf1dc58d7..6bab13fc36 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -476,7 +476,6 @@ void EmuScreen::dialogFinished(const Screen *dialog, DialogResult result) { // DR_CANCEL/DR_BACK means clicked on "continue", DR_OK means clicked on "back to menu", // DR_YES means a message sent to PauseMenu by System_PostUIMessage. if ((result == DR_OK || quit_) && !bootPending_) { - _dbg_assert_(!bootPending_); screenManager()->switchScreen(new MainScreen()); quit_ = false; } else { diff --git a/UI/ImDebugger/ImDisasmView.cpp b/UI/ImDebugger/ImDisasmView.cpp index e0153e92d2..e7d7438856 100644 --- a/UI/ImDebugger/ImDisasmView.cpp +++ b/UI/ImDebugger/ImDisasmView.cpp @@ -51,11 +51,11 @@ static ImColor scaleColor(ImColor color, float factor) { return color; } -bool ImDisasmView::getDisasmAddressText(u32 address, char* dest, bool abbreviateLabels, bool showData) { +bool ImDisasmView::getDisasmAddressText(u32 address, char *dest, size_t bufSize, bool abbreviateLabels, bool showData) { if (PSP_GetBootState() != BootState::Complete) return false; - return GetDisasmAddressText(address, dest, abbreviateLabels, showData, displaySymbols_); + return GetDisasmAddressText(address, dest, bufSize, abbreviateLabels, showData, displaySymbols_); } void ImDisasmView::assembleOpcode(u32 address, const std::string &defaultText) { @@ -358,7 +358,7 @@ void ImDisasmView::Draw(ImDrawList *drawList, ImControl &control) { } char addressText[64]; - getDisasmAddressText(address, addressText, true, line.type == DISTYPE_OPCODE); + getDisasmAddressText(address, addressText, sizeof(addressText), true, line.type == DISTYPE_OPCODE); drawList->AddText(ImVec2(bounds.x + pixelPositions_.addressStart, bounds.y + rowY1 + 2), textColor, addressText); if (isInInterval(address, line.totalSize, pc)) { @@ -1013,7 +1013,7 @@ void ImDisasmView::SearchNext(bool forward) { g_disassemblyManager.getLine(searchAddress, displaySymbols_, lineInfo, debugger_); char addressText[64]; - getDisasmAddressText(searchAddress, addressText, true, lineInfo.type == DISTYPE_OPCODE); + getDisasmAddressText(searchAddress, addressText, sizeof(addressText), true, lineInfo.type == DISTYPE_OPCODE); const char* opcode = lineInfo.name.c_str(); const char* arguments = lineInfo.params.c_str(); @@ -1075,7 +1075,7 @@ std::string ImDisasmView::disassembleRange(u32 start, u32 size) { char addressText[64], buffer[512]; g_disassemblyManager.getLine(disAddress, displaySymbols_, line, debugger_); - bool isLabel = getDisasmAddressText(disAddress, addressText, false, line.type == DISTYPE_OPCODE); + bool isLabel = getDisasmAddressText(disAddress, addressText, sizeof(addressText), false, line.type == DISTYPE_OPCODE); if (isLabel) { if (!previousLabel) result += "\r\n"; diff --git a/UI/ImDebugger/ImDisasmView.h b/UI/ImDebugger/ImDisasmView.h index b092c1df69..f70f7291f4 100644 --- a/UI/ImDebugger/ImDisasmView.h +++ b/UI/ImDebugger/ImDisasmView.h @@ -130,7 +130,7 @@ private: void disassembleToFile(); void FollowBranch(); void calculatePixelPositions(); - bool getDisasmAddressText(u32 address, char* dest, bool abbreviateLabels, bool showData); + bool getDisasmAddressText(u32 address, char *dest, size_t bufSize, bool abbreviateLabels, bool showData); void updateStatusBarText(); void drawBranchLine(ImDrawList *list, Bounds rc, std::map &addressPositions, const BranchLine &line); void CopyInstructions(u32 startAddr, u32 endAddr, CopyInstructionsMode mode); diff --git a/Windows/Debugger/CtrlDisAsmView.cpp b/Windows/Debugger/CtrlDisAsmView.cpp index 0edb83857d..2865dee776 100644 --- a/Windows/Debugger/CtrlDisAsmView.cpp +++ b/Windows/Debugger/CtrlDisAsmView.cpp @@ -529,8 +529,8 @@ void CtrlDisAsmView::onPaint(WPARAM wParam, LPARAM lParam) SetTextColor(hdc,textColor); char addressText[64]; - GetDisasmAddressText(address,addressText,true,line.type == DISTYPE_OPCODE, displaySymbols); - TextOutA(hdc,pixelPositions.addressStart,rowY1+2,addressText,(int)strlen(addressText)); + GetDisasmAddressText(address, addressText, sizeof(addressText), true, line.type == DISTYPE_OPCODE, displaySymbols); + TextOutA(hdc, pixelPositions.addressStart, rowY1+2, addressText, (int)strlen(addressText)); if (isInInterval(address,line.totalSize,debugger->GetPC())) { @@ -1252,7 +1252,7 @@ void CtrlDisAsmView::search(bool continueSearch) g_disassemblyManager.getLine(searchAddress,displaySymbols,lineInfo, debugger); char addressText[64]; - GetDisasmAddressText(searchAddress,addressText,true,lineInfo.type == DISTYPE_OPCODE, displaySymbols); + GetDisasmAddressText(searchAddress, addressText, sizeof(addressText), true, lineInfo.type == DISTYPE_OPCODE, displaySymbols); const char* opcode = lineInfo.name.c_str(); const char* arguments = lineInfo.params.c_str(); From dd38e8d012e767aa42d9c5dd9c094722a39a5046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 00:44:48 +0200 Subject: [PATCH 06/11] GPU constify --- GPU/Common/VertexDecoderCommon.cpp | 16 ++++++++++------ GPU/GPUCommonHW.cpp | 10 +++++----- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index eb0bce1ff4..460f18c119 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -106,14 +106,15 @@ void DecVtxFormat::InitializeFromID(uint32_t id) { void GetIndexBounds(const void *inds, int count, u32 vertType, u16 *indexLowerBound, u16 *indexUpperBound) { // Find index bounds. Could cache this in display lists. - // Also, this could be greatly sped up with SSE2/NEON, although rarely a bottleneck. + // Also, this could be greatly sped up with SSE2/NEON, although rarely a bottleneck, and some compilers + // autovectorize this just fine. u32 idx = vertType & GE_VTYPE_IDX_MASK; if (idx == GE_VTYPE_IDX_16BIT) { uint16_t upperBound = 0; uint16_t lowerBound = 0xFFFF; const u16_le *ind16 = (const u16_le *)inds; for (int i = 0; i < count; i++) { - u16 value = ind16[i]; + const u16 value = ind16[i]; if (value > upperBound) upperBound = value; if (value < lowerBound) @@ -126,7 +127,7 @@ void GetIndexBounds(const void *inds, int count, u32 vertType, u16 *indexLowerBo uint8_t lowerBound = 0xFF; const u8 *ind8 = (const u8 *)inds; for (int i = 0; i < count; i++) { - u8 value = ind8[i]; + const u8 value = ind8[i]; if (value > upperBound) upperBound = value; if (value < lowerBound) @@ -137,13 +138,13 @@ void GetIndexBounds(const void *inds, int count, u32 vertType, u16 *indexLowerBo } else if (idx == GE_VTYPE_IDX_32BIT) { int lowerBound = 0x7FFFFFFF; int upperBound = 0; - WARN_LOG_REPORT_ONCE(indexBounds32, Log::G3D, "GetIndexBounds: Decoding 32-bit indexes"); + bool oob = false; const u32_le *ind32 = (const u32_le *)inds; for (int i = 0; i < count; i++) { - u16 value = (u16)ind32[i]; + const u16 value = (u16)ind32[i]; // These aren't documented and should be rare. Let's bounds check each one. if (ind32[i] != value) { - ERROR_LOG_REPORT_ONCE(indexBounds32Bounds, Log::G3D, "GetIndexBounds: Index outside 16-bit range"); + oob = true; } if (value > upperBound) upperBound = value; @@ -152,6 +153,9 @@ void GetIndexBounds(const void *inds, int count, u32 vertType, u16 *indexLowerBo } *indexLowerBound = (u16)lowerBound; *indexUpperBound = (u16)upperBound; + if (oob) { + ERROR_LOG_REPORT_ONCE(indexBounds32Bounds, Log::G3D, "GetIndexBounds: Index outside 16-bit range"); + } } else { *indexLowerBound = 0; if (count > 0) { diff --git a/GPU/GPUCommonHW.cpp b/GPU/GPUCommonHW.cpp index 40fd04efcc..d5639bfb7b 100644 --- a/GPU/GPUCommonHW.cpp +++ b/GPU/GPUCommonHW.cpp @@ -911,7 +911,7 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { FlushImm(); // Upper bits are ignored. - GEPrimitiveType prim = static_cast((op >> 16) & 7); + const GEPrimitiveType prim = static_cast((op >> 16) & 7); SetDrawType(DRAW_PRIM, prim); // Discard AA lines as we can't do anything that makes sense with these anyway. The SW plugin might, though. @@ -956,7 +956,7 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { // This also makes skipping drawing very effective. bool changed; - VirtualFramebuffer *vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason, &changed); + VirtualFramebuffer *const vfb = framebufferManager_->SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason, &changed); if (blueToAlpha) { vfb->usageFlags |= FB_USAGE_BLUE_TO_ALPHA; } @@ -969,7 +969,7 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { vertexCost_ = EstimatePerVertexCost(); } - u32 count = op & 0xFFFF; + const u32 count = op & 0xFFFF; // Must check this after SetRenderFrameBuffer so we know SKIPDRAW_NON_DISPLAYED_FB. if (gstate_c.skipDrawReason & (SKIPDRAW_SKIPFRAME | SKIPDRAW_NON_DISPLAYED_FB)) { // Rough estimate, not sure what's correct. @@ -1075,7 +1075,7 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { // PRIM commands with other commands. A special case is Earth Defence Force 2 that changes culling mode // between each prim, we just change the triangle winding right here to still be able to join draw calls. - uint32_t vtypeCheckMask = g_Config.bSoftwareSkinning ? (~GE_VTYPE_WEIGHTCOUNT_MASK) : 0xFFFFFFFF; + const uint32_t vtypeCheckMask = g_Config.bSoftwareSkinning ? (~GE_VTYPE_WEIGHTCOUNT_MASK) : 0xFFFFFFFF; if (!useFastRunLoop_) goto bail; // we're either recording or stepping. @@ -1258,7 +1258,7 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { bail: drawEngineCommon_->FlushSkin(); gstate.cmdmem[GE_CMD_VERTEXTYPE] = vertexType; - int cmdCount = src - start; + const int cmdCount = src - start; // Skip over the commands we just read out manually. if (cmdCount > 0) { UpdatePC(currentList->pc, currentList->pc + cmdCount * 4); From dde3099d0c9cdc16a0a4328bd5b1290e8278086b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 09:22:25 +0200 Subject: [PATCH 07/11] Expose the hidden ShaderCache option in developer tools --- Core/Config.cpp | 2 +- Core/MIPS/MIPSInt.cpp | 3 +++ UI/DeveloperToolsScreen.cpp | 1 + UI/EmuScreen.cpp | 5 +++++ 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index 55f2296e88..2a631452d6 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -738,7 +738,7 @@ static const ConfigSetting graphicsSettings[] = { ConfigSetting("MultiThreading", &g_Config.bRenderMultiThreading, true, CfgFlag::DEFAULT), - ConfigSetting("ShaderCache", &g_Config.bShaderCache, true, CfgFlag::DONT_SAVE), // Doesn't save. Ini-only. + ConfigSetting("ShaderCache", &g_Config.bShaderCache, true, CfgFlag::DEFAULT), ConfigSetting("GpuLogProfiler", &g_Config.bGpuLogProfiler, false, CfgFlag::DEFAULT), ConfigSetting("UberShaderVertex", &g_Config.bUberShaderVertex, true, CfgFlag::DEFAULT), diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index e4a14d80f1..392aab0e04 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -1047,6 +1047,9 @@ namespace MIPSInt if (((op >> 24) & 3) != EMUOP_CALL_REPLACEMENT) { _dbg_assert_msg_(false, "Trying to interpret emuhack instruction that can't be interpreted"); } + + _assert_((PC & 3) == 0); + // It's a replacement func! int index = op.encoding & 0xFFFFFF; const ReplacementTableEntry *entry = GetReplacementFunc(index); diff --git a/UI/DeveloperToolsScreen.cpp b/UI/DeveloperToolsScreen.cpp index 56d62d1ede..98b11653a0 100644 --- a/UI/DeveloperToolsScreen.cpp +++ b/UI/DeveloperToolsScreen.cpp @@ -345,6 +345,7 @@ void DeveloperToolsScreen::CreateGraphicsTab(UI::LinearLayout *list) { list->Add(new ItemHeader(sy->T("General"))); list->Add(new CheckBox(&g_Config.bVendorBugChecksEnabled, dev->T("Enable driver bug workarounds"))); + list->Add(new CheckBox(&g_Config.bShaderCache, dev->T("Enable shader cache"))); static const char *ffModes[] = { "Render all frames", "", "Frame Skipping" }; PopupMultiChoice *ffMode = list->Add(new PopupMultiChoice(&g_Config.iFastForwardMode, dev->T("Fast-forward mode"), ffModes, 0, ARRAY_SIZE(ffModes), I18NCat::GRAPHICS, screenManager())); diff --git a/UI/EmuScreen.cpp b/UI/EmuScreen.cpp index 6bab13fc36..04b0393fd8 100644 --- a/UI/EmuScreen.cpp +++ b/UI/EmuScreen.cpp @@ -266,6 +266,11 @@ void EmuScreen::ProcessGameBoot(const Path &filename) { SetAssertCancelCallback(&AssertCancelCallback, this); + if (!g_Config.bShaderCache) { + // Only developers should ever see this. + g_OSD.Show(OSDType::MESSAGE_WARNING, "Shader cache is disabled (developer)"); + } + currentMIPS = &mipsr4k; CoreParameter coreParam{}; From 3e0fea509d29ca7eaec5ca6ba76d6ba7d21c3f5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 09:29:31 +0200 Subject: [PATCH 08/11] Improve sanity checks for vertex ranges in GPU --- GPU/GPUCommon.cpp | 26 +++++++++++--------------- GPU/GPUCommon.h | 2 +- GPU/GPUCommonHW.cpp | 14 ++++++++++---- GPU/GPUState.h | 1 - 4 files changed, 22 insertions(+), 21 deletions(-) diff --git a/GPU/GPUCommon.cpp b/GPU/GPUCommon.cpp index 1f922011b5..fc14cb8e53 100644 --- a/GPU/GPUCommon.cpp +++ b/GPU/GPUCommon.cpp @@ -1197,8 +1197,10 @@ void GPUCommon::Execute_BoundingBox(u32 op, u32 diff) { // Approximate based on timings of several counts on a PSP. cyclesExecuted += count * 22; - const bool useInds = (gstate.vertType & GE_VTYPE_IDX_MASK) != 0; - VertexDecoder *dec = drawEngineCommon_->GetVertexDecoder(gstate.vertType); + const u32 vertType = gstate.vertType; + + const bool useInds = (vertType & GE_VTYPE_IDX_MASK) != 0; + const VertexDecoder *dec = drawEngineCommon_->GetVertexDecoder(vertType); int bytesRead = (useInds ? 1 : dec->VertexSize()) * count; if (!Memory::IsValidRange(gstate_c.vertexAddr, bytesRead)) { @@ -1207,23 +1209,17 @@ void GPUCommon::Execute_BoundingBox(u32 op, u32 diff) { currentList->bboxResult = true; return; } - - const void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); - if (!control_points) { - ERROR_LOG_REPORT_ONCE(boundingbox, Log::G3D, "Invalid verts in bounding box check"); - currentList->bboxResult = true; - return; - } + const void *control_points = Memory::GetPointerUnchecked(gstate_c.vertexAddr); // we checked the range above. const void *inds = nullptr; if (useInds) { - int indexShift = ((gstate.vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; - inds = Memory::GetPointerUnchecked(gstate_c.indexAddr); - if (!inds || !Memory::IsValidRange(gstate_c.indexAddr, count << indexShift)) { + const int indexSizeShift = ((vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; + if (!Memory::IsValidRange(gstate_c.indexAddr, count << indexSizeShift)) { ERROR_LOG_REPORT_ONCE(boundingboxInds, Log::G3D, "Invalid inds in bounding box check"); currentList->bboxResult = true; return; } + inds = Memory::GetPointerUnchecked(gstate_c.indexAddr); } // Test if the bounding box is within the drawing region. @@ -1231,12 +1227,12 @@ void GPUCommon::Execute_BoundingBox(u32 op, u32 diff) { if (count > 0x200) { // The second to last set of 0x100 is checked (even for odd counts.) size_t skipSize = (count - 0x200) * dec->VertexSize(); - currentList->bboxResult = drawEngineCommon_->TestBoundingBox((const uint8_t *)control_points + skipSize, inds, 0x100, dec, gstate.vertType); + currentList->bboxResult = drawEngineCommon_->TestBoundingBox((const uint8_t *)control_points + skipSize, inds, 0x100, dec, vertType); } else if (count > 0x100) { int checkSize = count - 0x100; - currentList->bboxResult = drawEngineCommon_->TestBoundingBox(control_points, inds, checkSize, dec, gstate.vertType); + currentList->bboxResult = drawEngineCommon_->TestBoundingBox(control_points, inds, checkSize, dec, vertType); } else { - currentList->bboxResult = drawEngineCommon_->TestBoundingBox(control_points, inds, count, dec, gstate.vertType); + currentList->bboxResult = drawEngineCommon_->TestBoundingBox(control_points, inds, count, dec, vertType); } AdvanceVerts(gstate.vertType, count, bytesRead); } diff --git a/GPU/GPUCommon.h b/GPU/GPUCommon.h index fa5d5672b2..2b4827ac21 100644 --- a/GPU/GPUCommon.h +++ b/GPU/GPUCommon.h @@ -448,7 +448,7 @@ protected: void AdvanceVerts(u32 vertType, int count, int bytesRead) { if ((vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { - int indexShift = ((vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; + const int indexShift = ((vertType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; gstate_c.indexAddr += count << indexShift; } else { gstate_c.vertexAddr += bytesRead; diff --git a/GPU/GPUCommonHW.cpp b/GPU/GPUCommonHW.cpp index d5639bfb7b..0b3ffa5e11 100644 --- a/GPU/GPUCommonHW.cpp +++ b/GPU/GPUCommonHW.cpp @@ -985,14 +985,14 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { const void *verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); const void *inds = nullptr; - bool isTriangle = IsTrianglePrim(prim); + const bool isTriangle = IsTrianglePrim(prim); bool canExtend = isTriangle; u32 vertexType = gstate.vertType; if ((vertexType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { u32 indexAddr = gstate_c.indexAddr; - u32 indexSize = (vertexType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT; - if (!Memory::IsValidRange(indexAddr, count * indexSize)) { + const int indexShift = ((vertexType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; + if (!Memory::IsValidRange(indexAddr, count << indexShift)) { ERROR_LOG(Log::G3D, "Bad index address %08x (%d)!", indexAddr, count); return; } @@ -1109,7 +1109,13 @@ void GPUCommonHW::Execute_Prim(u32 op, u32 diff) { verts = Memory::GetPointerUnchecked(gstate_c.vertexAddr); inds = nullptr; if ((vertexType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) { - inds = Memory::GetPointerUnchecked(gstate_c.indexAddr); + const u32 indexAddr = gstate_c.indexAddr; + const int indexShift = ((vertexType & GE_VTYPE_IDX_MASK) >> GE_VTYPE_IDX_SHIFT) - 1; + if (!Memory::IsValidRange(gstate_c.indexAddr, count << indexShift)) { + // Bad index range. Let's give up the fast loop. + goto bail; + } + inds = Memory::GetPointerUnchecked(indexAddr); } else { // We can extend again after submitting a normal draw. canExtend = isTriangle; diff --git a/GPU/GPUState.h b/GPU/GPUState.h index b25bd443b2..0cb0517028 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -420,7 +420,6 @@ struct GPUgstate { int getTransferHeight() const { return ((transfersize >> 10) & 0x3FF) + 1; } int getTransferBpp() const { return (transferstart & 1) ? 4 : 2; } - void FastLoadBoneMatrix(u32 addr); // Real data in the context ends here From 8ed898c5e6261bb8c6d38dadb524c6dc0778bdc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 09:38:31 +0200 Subject: [PATCH 09/11] GPU: Constify VertexDecoder pointers, remove in some cases --- GPU/Common/DepthRaster.cpp | 6 +++--- GPU/Common/DepthRaster.h | 6 +++--- GPU/Common/DrawEngineCommon.cpp | 18 +++++++++--------- GPU/Common/DrawEngineCommon.h | 20 ++++++++++---------- GPU/Common/ShaderId.cpp | 5 +---- GPU/Common/ShaderId.h | 4 +--- GPU/Common/SoftwareTransformCommon.cpp | 2 +- GPU/Common/SoftwareTransformCommon.h | 2 +- GPU/D3D11/DrawEngineD3D11.cpp | 6 +++--- GPU/D3D11/ShaderManagerD3D11.cpp | 5 +++-- GPU/D3D11/ShaderManagerD3D11.h | 2 +- GPU/Directx9/DrawEngineDX9.cpp | 6 +++--- GPU/Directx9/ShaderManagerDX9.cpp | 6 +++--- GPU/Directx9/ShaderManagerDX9.h | 2 +- GPU/GLES/DrawEngineGLES.cpp | 4 ++-- GPU/GLES/ShaderManagerGLES.cpp | 6 +++--- GPU/GLES/ShaderManagerGLES.h | 4 +++- GPU/Vulkan/DrawEngineVulkan.cpp | 6 +++--- GPU/Vulkan/ShaderManagerVulkan.cpp | 5 +++-- GPU/Vulkan/ShaderManagerVulkan.h | 2 +- 20 files changed, 58 insertions(+), 59 deletions(-) diff --git a/GPU/Common/DepthRaster.cpp b/GPU/Common/DepthRaster.cpp index c46278f36b..2c205c72e0 100644 --- a/GPU/Common/DepthRaster.cpp +++ b/GPU/Common/DepthRaster.cpp @@ -264,7 +264,7 @@ void DepthRaster4Triangles(int stats[3], uint16_t *depthBuf, int stride, DepthSc } // This will always run on the main thread. Though, might consider moving the transforms out and just storing verts instead? -void DecodeAndTransformForDepthRaster(float *dest, const float *worldviewproj, const void *vertexData, int indexLowerBound, int indexUpperBound, VertexDecoder *dec, u32 vertTypeID) { +void DecodeAndTransformForDepthRaster(float *dest, const float *worldviewproj, const void *vertexData, int indexLowerBound, int indexUpperBound, const VertexDecoder *dec, u32 vertTypeID) { // TODO: Ditch skinned and morphed prims for now since we don't have a fast way to skin without running the full decoder. _dbg_assert_((vertTypeID & (GE_VTYPE_WEIGHT_MASK | GE_VTYPE_MORPHCOUNT_MASK)) == 0); @@ -298,7 +298,7 @@ void DecodeAndTransformForDepthRaster(float *dest, const float *worldviewproj, c } } -void TransformPredecodedForDepthRaster(float *dest, const float *worldviewproj, const void *decodedVertexData, VertexDecoder *dec, int count) { +void TransformPredecodedForDepthRaster(float *dest, const float *worldviewproj, const void *decodedVertexData, const VertexDecoder *dec, int count) { // TODO: Ditch skinned and morphed prims for now since we don't have a fast way to skin without running the full decoder. _dbg_assert_((dec->VertexType() & (GE_VTYPE_WEIGHT_MASK | GE_VTYPE_MORPHCOUNT_MASK)) == 0); @@ -315,7 +315,7 @@ void TransformPredecodedForDepthRaster(float *dest, const float *worldviewproj, } } -void ConvertPredecodedThroughForDepthRaster(float *dest, const void *decodedVertexData, VertexDecoder *dec, int count) { +void ConvertPredecodedThroughForDepthRaster(float *dest, const void *decodedVertexData, const VertexDecoder *dec, int count) { // TODO: Ditch skinned and morphed prims for now since we don't have a fast way to skin without running the full decoder. _dbg_assert_((dec->VertexType() & (GE_VTYPE_WEIGHT_MASK | GE_VTYPE_MORPHCOUNT_MASK)) == 0); diff --git a/GPU/Common/DepthRaster.h b/GPU/Common/DepthRaster.h index a798db1b3c..6f433ced41 100644 --- a/GPU/Common/DepthRaster.h +++ b/GPU/Common/DepthRaster.h @@ -53,7 +53,7 @@ struct TransformedVertex; int DepthRasterClipIndexedTriangles(int *tx, int *ty, float *tz, const float *transformed, const uint16_t *indexBuffer, const DepthDraw &draw, const DepthScissor scissor); int DepthRasterClipIndexedRectangles(int *tx, int *ty, float *tz, const float *transformed, const uint16_t *indexBuffer, const DepthDraw &draw, const DepthScissor scissor); -void DecodeAndTransformForDepthRaster(float *dest, const float *worldviewproj, const void *vertexData, int indexLowerBound, int indexUpperBound, VertexDecoder *dec, u32 vertTypeID); -void TransformPredecodedForDepthRaster(float *dest, const float *worldviewproj, const void *decodedVertexData, VertexDecoder *dec, int count); -void ConvertPredecodedThroughForDepthRaster(float *dest, const void *decodedVertexData, VertexDecoder *dec, int count); +void DecodeAndTransformForDepthRaster(float *dest, const float *worldviewproj, const void *vertexData, int indexLowerBound, int indexUpperBound, const VertexDecoder *dec, u32 vertTypeID); +void TransformPredecodedForDepthRaster(float *dest, const float *worldviewproj, const void *decodedVertexData, const VertexDecoder *dec, int count); +void ConvertPredecodedThroughForDepthRaster(float *dest, const void *decodedVertexData, const VertexDecoder *dec, int count); void DepthRasterScreenVerts(uint16_t *depth, int depthStride, const int *tx, const int *ty, const float *tz, int count, const DepthDraw &draw, const DepthScissor scissor, bool lowQ); diff --git a/GPU/Common/DrawEngineCommon.cpp b/GPU/Common/DrawEngineCommon.cpp index a05e260ffa..17ddffdf82 100644 --- a/GPU/Common/DrawEngineCommon.cpp +++ b/GPU/Common/DrawEngineCommon.cpp @@ -215,7 +215,7 @@ void DrawEngineCommon::UpdatePlanes() { // * Compute min/max of the verts, and then compute a bounding sphere and check that against the planes. // - Less accurate, but.. // - Only requires six plane evaluations then. -bool DrawEngineCommon::TestBoundingBox(const void *vdata, const void *inds, int vertexCount, VertexDecoder *dec, u32 vertType) { +bool DrawEngineCommon::TestBoundingBox(const void *vdata, const void *inds, int vertexCount, const VertexDecoder *dec, u32 vertType) { // Grab temp buffer space from large offsets in decoded_. Not exactly safe for large draws. if (vertexCount > 1024) { return true; @@ -354,7 +354,7 @@ bool DrawEngineCommon::TestBoundingBox(const void *vdata, const void *inds, int // corners. That way we can cull more draws quite cheaply. // We could take the min/max during the regular vertex decode, and just skip the draw call if it's trivially culled. // This would help games like Midnight Club (that one does a lot of out-of-bounds drawing) immensely. -bool DrawEngineCommon::TestBoundingBoxFast(const void *vdata, int vertexCount, VertexDecoder *dec, u32 vertType) { +bool DrawEngineCommon::TestBoundingBoxFast(const void *vdata, int vertexCount, const VertexDecoder *dec, u32 vertType) { SimpleVertex *corners = (SimpleVertex *)(decoded_ + 65536 * 12); float *verts = (float *)(decoded_ + 65536 * 18); @@ -527,7 +527,7 @@ bool DrawEngineCommon::TestBoundingBoxFast(const void *vdata, int vertexCount, V // 2D bounding box test against scissor. No indexing yet. // Only supports non-indexed draws with float positions. -bool DrawEngineCommon::TestBoundingBoxThrough(const void *vdata, int vertexCount, VertexDecoder *dec, u32 vertType) { +bool DrawEngineCommon::TestBoundingBoxThrough(const void *vdata, int vertexCount, const VertexDecoder *dec, u32 vertType) { // Grab temp buffer space from large offsets in decoded_. Not exactly safe for large draws. if (vertexCount > 16) { return true; @@ -607,7 +607,7 @@ int DrawEngineCommon::ComputeNumVertsToDecode() const { // Takes a list of consecutive PRIM opcodes, and extends the current draw call to include them. // This is just a performance optimization. -int DrawEngineCommon::ExtendNonIndexedPrim(const uint32_t *cmd, const uint32_t *stall, VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead, bool isTriangle) { +int DrawEngineCommon::ExtendNonIndexedPrim(const uint32_t *cmd, const uint32_t *stall, const VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead, bool isTriangle) { const uint32_t *start = cmd; int prevDrawVerts = numDrawVerts_ - 1; DeferredVerts &dv = drawVerts_[prevDrawVerts]; @@ -654,7 +654,7 @@ int DrawEngineCommon::ExtendNonIndexedPrim(const uint32_t *cmd, const uint32_t * return cmd - start; } -void DrawEngineCommon::SkipPrim(GEPrimitiveType prim, int vertexCount, VertexDecoder *dec, u32 vertTypeID, int *bytesRead) { +void DrawEngineCommon::SkipPrim(GEPrimitiveType prim, int vertexCount, const VertexDecoder *dec, u32 vertTypeID, int *bytesRead) { if (!indexGen.PrimCompatible(prevPrim_, prim)) { Flush(); } @@ -674,7 +674,7 @@ void DrawEngineCommon::SkipPrim(GEPrimitiveType prim, int vertexCount, VertexDec } // vertTypeID is the vertex type but with the UVGen mode smashed into the top bits. -bool DrawEngineCommon::SubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead) { +bool DrawEngineCommon::SubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, const VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead) { if (!indexGen.PrimCompatible(prevPrim_, prim) || numDrawVerts_ >= MAX_DEFERRED_DRAW_VERTS || numDrawInds_ >= MAX_DEFERRED_DRAW_INDS || vertexCountInDrawCalls_ + vertexCount > VERTEX_BUFFER_MAX) { Flush(); } @@ -771,7 +771,7 @@ void DrawEngineCommon::BeginFrame() { applySkinInDecode_ = g_Config.bSoftwareSkinning; } -void DrawEngineCommon::DecodeVerts(VertexDecoder *dec, u8 *dest) { +void DrawEngineCommon::DecodeVerts(const VertexDecoder *dec, u8 *dest) { if (!numDrawVerts_) { return; } @@ -1025,7 +1025,7 @@ bool DrawEngineCommon::CalculateDepthDraw(DepthDraw *draw, GEPrimitiveType prim, return true; } -void DrawEngineCommon::DepthRasterSubmitRaw(GEPrimitiveType prim, VertexDecoder *dec, uint32_t vertTypeID, int vertexCount) { +void DrawEngineCommon::DepthRasterSubmitRaw(GEPrimitiveType prim, const VertexDecoder *dec, uint32_t vertTypeID, int vertexCount) { if (!gstate.isModeClear() && (!gstate.isDepthTestEnabled() || !gstate.isDepthWriteEnabled())) { return; } @@ -1076,7 +1076,7 @@ void DrawEngineCommon::DepthRasterSubmitRaw(GEPrimitiveType prim, VertexDecoder // FlushQueuedDepth(); } -void DrawEngineCommon::DepthRasterPredecoded(GEPrimitiveType prim, const void *inVerts, int numDecoded, VertexDecoder *dec, int vertexCount) { +void DrawEngineCommon::DepthRasterPredecoded(GEPrimitiveType prim, const void *inVerts, int numDecoded, const VertexDecoder *dec, int vertexCount) { if (!gstate.isModeClear() && (!gstate.isDepthTestEnabled() || !gstate.isDepthWriteEnabled())) { return; } diff --git a/GPU/Common/DrawEngineCommon.h b/GPU/Common/DrawEngineCommon.h index 657da7e685..1a07ea2616 100644 --- a/GPU/Common/DrawEngineCommon.h +++ b/GPU/Common/DrawEngineCommon.h @@ -99,12 +99,12 @@ public: virtual void DispatchSubmitImm(GEPrimitiveType prim, TransformedVertex *buffer, int vertexCount, int cullMode, bool continuation); - bool TestBoundingBox(const void *control_points, const void *inds, int vertexCount, VertexDecoder *dec, u32 vertType); + bool TestBoundingBox(const void *control_points, const void *inds, int vertexCount, const VertexDecoder *dec, u32 vertType); // This is a less accurate version of TestBoundingBox, but faster. Can have more false positives. // Doesn't support indexing. - bool TestBoundingBoxFast(const void *control_points, int vertexCount, VertexDecoder *dec, u32 vertType); - bool TestBoundingBoxThrough(const void *vdata, int vertexCount, VertexDecoder *dec, u32 vertType); + bool TestBoundingBoxFast(const void *control_points, int vertexCount, const VertexDecoder *dec, u32 vertType); + bool TestBoundingBoxThrough(const void *vdata, int vertexCount, const VertexDecoder *dec, u32 vertType); void FlushPartialDecode() { DecodeVerts(dec_, decoded_); @@ -116,9 +116,9 @@ public: } } - int ExtendNonIndexedPrim(const uint32_t *cmd, const uint32_t *stall, VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead, bool isTriangle); - bool SubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead); - void SkipPrim(GEPrimitiveType prim, int vertexCount, VertexDecoder *dec, u32 vertTypeID, int *bytesRead); + int ExtendNonIndexedPrim(const uint32_t *cmd, const uint32_t *stall, const VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead, bool isTriangle); + bool SubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, const VertexDecoder *dec, u32 vertTypeID, bool clockwise, int *bytesRead); + void SkipPrim(GEPrimitiveType prim, int vertexCount, const VertexDecoder *dec, u32 vertTypeID, int *bytesRead); template void SubmitCurve(const void *control_points, const void *indices, Surface &surface, u32 vertType, int *bytesRead, const char *scope); @@ -170,7 +170,7 @@ protected: virtual bool UpdateUseHWTessellation(bool enabled) const { return enabled; } void UpdatePlanes(); - void DecodeVerts(VertexDecoder *dec, u8 *dest); + void DecodeVerts(const VertexDecoder *dec, u8 *dest); int DecodeInds(); int ComputeNumVertsToDecode() const; @@ -179,8 +179,8 @@ protected: void InitDepthRaster(); void ShutdownDepthRaster(); - void DepthRasterSubmitRaw(GEPrimitiveType prim, VertexDecoder *dec, uint32_t vertTypeID, int vertexCount); - void DepthRasterPredecoded(GEPrimitiveType prim, const void *inVerts, int numDecoded, VertexDecoder *dec, int vertexCount); + void DepthRasterSubmitRaw(GEPrimitiveType prim, const VertexDecoder *dec, uint32_t vertTypeID, int vertexCount); + void DepthRasterPredecoded(GEPrimitiveType prim, const void *inVerts, int numDecoded, const VertexDecoder *dec, int vertexCount); bool CalculateDepthDraw(DepthDraw *draw, GEPrimitiveType prim, int vertexCount); static inline int IndexSize(u32 vtype) { @@ -319,7 +319,7 @@ protected: uint32_t drawVertexOffsets_[MAX_DEFERRED_DRAW_VERTS]; DeferredInds drawInds_[MAX_DEFERRED_DRAW_INDS]; - VertexDecoder *dec_ = nullptr; + const VertexDecoder *dec_ = nullptr; u32 lastVType_ = -1; // corresponds to dec_. Could really just pick it out of dec_... int numDrawVerts_ = 0; int numDrawInds_ = 0; diff --git a/GPU/Common/ShaderId.cpp b/GPU/Common/ShaderId.cpp index bac29af015..0ecb1b7359 100644 --- a/GPU/Common/ShaderId.cpp +++ b/GPU/Common/ShaderId.cpp @@ -66,9 +66,7 @@ std::string VertexShaderDesc(const VShaderID &id) { return desc.str(); } -void ComputeVertexShaderID(VShaderID *id_out, VertexDecoder *vertexDecoder, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { - u32 vertType = vertexDecoder->VertexType(); - +void ComputeVertexShaderID(VShaderID *id_out, u32 vertType, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { bool isModeThrough = (vertType & GE_VTYPE_THROUGH) != 0; bool doTexture = gstate.isTextureMapEnabled() && !gstate.isModeClear(); bool doShadeMapping = doTexture && (gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP); @@ -117,7 +115,6 @@ void ComputeVertexShaderID(VShaderID *id_out, VertexDecoder *vertexDecoder, bool } // Bones. - u32 vertType = vertexDecoder->VertexType(); bool enableBones = !useSkinInDecode && vertTypeIsSkinningEnabled(vertType); id.SetBit(VS_BIT_ENABLE_BONES, enableBones); if (enableBones) { diff --git a/GPU/Common/ShaderId.h b/GPU/Common/ShaderId.h index 8141cac442..9c3b295e8b 100644 --- a/GPU/Common/ShaderId.h +++ b/GPU/Common/ShaderId.h @@ -280,9 +280,7 @@ namespace Draw { class Bugs; } -class VertexDecoder; - -void ComputeVertexShaderID(VShaderID *id, VertexDecoder *vertexDecoder, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); +void ComputeVertexShaderID(VShaderID *id, u32 vertType, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); // Generates a compact string that describes the shader. Useful in a list to get an overview // of the current flora of shaders. std::string VertexShaderDesc(const VShaderID &id); diff --git a/GPU/Common/SoftwareTransformCommon.cpp b/GPU/Common/SoftwareTransformCommon.cpp index 6344001fd3..4c8071681f 100644 --- a/GPU/Common/SoftwareTransformCommon.cpp +++ b/GPU/Common/SoftwareTransformCommon.cpp @@ -932,7 +932,7 @@ bool SoftwareTransform::ExpandPoints(int vertexCount, int &maxIndex, int vertsSi // The rest of the transform pipeline like lighting will go as normal, either hardware or software. // The implementation is initially a bit inefficient but shouldn't be a big deal. // An intermediate buffer of not-easy-to-predict size is stored at bufPtr. -u32 NormalizeVertices(SimpleVertex *sverts, u8 *bufPtr, const u8 *inPtr, int lowerBound, int upperBound, VertexDecoder *dec, u32 vertType) { +u32 NormalizeVertices(SimpleVertex *sverts, u8 *bufPtr, const u8 *inPtr, int lowerBound, int upperBound, const VertexDecoder *dec, u32 vertType) { // First, decode the vertices into a GPU compatible format. This step can be eliminated but will need a separate // implementation of the vertex decoder. dec->DecodeVerts(bufPtr, inPtr, &gstate_c.uv, lowerBound, upperBound); diff --git a/GPU/Common/SoftwareTransformCommon.h b/GPU/Common/SoftwareTransformCommon.h index e0f32b11d4..1acb0f799d 100644 --- a/GPU/Common/SoftwareTransformCommon.h +++ b/GPU/Common/SoftwareTransformCommon.h @@ -88,5 +88,5 @@ protected: }; // Slow. See description in the cpp file. -u32 NormalizeVertices(SimpleVertex *sverts, u8 *bufPtr, const u8 *inPtr, int lowerBound, int upperBound, VertexDecoder *dec, u32 vertType); +u32 NormalizeVertices(SimpleVertex *sverts, u8 *bufPtr, const u8 *inPtr, int lowerBound, int upperBound, const VertexDecoder *dec, u32 vertType); bool GetCurrentDrawAsDebugVertices(DrawEngineCommon *drawEngine, int count, std::vector &vertices, std::vector &indices); diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index c3504e2f73..7f51b78310 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -284,7 +284,7 @@ void DrawEngineD3D11::Flush() { D3D11VertexShader *vshader; D3D11FragmentShader *fshader; - shaderManager_->GetShaders(prim, dec_, &vshader, &fshader, pipelineState_, useHWTransform, useHWTessellation_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_); + shaderManager_->GetShaders(prim, dec_->VertexType(), &vshader, &fshader, pipelineState_, useHWTransform, useHWTessellation_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_); ComPtr inputLayout; SetupDecFmtForDraw(vshader, dec_->GetDecVtxFmt(), dec_->VertexType(), &inputLayout); context_->PSSetShader(fshader->GetShader(), nullptr, 0); @@ -331,7 +331,7 @@ void DrawEngineD3D11::Flush() { } } else { PROFILE_THIS_SCOPE("soft"); - VertexDecoder *swDec = dec_; + const VertexDecoder *swDec = dec_; if (swDec->nweights != 0) { u32 withSkinning = lastVType_ | (1 << 26); if (withSkinning != lastVType_) { @@ -420,7 +420,7 @@ void DrawEngineD3D11::Flush() { if (result.action == SW_DRAW_INDEXED) { D3D11VertexShader *vshader; D3D11FragmentShader *fshader; - shaderManager_->GetShaders(prim, swDec, &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat, true); + shaderManager_->GetShaders(prim, swDec->VertexType(), &vshader, &fshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat, true); context_->PSSetShader(fshader->GetShader(), nullptr, 0); context_->VSSetShader(vshader->GetShader(), nullptr, 0); shaderManager_->UpdateUniforms(framebufferManager_->UseBufferedRendering()); diff --git a/GPU/D3D11/ShaderManagerD3D11.cpp b/GPU/D3D11/ShaderManagerD3D11.cpp index 2b06fddf16..3dfd11ce4b 100644 --- a/GPU/D3D11/ShaderManagerD3D11.cpp +++ b/GPU/D3D11/ShaderManagerD3D11.cpp @@ -27,6 +27,7 @@ #include "Common/CommonTypes.h" #include "GPU/GPUState.h" #include "GPU/Common/VertexShaderGenerator.h" +#include "GPU/Common/VertexDecoderCommon.h" #include "GPU/D3D11/ShaderManagerD3D11.h" #include "GPU/D3D11/D3D11Util.h" @@ -162,13 +163,13 @@ void ShaderManagerD3D11::BindUniforms() { context_->PSSetConstantBuffers(0, 1, ps_cbs); } -void ShaderManagerD3D11::GetShaders(int prim, VertexDecoder *decoder, D3D11VertexShader **vshader, D3D11FragmentShader **fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { +void ShaderManagerD3D11::GetShaders(int prim, u32 vertexType, D3D11VertexShader **vshader, D3D11FragmentShader **fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { VShaderID VSID; FShaderID FSID; if (gstate_c.IsDirty(DIRTY_VERTEXSHADER_STATE)) { gstate_c.Clean(DIRTY_VERTEXSHADER_STATE); - ComputeVertexShaderID(&VSID, decoder, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); + ComputeVertexShaderID(&VSID, vertexType, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); } else { VSID = lastVSID_; } diff --git a/GPU/D3D11/ShaderManagerD3D11.h b/GPU/D3D11/ShaderManagerD3D11.h index 1043bca4b6..f773ee27f1 100644 --- a/GPU/D3D11/ShaderManagerD3D11.h +++ b/GPU/D3D11/ShaderManagerD3D11.h @@ -86,7 +86,7 @@ public: ShaderManagerD3D11(Draw::DrawContext *draw, ID3D11Device *device, ID3D11DeviceContext *context, D3D_FEATURE_LEVEL featureLevel); ~ShaderManagerD3D11(); - void GetShaders(int prim, VertexDecoder *decoder, D3D11VertexShader **vshader, D3D11FragmentShader **fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); + void GetShaders(int prim, u32 vertexType, D3D11VertexShader **vshader, D3D11FragmentShader **fshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); void ClearShaders() override; void DirtyLastShader() override; diff --git a/GPU/Directx9/DrawEngineDX9.cpp b/GPU/Directx9/DrawEngineDX9.cpp index 9800667044..37adb1d43f 100644 --- a/GPU/Directx9/DrawEngineDX9.cpp +++ b/GPU/Directx9/DrawEngineDX9.cpp @@ -268,7 +268,7 @@ void DrawEngineDX9::Flush() { ApplyDrawState(prim); ApplyDrawStateLate(); - VSShader *vshader = shaderManager_->ApplyShader(true, useHWTessellation_, dec_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_, pipelineState_); + VSShader *vshader = shaderManager_->ApplyShader(true, useHWTessellation_, dec_->VertexType(), decOptions_.expandAllWeightsToFloat, applySkinInDecode_, pipelineState_); ComPtr pHardwareVertexDecl; SetupDecFmtForDraw(dec_->GetDecVtxFmt(), dec_->VertexType(), &pHardwareVertexDecl); @@ -296,7 +296,7 @@ void DrawEngineDX9::Flush() { DepthRasterSubmitRaw(prim, dec_, dec_->VertexType(), vertexCount); } } else { - VertexDecoder *swDec = dec_; + const VertexDecoder *swDec = dec_; if (swDec->nweights != 0) { u32 withSkinning = lastVType_ | (1 << 26); if (withSkinning != lastVType_) { @@ -386,7 +386,7 @@ void DrawEngineDX9::Flush() { ApplyDrawStateLate(); - VSShader *vshader = shaderManager_->ApplyShader(false, false, swDec, decOptions_.expandAllWeightsToFloat, true, pipelineState_); + VSShader *vshader = shaderManager_->ApplyShader(false, false, swDec->VertexType(), decOptions_.expandAllWeightsToFloat, true, pipelineState_); if (result.action == SW_DRAW_INDEXED) { if (result.setStencil) { diff --git a/GPU/Directx9/ShaderManagerDX9.cpp b/GPU/Directx9/ShaderManagerDX9.cpp index 2ec897cc00..b6e5297d87 100644 --- a/GPU/Directx9/ShaderManagerDX9.cpp +++ b/GPU/Directx9/ShaderManagerDX9.cpp @@ -544,11 +544,11 @@ void ShaderManagerDX9::DirtyLastShader() { gstate_c.Dirty(DIRTY_ALL_UNIFORMS | DIRTY_VERTEXSHADER_STATE | DIRTY_FRAGMENTSHADER_STATE); } -VSShader *ShaderManagerDX9::ApplyShader(bool useHWTransform, bool useHWTessellation, VertexDecoder *decoder, bool weightsAsFloat, bool useSkinInDecode, const ComputedPipelineState &pipelineState) { +VSShader *ShaderManagerDX9::ApplyShader(bool useHWTransform, bool useHWTessellation, u32 vertexType, bool weightsAsFloat, bool useSkinInDecode, const ComputedPipelineState &pipelineState) { VShaderID VSID; if (gstate_c.IsDirty(DIRTY_VERTEXSHADER_STATE)) { gstate_c.Clean(DIRTY_VERTEXSHADER_STATE); - ComputeVertexShaderID(&VSID, decoder, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); + ComputeVertexShaderID(&VSID, vertexType, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); } else { VSID = lastVSID_; } @@ -598,7 +598,7 @@ VSShader *ShaderManagerDX9::ApplyShader(bool useHWTransform, bool useHWTessellat } delete vs; - ComputeVertexShaderID(&VSID, decoder, false, false, weightsAsFloat, useSkinInDecode); + ComputeVertexShaderID(&VSID, vertexType, false, false, weightsAsFloat, useSkinInDecode); // TODO: Look for existing shader with the appropriate ID, use that instead of generating a new one - however, need to make sure // that that shader ID is not used when computing the linked shader ID below, because then IDs won't match diff --git a/GPU/Directx9/ShaderManagerDX9.h b/GPU/Directx9/ShaderManagerDX9.h index c30ca3c912..23c679fe5b 100644 --- a/GPU/Directx9/ShaderManagerDX9.h +++ b/GPU/Directx9/ShaderManagerDX9.h @@ -80,7 +80,7 @@ public: ~ShaderManagerDX9(); void ClearShaders() override; - VSShader *ApplyShader(bool useHWTransform, bool useHWTessellation, VertexDecoder *decoder, bool weightsAsFloat, bool useSkinInDecode, const ComputedPipelineState &pipelineState); + VSShader *ApplyShader(bool useHWTransform, bool useHWTessellation, u32 vertexType, bool weightsAsFloat, bool useSkinInDecode, const ComputedPipelineState &pipelineState); void DirtyLastShader() override; int GetNumVertexShaders() const { return (int)vsCache_.size(); } diff --git a/GPU/GLES/DrawEngineGLES.cpp b/GPU/GLES/DrawEngineGLES.cpp index cb561ae0eb..7c314ff4ee 100644 --- a/GPU/GLES/DrawEngineGLES.cpp +++ b/GPU/GLES/DrawEngineGLES.cpp @@ -253,7 +253,7 @@ void DrawEngineGLES::Flush() { GEPrimitiveType prim = prevPrim_; - Shader *vshader = shaderManager_->ApplyVertexShader(CanUseHardwareTransform(prim), useHWTessellation_, dec_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_ || !CanUseHardwareTransform(prim), &vsid); + Shader *vshader = shaderManager_->ApplyVertexShader(CanUseHardwareTransform(prim), useHWTessellation_, dec_->VertexType(), decOptions_.expandAllWeightsToFloat, applySkinInDecode_ || !CanUseHardwareTransform(prim), &vsid); GLRBuffer *vertexBuffer = nullptr; GLRBuffer *indexBuffer = nullptr; @@ -320,7 +320,7 @@ void DrawEngineGLES::Flush() { } } else { PROFILE_THIS_SCOPE("soft"); - VertexDecoder *swDec = dec_; + const VertexDecoder *swDec = dec_; if (swDec->nweights != 0) { u32 withSkinning = lastVType_ | (1 << 26); if (withSkinning != lastVType_) { diff --git a/GPU/GLES/ShaderManagerGLES.cpp b/GPU/GLES/ShaderManagerGLES.cpp index 830a3d324f..b5453b8abe 100644 --- a/GPU/GLES/ShaderManagerGLES.cpp +++ b/GPU/GLES/ShaderManagerGLES.cpp @@ -778,10 +778,10 @@ Shader *ShaderManagerGLES::CompileVertexShader(VShaderID VSID) { return new Shader(render_, codeBuffer_, desc, params); } -Shader *ShaderManagerGLES::ApplyVertexShader(bool useHWTransform, bool useHWTessellation, VertexDecoder *decoder, bool weightsAsFloat, bool useSkinInDecode, VShaderID *VSID) { +Shader *ShaderManagerGLES::ApplyVertexShader(bool useHWTransform, bool useHWTessellation, u32 vertexType, bool weightsAsFloat, bool useSkinInDecode, VShaderID *VSID) { if (gstate_c.IsDirty(DIRTY_VERTEXSHADER_STATE)) { gstate_c.Clean(DIRTY_VERTEXSHADER_STATE); - ComputeVertexShaderID(VSID, decoder, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); + ComputeVertexShaderID(VSID, vertexType, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); } else { *VSID = lastVSID_; } @@ -814,7 +814,7 @@ Shader *ShaderManagerGLES::ApplyVertexShader(bool useHWTransform, bool useHWTess // Can still work with software transform. VShaderID vsidTemp; - ComputeVertexShaderID(&vsidTemp, decoder, false, false, weightsAsFloat, true); + ComputeVertexShaderID(&vsidTemp, vertexType, false, false, weightsAsFloat, true); vs = CompileVertexShader(vsidTemp); } diff --git a/GPU/GLES/ShaderManagerGLES.h b/GPU/GLES/ShaderManagerGLES.h index 0322863907..5ea181bd29 100644 --- a/GPU/GLES/ShaderManagerGLES.h +++ b/GPU/GLES/ShaderManagerGLES.h @@ -157,6 +157,8 @@ private: uint64_t uniformMask_; }; +class VertexDecoder; + class ShaderManagerGLES : public ShaderManagerCommon { public: ShaderManagerGLES(Draw::DrawContext *draw); @@ -166,7 +168,7 @@ public: // This is the old ApplyShader split into two parts, because of annoying information dependencies. // If you call ApplyVertexShader, you MUST call ApplyFragmentShader soon afterwards. - Shader *ApplyVertexShader(bool useHWTransform, bool useHWTessellation, VertexDecoder *vertexDecoder, bool weightsAsFloat, bool useSkinInDecode, VShaderID *VSID); + Shader *ApplyVertexShader(bool useHWTransform, bool useHWTessellation, u32 vertexType, bool weightsAsFloat, bool useSkinInDecode, VShaderID *VSID); LinkedShader *ApplyFragmentShader(VShaderID VSID, Shader *vs, const ComputedPipelineState &pipelineState, bool useBufferedRendering); void DeviceLost() override; diff --git a/GPU/Vulkan/DrawEngineVulkan.cpp b/GPU/Vulkan/DrawEngineVulkan.cpp index 97431354fe..ec132cce1a 100644 --- a/GPU/Vulkan/DrawEngineVulkan.cpp +++ b/GPU/Vulkan/DrawEngineVulkan.cpp @@ -293,7 +293,7 @@ void DrawEngineVulkan::Flush() { VulkanFragmentShader *fshader = nullptr; VulkanGeometryShader *gshader = nullptr; - shaderManager_->GetShaders(prim, dec_, &vshader, &fshader, &gshader, pipelineState_, true, useHWTessellation_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_); + shaderManager_->GetShaders(prim, dec_->VertexType(), &vshader, &fshader, &gshader, pipelineState_, true, useHWTessellation_, decOptions_.expandAllWeightsToFloat, applySkinInDecode_); _dbg_assert_msg_(vshader->UseHWTransform(), "Bad vshader"); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &dec_->decFmt, vshader, fshader, gshader, true, 0, framebufferManager_->GetMSAALevel(), false); if (!pipeline || !pipeline->pipeline) { @@ -375,7 +375,7 @@ void DrawEngineVulkan::Flush() { } } else { PROFILE_THIS_SCOPE("soft"); - VertexDecoder *swDec = dec_; + const VertexDecoder *swDec = dec_; if (swDec->nweights != 0) { u32 withSkinning = lastVType_ | (1 << 26); if (withSkinning != lastVType_) { @@ -484,7 +484,7 @@ void DrawEngineVulkan::Flush() { VulkanFragmentShader *fshader = nullptr; VulkanGeometryShader *gshader = nullptr; - shaderManager_->GetShaders(prim, swDec, &vshader, &fshader, &gshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat, true); + shaderManager_->GetShaders(prim, swDec->VertexType(), &vshader, &fshader, &gshader, pipelineState_, false, false, decOptions_.expandAllWeightsToFloat, true); _dbg_assert_msg_(!vshader->UseHWTransform(), "Bad vshader"); VulkanPipeline *pipeline = pipelineManager_->GetOrCreatePipeline(renderManager, pipelineLayout_, pipelineKey_, &swDec->decFmt, vshader, fshader, gshader, false, 0, framebufferManager_->GetMSAALevel(), false); if (!pipeline || !pipeline->pipeline) { diff --git a/GPU/Vulkan/ShaderManagerVulkan.cpp b/GPU/Vulkan/ShaderManagerVulkan.cpp index df9b310359..2a29e7cc5a 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.cpp +++ b/GPU/Vulkan/ShaderManagerVulkan.cpp @@ -27,6 +27,7 @@ #include "Common/StringUtils.h" #include "Common/GPU/Vulkan/VulkanContext.h" #include "Common/Log.h" +#include "Common/TimeUtil.h" #include "GPU/GPUState.h" #include "GPU/Common/FragmentShaderGenerator.h" #include "GPU/Common/VertexShaderGenerator.h" @@ -279,14 +280,14 @@ uint64_t ShaderManagerVulkan::UpdateUniforms(bool useBufferedRendering) { return dirty; } -void ShaderManagerVulkan::GetShaders(int prim, VertexDecoder *decoder, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, VulkanGeometryShader **gshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { +void ShaderManagerVulkan::GetShaders(int prim, u32 vertexType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, VulkanGeometryShader **gshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode) { VulkanContext *vulkan = (VulkanContext *)draw_->GetNativeObject(Draw::NativeObject::CONTEXT); VShaderID VSID; VulkanVertexShader *vs = nullptr; if (gstate_c.IsDirty(DIRTY_VERTEXSHADER_STATE)) { gstate_c.Clean(DIRTY_VERTEXSHADER_STATE); - ComputeVertexShaderID(&VSID, decoder, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); + ComputeVertexShaderID(&VSID, vertexType, useHWTransform, useHWTessellation, weightsAsFloat, useSkinInDecode); if (VSID == lastVSID_) { _dbg_assert_(lastVShader_ != nullptr); vs = lastVShader_; diff --git a/GPU/Vulkan/ShaderManagerVulkan.h b/GPU/Vulkan/ShaderManagerVulkan.h index dabe5b7368..fd14c235c0 100644 --- a/GPU/Vulkan/ShaderManagerVulkan.h +++ b/GPU/Vulkan/ShaderManagerVulkan.h @@ -118,7 +118,7 @@ public: void DeviceLost() override; void DeviceRestore(Draw::DrawContext *draw) override; - void GetShaders(int prim, VertexDecoder *decoder, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, VulkanGeometryShader **gshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); + void GetShaders(int prim, u32 vertexType, VulkanVertexShader **vshader, VulkanFragmentShader **fshader, VulkanGeometryShader **gshader, const ComputedPipelineState &pipelineState, bool useHWTransform, bool useHWTessellation, bool weightsAsFloat, bool useSkinInDecode); void ClearShaders() override; void DirtyLastShader() override; From 4e0b6ac3ecb6069373873bfc782b35ddca2524d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 10:04:22 +0200 Subject: [PATCH 10/11] More misc cleanup --- Common/TimeUtil.cpp | 5 ++++- Core/HLE/sceKernel.cpp | 4 ++-- Core/System.cpp | 16 +++++++++------- GPU/Common/VertexDecoderCommon.cpp | 2 +- GPU/GPUState.cpp | 23 +++++++++++++++++++++-- GPU/GPUState.h | 8 +------- GPU/Vulkan/PipelineManagerVulkan.cpp | 3 +-- 7 files changed, 39 insertions(+), 22 deletions(-) diff --git a/Common/TimeUtil.cpp b/Common/TimeUtil.cpp index 8522109d66..5169f71afc 100644 --- a/Common/TimeUtil.cpp +++ b/Common/TimeUtil.cpp @@ -289,7 +289,10 @@ void sleep_precise(double seconds) { LARGE_INTEGER due; due.QuadPart = -(sleepTicks > maxTicks ? maxTicks : sleepTicks); // Note: SetWaitableTimerEx is not available on Vista. - SetWaitableTimer(Timer, &due, 0, NULL, NULL, FALSE); + if (!SetWaitableTimer(Timer, &due, 0, NULL, NULL, FALSE)) { + _dbg_assert_(false); + break; + } WaitForSingleObject(Timer, INFINITE); QueryPerformanceCounter(&qpc); } diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index a20ba965a2..1596ebe618 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -360,11 +360,11 @@ u32 sceKernelDevkitVersion() } u32 sceKernelRegisterKprintfHandler() { - return hleLogError(Log::sceKernel, 0, "UNIMPL"); + return hleLogWarning(Log::sceKernel, 0, "UNIMPL"); } int sceKernelRegisterDefaultExceptionHandler() { - return hleLogError(Log::sceKernel, 0, "UNIMPL"); + return hleLogWarning(Log::sceKernel, 0, "UNIMPL"); } void sceKernelSetGPO(u32 ledBits) { diff --git a/Core/System.cpp b/Core/System.cpp index 4ca9d52a01..88e1a99228 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -582,19 +582,21 @@ bool PSP_InitStart(const CoreParameter &coreParam) { } BootState PSP_InitUpdate(std::string *error_string) { - if (g_bootState == BootState::Booting || g_bootState == BootState::Off) { + const BootState bootState = g_bootState; + + if (bootState == BootState::Booting || bootState == BootState::Off) { // Nothing to do right now. - _dbg_assert_(g_bootState == BootState::Booting || !g_loadingThread.joinable()); - return g_bootState; + _dbg_assert_(bootState == BootState::Booting || !g_loadingThread.joinable()); + return bootState; } - _dbg_assert_(g_bootState == BootState::Complete || g_bootState == BootState::Failed); + _dbg_assert_(bootState == BootState::Complete || bootState == BootState::Failed); // Since we load on a background thread, wait for startup to complete. - _assert_msg_(g_loadingThread.joinable(), "bootstate: %d", (int)g_bootState); + _assert_msg_(g_loadingThread.joinable(), "bootstate: %d", (int)bootState); g_loadingThread.join(); - if (g_bootState == BootState::Failed) { + if (bootState == BootState::Failed) { // Failed! (Note: PSP_Shutdown was already called on the loader thread). Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); *error_string = g_CoreParameter.errorString; @@ -627,7 +629,7 @@ BootState PSP_InitUpdate(std::string *error_string) { Core_NotifyLifecycle(CoreLifecycle::START_COMPLETE); // The thread should have set it at this point. - _dbg_assert_(g_bootState == BootState::Complete); + _dbg_assert_(bootState == BootState::Complete); return BootState::Complete; } diff --git a/GPU/Common/VertexDecoderCommon.cpp b/GPU/Common/VertexDecoderCommon.cpp index 460f18c119..11a75d1269 100644 --- a/GPU/Common/VertexDecoderCommon.cpp +++ b/GPU/Common/VertexDecoderCommon.cpp @@ -107,7 +107,7 @@ void DecVtxFormat::InitializeFromID(uint32_t id) { void GetIndexBounds(const void *inds, int count, u32 vertType, u16 *indexLowerBound, u16 *indexUpperBound) { // Find index bounds. Could cache this in display lists. // Also, this could be greatly sped up with SSE2/NEON, although rarely a bottleneck, and some compilers - // autovectorize this just fine. + // autovectorize this just fine. (Though, it should be noted, MSVC generates really crap code here...). u32 idx = vertType & GE_VTYPE_IDX_MASK; if (idx == GE_VTYPE_IDX_16BIT) { uint16_t upperBound = 0; diff --git a/GPU/GPUState.cpp b/GPU/GPUState.cpp index 1049b8be96..010430c597 100644 --- a/GPU/GPUState.cpp +++ b/GPU/GPUState.cpp @@ -362,7 +362,7 @@ void GPUStateCache::DoState(PointerWrap &p) { gstate_c.Dirty(DIRTY_CULL_PLANES); } -static const char *const gpuUseFlagNames[32] = { +static const char *const g_gpuUseFlagNames[32] = { "GPU_USE_DUALSOURCE_BLEND", "GPU_USE_LIGHT_UBERSHADER", "GPU_USE_FRAGMENT_TEST_CACHE", @@ -399,8 +399,27 @@ static const char *const gpuUseFlagNames[32] = { const char *GpuUseFlagToString(int useFlag) { if ((u32)useFlag < 32) { - return gpuUseFlagNames[useFlag]; + return g_gpuUseFlagNames[useFlag]; } else { return "N/A"; } } + +bool GPUStateCache::SetUseFlags(const u32 newFlags) { + if (newFlags != useFlags_) { + if (useFlags_ != 0 && newFlags != 0) { + INFO_LOG(Log::G3D, "Shader useflags changed from %08x to %08x:", useFlags_, newFlags); + for (int i = 0; i < 32; i++) { + const int mask = 1 << i; + bool oldVal = (useFlags_ & mask) != 0; + bool newVal = (newFlags & mask) != 0; + if (oldVal != newVal) { + INFO_LOG(Log::G3D, "%s changed from %d to %d", g_gpuUseFlagNames[i], (int)oldVal, (int)newVal); + } + } + useFlagsChanged = true; + } + useFlags_ = newFlags; + } + return useFlagsChanged; +} diff --git a/GPU/GPUState.h b/GPU/GPUState.h index 0cb0517028..b7427b7d1f 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -578,13 +578,7 @@ struct GPUStateCache { Dirty(DIRTY_UVSCALEOFFSET); } } - void SetUseFlags(u32 newFlags) { - if (newFlags != useFlags_) { - if (useFlags_ != 0) - useFlagsChanged = true; - useFlags_ = newFlags; - } - } + bool SetUseFlags(u32 newFlags); // When checking for a single flag, use Use()/UseAll(). u32 GetUseFlags() const { diff --git a/GPU/Vulkan/PipelineManagerVulkan.cpp b/GPU/Vulkan/PipelineManagerVulkan.cpp index 06cbcc83c6..4954087149 100644 --- a/GPU/Vulkan/PipelineManagerVulkan.cpp +++ b/GPU/Vulkan/PipelineManagerVulkan.cpp @@ -833,7 +833,6 @@ bool PipelineManagerVulkan::LoadPipelineCache(FILE *file, bool loadRawPipelineCa rm->NudgeCompilerThread(); - NOTICE_LOG(Log::G3D, "Recreated Vulkan pipeline cache (%d pipelines, %d failed).", (int)size, pipelineCreateFailCount); - // We just ignore any failures. + // The rest of the work is async, we can't know here if it'll succeed. return true; } From c9bab212a37885d509795282b48dada64478280f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Wed, 14 May 2025 10:08:16 +0200 Subject: [PATCH 11/11] Make Read_Instruction safer --- Core/MemMap.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/Core/MemMap.cpp b/Core/MemMap.cpp index 0d0cfbe990..c090e1ebf2 100644 --- a/Core/MemMap.cpp +++ b/Core/MemMap.cpp @@ -418,8 +418,7 @@ MemoryInitedLock Lock() return MemoryInitedLock(); } -__forceinline static Opcode Read_Instruction(u32 address, bool resolveReplacements, Opcode inst) -{ +static Opcode Read_Instruction(u32 address, bool resolveReplacements, Opcode inst) { if (!MIPS_IS_EMUHACK(inst.encoding)) { return inst; } @@ -458,14 +457,19 @@ __forceinline static Opcode Read_Instruction(u32 address, bool resolveReplacemen } } -Opcode Read_Instruction(u32 address, bool resolveReplacements) -{ - Opcode inst = Opcode(Read_U32(address)); +Opcode Read_Instruction(u32 address, bool resolveReplacements) { + if (!IsValid4AlignedAddress(address)) { + // BAD! + _dbg_assert_(false); + return Opcode(0); + } + + Opcode inst = Opcode(ReadUnchecked_U32(address)); return Read_Instruction(address, resolveReplacements, inst); } -Opcode ReadUnchecked_Instruction(u32 address, bool resolveReplacements) -{ +Opcode ReadUnchecked_Instruction(u32 address, bool resolveReplacements) { + _dbg_assert_((address & 3) == 0); Opcode inst = Opcode(ReadUnchecked_U32(address)); return Read_Instruction(address, resolveReplacements, inst); } @@ -482,10 +486,9 @@ Opcode Read_Opcode_JIT(u32 address) } // WARNING! No checks! -// We assume that _Address is cached -void Write_Opcode_JIT(const u32 _Address, const Opcode& _Value) -{ - Memory::WriteUnchecked_U32(_Value.encoding, _Address); +void Write_Opcode_JIT(const u32 address, const Opcode& _Value) { + _dbg_assert_((address & 3) == 0); + Memory::WriteUnchecked_U32(_Value.encoding, address); } void Memset(const u32 _Address, const u8 _iValue, const u32 _iLength, const char *tag) {