From ee678536362c56f38f9a7010abb8bd4c2e174265 Mon Sep 17 00:00:00 2001 From: crueter Date: Thu, 26 Feb 2026 01:04:14 +0100 Subject: [PATCH 001/145] [desktop] Show basic driver info on GPU selector box (#3636) Shows a short driver identification string in the Graphics Device combo box (desktop only, Android doesn't need this at all) Largely meant for debugging, especially macOS. Maybe Windows in the future once MESA begins working on FOSS drivers over there. Linux on ARM platforms too maybe? And Nvidia Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3636 Reviewed-by: DraVee Reviewed-by: MaranBr --- .../vulkan_common/vulkan_device.cpp | 51 +-------------- .../vulkan_common/vulkan_wrapper.cpp | 62 ++++++++++++++++++- src/video_core/vulkan_common/vulkan_wrapper.h | 6 +- src/yuzu/vk_device_info.cpp | 15 ++++- 4 files changed, 79 insertions(+), 55 deletions(-) diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index 8cb2ebfb62..3d98f2cbf7 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -850,56 +850,7 @@ bool Device::IsFormatSupported(VkFormat wanted_format, VkFormatFeatureFlags want } std::string Device::GetDriverName() const { - switch (properties.driver.driverID) { - case VK_DRIVER_ID_AMD_PROPRIETARY: - return "AMD"; - case VK_DRIVER_ID_AMD_OPEN_SOURCE: - return "AMDVLK"; - case VK_DRIVER_ID_MESA_RADV: - return "RADV"; - case VK_DRIVER_ID_NVIDIA_PROPRIETARY: - return "NVIDIA"; - case VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS: - return "Intel"; - case VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA: - return "ANV"; - case VK_DRIVER_ID_IMAGINATION_PROPRIETARY: - return "PowerVR"; - case VK_DRIVER_ID_QUALCOMM_PROPRIETARY: - return "Qualcomm"; - case VK_DRIVER_ID_ARM_PROPRIETARY: - return "Mali"; - case VK_DRIVER_ID_SAMSUNG_PROPRIETARY: - return "Xclipse"; - case VK_DRIVER_ID_GOOGLE_SWIFTSHADER: - return "SwiftShader"; - case VK_DRIVER_ID_BROADCOM_PROPRIETARY: - return "Broadcom"; - case VK_DRIVER_ID_MESA_LLVMPIPE: - return "Lavapipe"; - case VK_DRIVER_ID_MOLTENVK: - return "MoltenVK"; - case VK_DRIVER_ID_VERISILICON_PROPRIETARY: - return "Vivante"; - case VK_DRIVER_ID_MESA_TURNIP: - return "Turnip"; - case VK_DRIVER_ID_MESA_V3DV: - return "V3DV"; - case VK_DRIVER_ID_MESA_PANVK: - return "PanVK"; - case VK_DRIVER_ID_MESA_VENUS: - return "Venus"; - case VK_DRIVER_ID_MESA_DOZEN: - return "Dozen"; - case VK_DRIVER_ID_MESA_NVK: - return "NVK"; - case VK_DRIVER_ID_IMAGINATION_OPEN_SOURCE_MESA: - return "PVR"; - // case VK_DRIVER_ID_MESA_AGXV: - // return "Asahi"; - default: - return properties.driver.driverName; - } + return vk::GetDriverName(properties.driver); } bool Device::ShouldBoostClocks() const { diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp index 534a11edd4..926f48de89 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.cpp +++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -1012,4 +1012,64 @@ std::optional> EnumerateInstanceLayerProperties( return properties; } +std::string GetDriverName(VkPhysicalDeviceDriverProperties driver) { + switch (driver.driverID) { + case VK_DRIVER_ID_AMD_PROPRIETARY: + return "AMD"; + case VK_DRIVER_ID_AMD_OPEN_SOURCE: + return "AMDVLK"; + case VK_DRIVER_ID_MESA_RADV: + return "RADV"; + case VK_DRIVER_ID_NVIDIA_PROPRIETARY: + return "Nvidia"; + case VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS: + return "Intel"; + case VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA: + return "ANV"; + case VK_DRIVER_ID_IMAGINATION_PROPRIETARY: + return "PowerVR"; + case VK_DRIVER_ID_QUALCOMM_PROPRIETARY: + return "Qualcomm"; + case VK_DRIVER_ID_ARM_PROPRIETARY: + return "Mali"; + case VK_DRIVER_ID_SAMSUNG_PROPRIETARY: + return "Xclipse"; + case VK_DRIVER_ID_GOOGLE_SWIFTSHADER: + return "SwiftShader"; + case VK_DRIVER_ID_BROADCOM_PROPRIETARY: + return "Broadcom"; + case VK_DRIVER_ID_MESA_LLVMPIPE: + return "llvmpipe"; + case VK_DRIVER_ID_MOLTENVK: + return "MoltenVK"; + case VK_DRIVER_ID_VERISILICON_PROPRIETARY: + return "Vivante"; + case VK_DRIVER_ID_MESA_TURNIP: + return "Turnip"; + case VK_DRIVER_ID_MESA_V3DV: + return "V3DV"; + case VK_DRIVER_ID_MESA_PANVK: + return "PanVK"; + case VK_DRIVER_ID_MESA_VENUS: + return "Venus"; + case VK_DRIVER_ID_MESA_DOZEN: + return "Dozen"; + case VK_DRIVER_ID_MESA_NVK: + return "NVK"; + case VK_DRIVER_ID_IMAGINATION_OPEN_SOURCE_MESA: + return "PVR"; + case VK_DRIVER_ID_MESA_HONEYKRISP: + return "HoneyKrisp"; + case VK_DRIVER_ID_MESA_KOSMICKRISP: + return "KosmicKrisp"; + case VK_DRIVER_ID_GGP_PROPRIETARY: + case VK_DRIVER_ID_COREAVI_PROPRIETARY: + case VK_DRIVER_ID_JUICE_PROPRIETARY: + case VK_DRIVER_ID_VULKAN_SC_EMULATION_ON_VULKAN: + case VK_DRIVER_ID_MAX_ENUM: + default: + return driver.driverName; + } +} + } // namespace Vulkan::vk diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h index 04b9420d98..5c04132f7b 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.h +++ b/src/video_core/vulkan_common/vulkan_wrapper.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include "common/common_types.h" #include "video_core/vulkan_common/vulkan.h" @@ -1601,4 +1603,6 @@ std::optional> EnumerateInstanceExtensionProp std::optional> EnumerateInstanceLayerProperties( const InstanceDispatch& dld); +std::string GetDriverName(VkPhysicalDeviceDriverProperties driver); + } // namespace Vulkan::vk diff --git a/src/yuzu/vk_device_info.cpp b/src/yuzu/vk_device_info.cpp index d961d550a1..45faecb95d 100644 --- a/src/yuzu/vk_device_info.cpp +++ b/src/yuzu/vk_device_info.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2023 yuzu Emulator Project @@ -47,7 +47,8 @@ void PopulateRecords(std::vector& records, QWindow* window) try { records.reserve(physical_devices.size()); for (const VkPhysicalDevice device : physical_devices) { const auto physical_device = vk::PhysicalDevice(device, dld); - const std::string name = physical_device.GetProperties().deviceName; + std::string name = physical_device.GetProperties().deviceName; + const std::vector present_modes = physical_device.GetSurfacePresentModesKHR(*surface); @@ -59,8 +60,16 @@ void PopulateRecords(std::vector& records, QWindow* window) try { properties.pNext = &driver_properties; dld.vkGetPhysicalDeviceProperties2(physical_device, &properties); + const auto driverID = driver_properties.driverID; + bool has_broken_compute{Vulkan::Device::CheckBrokenCompute( - driver_properties.driverID, properties.properties.driverVersion)}; + driverID, properties.properties.driverVersion)}; + + std::string driver_string = Vulkan::vk::GetDriverName(driver_properties); + + if (driver_string.empty()) driver_string = "Unknown"; + + name = fmt::format("{} ({})", name, driver_string); records.push_back(VkDeviceInfo::Record(name, present_modes, has_broken_compute)); } From f957c36238103bf3dc88bc6105991fcea3b8ad54 Mon Sep 17 00:00:00 2001 From: crueter Date: Thu, 26 Feb 2026 01:04:23 +0100 Subject: [PATCH 002/145] [vk] Disable vsync when Turbo Mode is enabled (#3633) Note to self: you have a 60Hz display, use it Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3633 Reviewed-by: DraVee Reviewed-by: MaranBr --- src/video_core/renderer_vulkan/vk_swapchain.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/video_core/renderer_vulkan/vk_swapchain.cpp b/src/video_core/renderer_vulkan/vk_swapchain.cpp index 89aa6c4628..b89e981444 100644 --- a/src/video_core/renderer_vulkan/vk_swapchain.cpp +++ b/src/video_core/renderer_vulkan/vk_swapchain.cpp @@ -10,9 +10,8 @@ #include #include "common/logging/log.h" -#include #include "common/settings.h" -#include "core/core.h" +#include "common/settings_enums.h" #include "video_core/renderer_vulkan/vk_scheduler.h" #include "video_core/renderer_vulkan/vk_swapchain.h" #include "video_core/vulkan_common/vk_enum_string_helper.h" @@ -45,7 +44,8 @@ static VkPresentModeKHR ChooseSwapPresentMode(bool has_imm, bool has_mailbox, Settings::VSyncMode setting = [has_imm, has_mailbox]() { // Choose Mailbox or Immediate if unlocked and those modes are supported const auto mode = Settings::values.vsync_mode.GetValue(); - if (Settings::values.use_speed_limit.GetValue()) { + if (Settings::values.use_speed_limit.GetValue() && + Settings::values.current_speed_mode.GetValue() != Settings::SpeedMode::Turbo) { return mode; } switch (mode) { From 04e88ab82cd92c449e04d7a6114f607ca0289294 Mon Sep 17 00:00:00 2001 From: PavelBARABANOV Date: Thu, 26 Feb 2026 03:15:32 +0100 Subject: [PATCH 003/145] [qt] Remove QEvent::Polish from titlebar filter to fix Applets tab (#3644) Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3644 Reviewed-by: MaranBr Reviewed-by: crueter Co-authored-by: PavelBARABANOV Co-committed-by: PavelBARABANOV --- src/yuzu/main_window.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/yuzu/main_window.cpp b/src/yuzu/main_window.cpp index e19f2def95..6ead3c4130 100644 --- a/src/yuzu/main_window.cpp +++ b/src/yuzu/main_window.cpp @@ -220,7 +220,6 @@ struct TitlebarFilter final : QObject { case QEvent::WinIdChange: case QEvent::Show: case QEvent::ShowToParent: - case QEvent::Polish: case QEvent::WindowStateChange: case QEvent::ZOrderChange: ApplyDarkToTopLevel(w, dark); From 0d950195e9cfbd89a3fb69e784437f3cc5c3e88e Mon Sep 17 00:00:00 2001 From: John Date: Thu, 26 Feb 2026 03:57:25 +0100 Subject: [PATCH 004/145] [Settings] Add "Enable Legacy Rescale Pass" Toggle (#3582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR introduces an optional Legacy Rescale Compatibility Mode that restores the previous rescale‑pass behavior for titles that rely on its quirks. While the new rescale logic is generally more correct, some games exhibit visual issues that the legacy behavior incidentally avoids. Enabling this mode can mitigate line artifacts on AMD GPUs and reduce grey‑texture flickering on Nvidia GPUs in Luigi’s Mansion 3. This is a compatibility workaround rather than a full fix, and should only be used for titles affected by these rare edge‑case rendering problems. Original Logic from MaranBR Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3582 Co-authored-by: John Co-committed-by: John --- src/common/settings.h | 3 +++ src/qt_common/config/shared_translation.cpp | 6 ++++++ .../frontend/maxwell/translate_program.cpp | 2 +- src/shader_recompiler/ir_opt/rescaling_pass.cpp | 17 ++++++++++++----- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/common/settings.h b/src/common/settings.h index dd3cd14a02..7ea4136576 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -557,6 +557,9 @@ struct Values { SwitchableSetting fix_bloom_effects{linkage, false, "fix_bloom_effects", Category::RendererHacks}; + SwitchableSetting rescale_hack{linkage, false, "rescale_hack", + Category::RendererHacks}; + SwitchableSetting use_asynchronous_shaders{linkage, false, "use_asynchronous_shaders", Category::RendererHacks}; diff --git a/src/qt_common/config/shared_translation.cpp b/src/qt_common/config/shared_translation.cpp index 9d33fa6979..5f3a6c18c0 100644 --- a/src/qt_common/config/shared_translation.cpp +++ b/src/qt_common/config/shared_translation.cpp @@ -356,6 +356,12 @@ std::unique_ptr InitializeTranslations(QObject* parent) tr("Fix bloom effects"), tr("Removes bloom in Burnout.")); + INSERT(Settings, + rescale_hack, + tr("Enable Legacy Rescale Pass"), + tr("May fix rescale issues in some games by relying on behavior from the previous implementation.\n" + "Legacy behavior workaround that fixes AMD GPU line artifacts and Nvidia GPU grey texture flicker in Luigis Mansion 3.")); + // Renderer (Extensions) INSERT(Settings, dyna_state, tr("Extended Dynamic State"), tr("Controls the number of features that can be used in Extended Dynamic State.\n" diff --git a/src/shader_recompiler/frontend/maxwell/translate_program.cpp b/src/shader_recompiler/frontend/maxwell/translate_program.cpp index 81aee6453a..f156192c13 100644 --- a/src/shader_recompiler/frontend/maxwell/translate_program.cpp +++ b/src/shader_recompiler/frontend/maxwell/translate_program.cpp @@ -304,7 +304,7 @@ IR::Program TranslateProgram(ObjectPool& inst_pool, ObjectPool Date: Thu, 26 Feb 2026 16:48:04 +0100 Subject: [PATCH 005/145] [hle] Implement IApplicationManagerInterface::GetTotalSpaceSize (#3642) oops Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3642 Reviewed-by: MaranBr Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- .../hle/service/ns/application_manager_interface.cpp | 10 +++++++--- .../hle/service/ns/application_manager_interface.h | 1 + 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/core/hle/service/ns/application_manager_interface.cpp b/src/core/hle/service/ns/application_manager_interface.cpp index bed5057f37..5490c09d03 100644 --- a/src/core/hle/service/ns/application_manager_interface.cpp +++ b/src/core/hle/service/ns/application_manager_interface.cpp @@ -67,7 +67,7 @@ IApplicationManagerInterface::IApplicationManagerInterface(Core::System& system_ {44, D<&IApplicationManagerInterface::GetSdCardMountStatusChangedEvent>, "GetSdCardMountStatusChangedEvent"}, {45, nullptr, "GetGameCardAttachmentEvent"}, {46, nullptr, "GetGameCardAttachmentInfo"}, - {47, nullptr, "GetTotalSpaceSize"}, + {47, D<&IApplicationManagerInterface::GetTotalSpaceSize>, "GetTotalSpaceSize"}, {48, D<&IApplicationManagerInterface::GetFreeSpaceSize>, "GetFreeSpaceSize"}, {49, nullptr, "GetSdCardRemovedEvent"}, {52, D<&IApplicationManagerInterface::GetGameCardUpdateDetectionEvent>, "GetGameCardUpdateDetectionEvent"}, @@ -751,8 +751,12 @@ Result IApplicationManagerInterface::GetSdCardMountStatusChangedEvent( R_SUCCEED(); } -Result IApplicationManagerInterface::GetFreeSpaceSize(Out out_free_space_size, - FileSys::StorageId storage_id) { +Result IApplicationManagerInterface::GetTotalSpaceSize(Out out_total_space_size, FileSys::StorageId storage_id) { + LOG_DEBUG(Service_NS, "called"); + R_RETURN(IContentManagementInterface(system).GetTotalSpaceSize(out_total_space_size, storage_id)); +} + +Result IApplicationManagerInterface::GetFreeSpaceSize(Out out_free_space_size, FileSys::StorageId storage_id) { LOG_DEBUG(Service_NS, "called"); R_RETURN(IContentManagementInterface(system).GetFreeSpaceSize(out_free_space_size, storage_id)); } diff --git a/src/core/hle/service/ns/application_manager_interface.h b/src/core/hle/service/ns/application_manager_interface.h index ffb744d3fa..245d59a068 100644 --- a/src/core/hle/service/ns/application_manager_interface.h +++ b/src/core/hle/service/ns/application_manager_interface.h @@ -50,6 +50,7 @@ public: u32 flags, u64 application_id, Uid account_id); Result CheckSdCardMountStatus(); Result GetSdCardMountStatusChangedEvent(OutCopyHandle out_event); + Result GetTotalSpaceSize(Out out_total_space_size, FileSys::StorageId storage_id); Result GetFreeSpaceSize(Out out_free_space_size, FileSys::StorageId storage_id); Result GetGameCardUpdateDetectionEvent(OutCopyHandle out_event); Result ResumeAll(); From bf25058dbdbaafe16377f78f307f65a1b5399d8b Mon Sep 17 00:00:00 2001 From: crueter Date: Fri, 27 Feb 2026 03:33:29 +0100 Subject: [PATCH 006/145] [docs] SIGNUP: Add spam/junk notice, email patch info, and clarify some things (#3648) Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3648 --- docs/SIGNUP.md | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/SIGNUP.md b/docs/SIGNUP.md index 6995db6d9a..5e5f7cebf6 100644 --- a/docs/SIGNUP.md +++ b/docs/SIGNUP.md @@ -18,7 +18,7 @@ First of all, you MUST have a valid reason to sign up for our Git. Valid reasons The following are not valid reasons to sign up: - I want to contribute to Eden. - * Be at least somewhat specific! + * Be at least somewhat specific! We always welcome contributors and developers, but generic "I want to contribute" messages don't give us enough information. - I want to support Eden. * If you wish to support us through development, be more specific; otherwise, to support us, check out our [donations page](https://eden-emu.dev/donations). - I want to report issues. @@ -41,17 +41,36 @@ Email: I wish to sign up because... ``` -Email notifications are disabled for the time being, so you don't have to use a real email. If you wish to remain anonymous, either send a separate email asking for access to a shared anonymous account, *or* create a fake username and email. +Email notifications are disabled for the time being, so you don't have to use a real email. If you wish to remain anonymous, either send a separate email asking for access to a shared anonymous account, *or* create a fake username and email. Do note that the email you sign up with is used to accredit commits on the web UI, and *must* match your configured GPG key. + +## Patches + +In general, PRs are the preferred method of tracking patches, as they allow us to go through our standard triage, CI, and testing process without having to deal with the minutiae of incremental patches. However, we also understand that many people prefer to use raw patches, and that's totally okay! While we currently don't have a mailing list, we do accept email patches. To do so: + +1. Make your changes on a clean copy of the master branch +2. Commit your changes with a descriptive, well-formed message (see the [commit message docs](https://git.eden-emu.dev/eden-emu/eden/src/branch/master/docs/Development.md#pull-requests)), and a proper description thoroughly explaining your changes. + * Note that we don't need to know all the individual details about your code. A description explaining the motivation and general implementation of your changes is enough, alongside caveats and any potential blockers. +3. Format your patch with `git format-patch -1 HEAD`. +4. Email us with the subject `[Eden] [PATCH] `, with a brief description of your patch, and the previously-formatted patch file as an attachment. + * If you don't include the first two bracketed parts, your email may be lost! + +The following emails are currently set up to receive and process patches: + +- [eden@eden-emu.dev](mailto:eden@eden-emu.dev] +- [crueter@eden-emu.dev](mailto:eden@eden-emu.dev) ## Instructions If you have read everything above and affirm that you will not abuse your access, click the summary below to get the email to send your request to.
-I affirm that I have read ALL of the information above, and will not abuse my access to Eden, nor will I send unnecessary spam requests or the following email. +I affirm that I have read ALL of the information above, and will not abuse my access to Eden, nor will I send unnecessary spam to the following email. Email [crueter@crueter.xyz](mailto:crueter@crueter.xyz) with the format above. Once your request is processed, you should receive a confirmation email from crueter with your password alongside a link to a repository containing instructions on SSH, etc. Note that you are required to change your password. If your request is rejected, you will receive a notice as such, asking for clarification if needed. If you do not receive a response in 48 hours, you may send another email. -
\ No newline at end of file +> [!WARNING] +> Some email providers may place the response email in your spam/junk folder; notable offenders include Gmail and Outlook. *Always* ensure to check your Spam/Junk folder, until Google/Microsoft finally end their vendetta against the great evil of my `.xyz` domain. + + From fc63de39dd4e1bd1bb4d0cee5808bb8f38598fa8 Mon Sep 17 00:00:00 2001 From: crueter Date: Fri, 27 Feb 2026 03:33:36 +0100 Subject: [PATCH 007/145] [docs] Bring back the Options page, and clean up LLM policy (#3649) Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3649 --- docs/Options.md | 100 ++++++++++++++++++++++++++++++++++++++++++++ docs/README.md | 1 + docs/policies/AI.md | 9 +++- 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 docs/Options.md diff --git a/docs/Options.md b/docs/Options.md new file mode 100644 index 0000000000..55aead805f --- /dev/null +++ b/docs/Options.md @@ -0,0 +1,100 @@ +# CMake Options + +To change these options, add `-DOPTION_NAME=NEWVALUE` to the command line. + +- On Qt Creator, go to Project -> Current Configuration + +Notes: + +- Defaults are marked per-platform. +- "Non-UNIX" just means Windows/MSVC and Android (yes, macOS is UNIX +- Android generally doesn't need to change anything; if you do, go to `src/android/app/build.gradle.kts` +- To set a boolean variable to on, use `ON` for the value; to turn it off, use `OFF` +- If a variable is mentioned as being e.g. "ON" for a specific platform(s), that means it is defaulted to OFF on others +- TYPE is always boolean unless otherwise specified +- Format: + - `OPTION_NAME` (TYPE DEFAULT) DESCRIPTION + +## Options + +### Dependencies + +These options control dependencies. + +- `YUZU_USE_BUNDLED_FFMPEG` (ON for non-UNIX) Download a pre-built and configured FFmpeg +- `YUZU_USE_EXTERNAL_FFMPEG` (ON for Solaris) Build FFmpeg from source +- `YUZU_DOWNLOAD_ANDROID_VVL` (ON) Download validation layer binary for Android +- `YUZU_DOWNLOAD_TIME_ZONE_DATA` (ON) Always download time zone binaries + - Currently, build fails without this +- `YUZU_TZDB_PATH` (string) Path to a pre-downloaded timezone database (useful for nixOS and Gentoo) +- `YUZU_USE_BUNDLED_MOLTENVK` (ON, macOS only) Download bundled MoltenVK lib +- `YUZU_USE_BUNDLED_OPENSSL` (ON for MSVC, Android, Solaris, and OpenBSD) Download bundled OpenSSL build +- `YUZU_USE_EXTERNAL_SDL2` (OFF) Compiles SDL2 from source +- `YUZU_USE_BUNDLED_SDL2` (ON for MSVC) Download a prebuilt SDL2 + +### Miscellaneous + +- `ENABLE_WEB_SERVICE` (ON) Enable multiplayer service +- `ENABLE_WIFI_SCAN` (OFF) Enable WiFi scanning (requires iw on Linux) - experimental +- `ENABLE_CUBEB` (ON) Enables the cubeb audio backend + - This option is subject for removal. +- `YUZU_TESTS` (ON) Compile tests - requires Catch2 +- `ENABLE_LTO` (OFF) Enable link-time optimization + - Not recommended on Windows + - UNIX may be better off appending `-flto=thin` to compiler args +- `USE_FASTER_LINKER` (OFF) Check if a faster linker is available + - Not recommended outside of Linux + +### Flavors + +These options control executables and build flavors. + +- `YUZU_LEGACY` (OFF): Apply patches to improve compatibility on some older GPUs at the cost of performance +- `NIGHTLY_BUILD` (OFF): This is only used by CI. Do not use this unless you're making your own distribution and know what you're doing. +- `YUZU_STATIC_BUILD` (OFF) Attempt to build using static libraries if possible + - Not supported on Linux + - Automatically set if `YUZU_USE_BUNDLED_QT` is on for non-Linux +- `ENABLE_UPDATE_CHECKER` (OFF) Enable update checking functionality +- `YUZU_DISABLE_LLVM` (OFF) Do not attempt to link to the LLVM demangler + - Really only useful for CI or distribution builds + +**Desktop only**: + +- `YUZU_CMD` (ON) Compile the SDL2 frontend (eden-cli) +- `YUZU_ROOM` (OFF) Compile dedicated room functionality into the main executable +- `YUZU_ROOM_STANDALONE` (OFF) Compile a separate executable for room functionality +- `YUZU_STATIC_ROOM` (OFF) Compile the room executable *only* as a static, portable executable + - This is only usable on Alpine Linux. + +### Desktop + +The following options are desktop only. + +- `ENABLE_LIBUSB` (ON) Enable the use of the libusb input frontend (HIGHLY RECOMMENDED) +- `ENABLE_OPENGL` (ON) Enable the OpenGL graphics frontend + - Unavailable on Windows/ARM64 + - You probably shouldn't turn this off. + +### Qt + +Also desktop-only, but apply strictly to Qt + +- `ENABLE_QT` (ON) Enable the Qt frontend (recommended) +- `ENABLE_QT_TRANSLATION` (OFF) Enable translations for the Qt frontend +- `YUZU_USE_BUNDLED_QT` (ON for MSVC) Download bundled Qt binaries + - Not recommended on Linux. For Windows and macOS, the provided build is statically linked. +- `YUZU_QT_MIRROR` (string) What mirror to use for downloading the bundled Qt libraries +- `YUZU_USE_QT_MULTIMEDIA` (OFF) Use QtMultimedia for camera support +- `YUZU_USE_QT_WEB_ENGINE` (OFF) Use QtWebEngine for web applet implementation (requires the huge QtWebEngine dependency; not recommended) +- `USE_DISCORD_PRESENCE` (OFF) Enables Discord Rich Presence (Qt frontend only) + +### Retired Options + +The following options were a part of Eden at one point, but have since been retired. + +- `ENABLE_OPENSSL` - MbedTLS was fully replaced with OpenSSL in [#3606](https://git.eden-emu.dev/eden-emu/eden/pulls/3606), because OpenSSL straight-up performs better. +- `ENABLE_SDL2` - While technically possible to *not* use SDL2 on desktop, this is **NOT** a supported configuration under any means, and adding this matrix to our build system was not worth the effort. +- `YUZU_USE_CPM` - This option once had a purpose, but that purpose has long since passed us by. *All* builds use CPMUtil to manage dependencies now. + - If you want to *force* the usage of system dependencies, use `-DCPMUTIL_FORCE_SYSTEM=ON`. + +See `src/dynarmic/CMakeLists.txt` for additional options--usually, these don't need changed diff --git a/docs/README.md b/docs/README.md index 5af1ac8345..01727ae4dc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,6 +3,7 @@ This contains documentation created by developers. This contains build instructions, guidelines, instructions/layouts for [cool stuff we made](./CPMUtil), and more. - **[General Build Instructions](Build.md)** +- **[CMake Options](Options.md)** - **[Cross Compiling](CrossCompile.md)** - **[Development Guidelines](Development.md)** - **[Dependencies](Deps.md)** diff --git a/docs/policies/AI.md b/docs/policies/AI.md index 1618420a11..719548f4c8 100644 --- a/docs/policies/AI.md +++ b/docs/policies/AI.md @@ -17,7 +17,9 @@ AI is notorious for hallucinating facts out of thin air and sometimes outright l - Code that works, but is extraordinarily verbose or not nearly as efficient as it can be - Code that works well and is written well, but solves a different problem than was intended, or solves the same problem but in a completely incorrect way that will break other things horribly. -Human-written code will, without exception, always be of infinitely higher quality when properly researched and implemented by someone both familiar with the surrounding code and the programming language in use. LLMs may produce a "good enough" result, but this result is often subpar. Keep in mind: all code is held under a standard of excellence. If your code sucks, it will be rejected. AI-generated code just so happens to be a particularly sucky genre of code, and will thus be held to this same standard. +Human-written code will, without exception, always be of infinitely higher quality when properly researched and implemented by someone familiar with *both* the surrounding code and the programming language in use. LLMs may produce a "good enough" result, but this result is often subpar. + +**All code is held under a STRICT STANDARD OF EXCELLENCE**. AI code is no different, and since it often produces subpar or outright terrible code, it will often fail to meet this excellence standard. On a lesser-known note, LLM outputs often contain unicode symbols such as emojis or the arrow symbol. Please don't put Unicode symbols in your code. It messes with many an IDE, and the three people viewing your code on Lynx will be very unhappy. @@ -25,7 +27,8 @@ On a lesser-known note, LLM outputs often contain unicode symbols such as emojis ## Acceptable Use -- As stated previously, AI is good in a few *very specific* cases. In these cases, it's usually fine to use AI, as long as you **explicitly provide notice that it was used**. +As stated previously, AI is good in a few *very specific* cases. In these cases, it's usually fine to use AI, as long as you **explicitly provide notice that it was used**. + - Anything directly outside of the realm of the code written in your PR or patch is none of our business. - This primarily covers research. - However, we *still* strongly discourage this for the reasons mentioned above. @@ -104,4 +107,6 @@ This consolidates profile removal behavior, fixes potential race conditions in t This has all of the same problems as the other one. Needlessly verbose, doesn't address *what* it actually fixes ("consolidates profile removal behavior"... okay, why? What does it fix?), etc. It even has the bonus of totally hallucinating the addition of a method! +On a more "philosophical" note, LLMs tend to be geared towards *corporate language*, as that's what they're trained on. This is why AI-generated commit messages feel like "word salad", and typically pad out the commit message to make it *look* like a lot of things were changed (trust me, it's like that in the corporate world). They typically also drift towards unneeded buzzwords and useless implementation details. + **Don't use AI for commit messages**. From f8712e50e6860616b4ea86d57a9b09cd99aad728 Mon Sep 17 00:00:00 2001 From: JPikachu Date: Sat, 28 Feb 2026 01:06:22 +0100 Subject: [PATCH 008/145] [audio] stub SetAudioDeviceOutputVolumeAutoTuneEnabled and IsAudioDeviceOutputVolumeAutoTuneEnabled (#3654) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For Pokémon LeafGreen Version and Pokémon FireRed Version Co-authored-by: JPikachu Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3654 Reviewed-by: Maufeat Reviewed-by: Lizzie Co-authored-by: JPikachu Co-committed-by: JPikachu --- src/core/hle/service/audio/audio_device.cpp | 17 ++++++++++++++--- src/core/hle/service/audio/audio_device.h | 5 +++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/core/hle/service/audio/audio_device.cpp b/src/core/hle/service/audio/audio_device.cpp index 9bf78c4a55..eb64892ed8 100644 --- a/src/core/hle/service/audio/audio_device.cpp +++ b/src/core/hle/service/audio/audio_device.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project @@ -36,8 +36,8 @@ IAudioDevice::IAudioDevice(Core::System& system_, u64 applet_resource_user_id, u {16, nullptr, "ReleaseAudioInputDeviceNotification"}, //17.0.0+ {17, nullptr, "AcquireAudioOutputDeviceNotification"}, //17.0.0+ {18, nullptr, "ReleaseAudioOutputDeviceNotification"}, //17.0.0+ - {19, nullptr, "SetAudioDeviceOutputVolumeAutoTuneEnabled"}, //18.0.0+ - {20, nullptr, "IsAudioDeviceOutputVolumeAutoTuneEnabled"}, //18.0.0+ + {19, D<&IAudioDevice::SetAudioDeviceOutputVolumeAutoTuneEnabled>, "SetAudioDeviceOutputVolumeAutoTuneEnabled"}, //18.0.0+ + {20, D<&IAudioDevice::IsAudioDeviceOutputVolumeAutoTuneEnabled>, "IsAudioDeviceOutputVolumeAutoTuneEnabled"}, //18.0.0+ {21, nullptr, "IsActiveOutputDeviceEstimatedLowLatency"} //21.0.0+ }; RegisterHandlers(functions); @@ -170,4 +170,15 @@ Result IAudioDevice::ListAudioOutputDeviceName( R_SUCCEED(); } +Result IAudioDevice::SetAudioDeviceOutputVolumeAutoTuneEnabled(bool enabled) { + LOG_WARNING(Service_Audio, "(STUBBED) called"); + R_SUCCEED(); +} + +Result IAudioDevice::IsAudioDeviceOutputVolumeAutoTuneEnabled(Out out_enabled) { + LOG_WARNING(Service_Audio, "(STUBBED) called"); + *out_enabled = false; + R_SUCCEED(); +} + } // namespace Service::Audio diff --git a/src/core/hle/service/audio/audio_device.h b/src/core/hle/service/audio/audio_device.h index 752157272c..f6c12fbfeb 100644 --- a/src/core/hle/service/audio/audio_device.h +++ b/src/core/hle/service/audio/audio_device.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -49,6 +52,8 @@ private: Result ListAudioOutputDeviceName( OutArray out_names, Out out_count); + Result SetAudioDeviceOutputVolumeAutoTuneEnabled(bool enabled); + Result IsAudioDeviceOutputVolumeAutoTuneEnabled(Out out_enabled); KernelHelpers::ServiceContext service_context; std::unique_ptr impl; From 06a08de68a95506a9cbe4633c58f6bdb5ded0c70 Mon Sep 17 00:00:00 2001 From: lizzie Date: Sat, 28 Feb 2026 01:06:33 +0100 Subject: [PATCH 009/145] [core/loader] prevent program_image reallocations in NSO+KIP loading methods (#3639) also changes some methods to std::span<> as well, but mainly std::vector<> in the NSO/KIP loading stuff is not needed to be memcpy'ed and memmove'd around this should save a marginal amount of loading time (RDR1) Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3639 Reviewed-by: DraVee Reviewed-by: Maufeat Co-authored-by: lizzie Co-committed-by: lizzie --- src/core/CMakeLists.txt | 1 - src/core/arm/nce/patcher.cpp | 9 +- src/core/arm/nce/patcher.h | 7 +- src/core/file_sys/kernel_executable.cpp | 9 +- src/core/file_sys/kernel_executable.h | 10 +- src/core/hle/kernel/code_set.h | 5 +- src/core/hle/kernel/physical_memory.h | 23 ----- .../hle/service/am/frontend/applet_error.cpp | 5 +- .../am/frontend/applet_software_keyboard.cpp | 19 ++-- .../am/frontend/applet_software_keyboard.h | 19 ++-- .../am/frontend/applet_web_browser.cpp | 13 ++- src/core/hle/service/lm/lm.cpp | 10 +- .../service/ns/platform_service_manager.cpp | 3 +- src/core/hle/service/ro/ro.cpp | 28 +++--- src/core/hle/service/ro/ro_types.h | 51 +--------- src/core/loader/kip.cpp | 19 +--- src/core/loader/nro.cpp | 4 +- src/core/loader/nso.cpp | 99 ++++++++----------- 18 files changed, 122 insertions(+), 212 deletions(-) delete mode 100644 src/core/hle/kernel/physical_memory.h diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index b3071d94b2..08d6e73688 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -342,7 +342,6 @@ add_library(core STATIC hle/kernel/message_buffer.h hle/kernel/physical_core.cpp hle/kernel/physical_core.h - hle/kernel/physical_memory.h hle/kernel/slab_helpers.h hle/kernel/svc.cpp hle/kernel/svc.h diff --git a/src/core/arm/nce/patcher.cpp b/src/core/arm/nce/patcher.cpp index bd8e4fd7fb..ea77166645 100644 --- a/src/core/arm/nce/patcher.cpp +++ b/src/core/arm/nce/patcher.cpp @@ -4,6 +4,7 @@ #include #include #include "common/arm64/native_clock.h" +#include "common/alignment.h" #include "common/literals.h" #include "core/arm/nce/arm_nce.h" #include "core/arm/nce/guest_context.h" @@ -46,8 +47,7 @@ Patcher::Patcher() : c(m_patch_instructions), c_pre(m_patch_instructions_pre) { Patcher::~Patcher() = default; -bool Patcher::PatchText(const Kernel::PhysicalMemory& program_image, - const Kernel::CodeSet::Segment& code) { +bool Patcher::PatchText(std::span program_image, const Kernel::CodeSet::Segment& code) { // If we have patched modules but cannot reach the new module, then it needs its own patcher. const size_t image_size = program_image.size(); @@ -175,10 +175,7 @@ bool Patcher::PatchText(const Kernel::PhysicalMemory& program_image, return true; } -bool Patcher::RelocateAndCopy(Common::ProcessAddress load_base, - const Kernel::CodeSet::Segment& code, - Kernel::PhysicalMemory& program_image, - EntryTrampolines* out_trampolines) { +bool Patcher::RelocateAndCopy(Common::ProcessAddress load_base, const Kernel::CodeSet::Segment& code, std::vector& program_image, EntryTrampolines* out_trampolines) { const size_t patch_size = GetSectionSize(); const size_t pre_patch_size = GetPreSectionSize(); diff --git a/src/core/arm/nce/patcher.h b/src/core/arm/nce/patcher.h index 303cf68ec6..499c98c901 100644 --- a/src/core/arm/nce/patcher.h +++ b/src/core/arm/nce/patcher.h @@ -14,7 +14,6 @@ #include "common/settings.h" #include "core/hle/kernel/code_set.h" #include "core/hle/kernel/k_typed_address.h" -#include "core/hle/kernel/physical_memory.h" #include using ModuleID = std::array; // NSO build ID struct PatchCacheKey { @@ -56,10 +55,8 @@ public: } explicit Patcher(); ~Patcher(); - bool PatchText(const Kernel::PhysicalMemory& program_image, - const Kernel::CodeSet::Segment& code); - bool RelocateAndCopy(Common::ProcessAddress load_base, const Kernel::CodeSet::Segment& code, - Kernel::PhysicalMemory& program_image, EntryTrampolines* out_trampolines); + bool PatchText(std::span program_image, const Kernel::CodeSet::Segment& code); + bool RelocateAndCopy(Common::ProcessAddress load_base, const Kernel::CodeSet::Segment& code, std::vector& program_image, EntryTrampolines* out_trampolines); size_t GetSectionSize() const noexcept; size_t GetPreSectionSize() const noexcept; diff --git a/src/core/file_sys/kernel_executable.cpp b/src/core/file_sys/kernel_executable.cpp index b84492d30a..dea05f840f 100644 --- a/src/core/file_sys/kernel_executable.cpp +++ b/src/core/file_sys/kernel_executable.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -160,15 +163,15 @@ u32 KIP::GetMainThreadCpuCore() const { return header.default_core; } -const std::vector& KIP::GetTextSection() const { +std::span KIP::GetTextSection() const { return decompressed_sections[0]; } -const std::vector& KIP::GetRODataSection() const { +std::span KIP::GetRODataSection() const { return decompressed_sections[1]; } -const std::vector& KIP::GetDataSection() const { +std::span KIP::GetDataSection() const { return decompressed_sections[2]; } diff --git a/src/core/file_sys/kernel_executable.h b/src/core/file_sys/kernel_executable.h index 928ba2d99f..ac4b1acaf4 100644 --- a/src/core/file_sys/kernel_executable.h +++ b/src/core/file_sys/kernel_executable.h @@ -1,9 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include +#include #include #include @@ -70,9 +74,9 @@ public: u32 GetMainThreadStackSize() const; u32 GetMainThreadCpuCore() const; - const std::vector& GetTextSection() const; - const std::vector& GetRODataSection() const; - const std::vector& GetDataSection() const; + std::span GetTextSection() const; + std::span GetRODataSection() const; + std::span GetDataSection() const; u32 GetTextOffset() const; u32 GetRODataOffset() const; diff --git a/src/core/hle/kernel/code_set.h b/src/core/hle/kernel/code_set.h index 1416fc52b1..88bc7f5e66 100644 --- a/src/core/hle/kernel/code_set.h +++ b/src/core/hle/kernel/code_set.h @@ -7,9 +7,9 @@ #pragma once #include +#include #include "core/hle/kernel/k_typed_address.h" -#include "core/hle/kernel/physical_memory.h" namespace Kernel { @@ -97,8 +97,7 @@ struct CodeSet final { #endif /// The overall data that backs this code set. - Kernel::PhysicalMemory memory; - + std::vector memory; /// The segments that comprise this code set. std::array segments; diff --git a/src/core/hle/kernel/physical_memory.h b/src/core/hle/kernel/physical_memory.h deleted file mode 100644 index 253fa45636..0000000000 --- a/src/core/hle/kernel/physical_memory.h +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#pragma once - -#include - -#include "common/alignment.h" - -namespace Kernel { - -// This encapsulation serves 2 purposes: -// - First, to encapsulate host physical memory under a single type and set an -// standard for managing it. -// - Second to ensure all host backing memory used is aligned to 256 bytes due -// to strict alignment restrictions on GPU memory. - -using PhysicalMemoryVector = std::vector>; -class PhysicalMemory final : public PhysicalMemoryVector { - using PhysicalMemoryVector::PhysicalMemoryVector; -}; - -} // namespace Kernel diff --git a/src/core/hle/service/am/frontend/applet_error.cpp b/src/core/hle/service/am/frontend/applet_error.cpp index 34ec7013b5..1c530aa324 100644 --- a/src/core/hle/service/am/frontend/applet_error.cpp +++ b/src/core/hle/service/am/frontend/applet_error.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -93,7 +96,7 @@ union Error::ErrorArguments { namespace { template -void CopyArgumentData(const std::vector& data, T& variable) { +void CopyArgumentData(std::span data, T& variable) { ASSERT(data.size() >= sizeof(T)); std::memcpy(&variable, data.data(), sizeof(T)); } diff --git a/src/core/hle/service/am/frontend/applet_software_keyboard.cpp b/src/core/hle/service/am/frontend/applet_software_keyboard.cpp index d1bc030182..fe07d72912 100644 --- a/src/core/hle/service/am/frontend/applet_software_keyboard.cpp +++ b/src/core/hle/service/am/frontend/applet_software_keyboard.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -775,7 +778,7 @@ Result SoftwareKeyboard::RequestExit() { // Inline Software Keyboard Requests -void SoftwareKeyboard::RequestFinalize(const std::vector& request_data) { +void SoftwareKeyboard::RequestFinalize(std::span request_data) { LOG_DEBUG(Service_AM, "Processing Request: Finalize"); ChangeState(SwkbdState::NotInitialized); @@ -783,17 +786,17 @@ void SoftwareKeyboard::RequestFinalize(const std::vector& request_data) { ExitKeyboard(); } -void SoftwareKeyboard::RequestSetUserWordInfo(const std::vector& request_data) { +void SoftwareKeyboard::RequestSetUserWordInfo(std::span request_data) { LOG_WARNING(Service_AM, "SetUserWordInfo is not implemented."); ReplyReleasedUserWordInfo(); } -void SoftwareKeyboard::RequestSetCustomizeDic(const std::vector& request_data) { +void SoftwareKeyboard::RequestSetCustomizeDic(std::span request_data) { LOG_WARNING(Service_AM, "SetCustomizeDic is not implemented."); } -void SoftwareKeyboard::RequestCalc(const std::vector& request_data) { +void SoftwareKeyboard::RequestCalc(std::span request_data) { LOG_DEBUG(Service_AM, "Processing Request: Calc"); ASSERT(request_data.size() >= sizeof(SwkbdRequestCommand) + sizeof(SwkbdCalcArgCommon)); @@ -930,17 +933,17 @@ void SoftwareKeyboard::RequestCalcNew() { } } -void SoftwareKeyboard::RequestSetCustomizedDictionaries(const std::vector& request_data) { +void SoftwareKeyboard::RequestSetCustomizedDictionaries(std::span request_data) { LOG_WARNING(Service_AM, "SetCustomizedDictionaries is not implemented."); } -void SoftwareKeyboard::RequestUnsetCustomizedDictionaries(const std::vector& request_data) { +void SoftwareKeyboard::RequestUnsetCustomizedDictionaries(std::span request_data) { LOG_WARNING(Service_AM, "(STUBBED) Processing Request: UnsetCustomizedDictionaries"); ReplyUnsetCustomizedDictionaries(); } -void SoftwareKeyboard::RequestSetChangedStringV2Flag(const std::vector& request_data) { +void SoftwareKeyboard::RequestSetChangedStringV2Flag(std::span request_data) { LOG_DEBUG(Service_AM, "Processing Request: SetChangedStringV2Flag"); ASSERT(request_data.size() == sizeof(SwkbdRequestCommand) + 1); @@ -948,7 +951,7 @@ void SoftwareKeyboard::RequestSetChangedStringV2Flag(const std::vector& requ std::memcpy(&use_changed_string_v2, request_data.data() + sizeof(SwkbdRequestCommand), 1); } -void SoftwareKeyboard::RequestSetMovedCursorV2Flag(const std::vector& request_data) { +void SoftwareKeyboard::RequestSetMovedCursorV2Flag(std::span request_data) { LOG_DEBUG(Service_AM, "Processing Request: SetMovedCursorV2Flag"); ASSERT(request_data.size() == sizeof(SwkbdRequestCommand) + 1); diff --git a/src/core/hle/service/am/frontend/applet_software_keyboard.h b/src/core/hle/service/am/frontend/applet_software_keyboard.h index 2a7d01b965..a3e4150080 100644 --- a/src/core/hle/service/am/frontend/applet_software_keyboard.h +++ b/src/core/hle/service/am/frontend/applet_software_keyboard.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -124,16 +127,16 @@ private: // Inline Software Keyboard Requests - void RequestFinalize(const std::vector& request_data); - void RequestSetUserWordInfo(const std::vector& request_data); - void RequestSetCustomizeDic(const std::vector& request_data); - void RequestCalc(const std::vector& request_data); + void RequestFinalize(std::span request_data); + void RequestSetUserWordInfo(std::span request_data); + void RequestSetCustomizeDic(std::span request_data); + void RequestCalc(std::span request_data); void RequestCalcOld(); void RequestCalcNew(); - void RequestSetCustomizedDictionaries(const std::vector& request_data); - void RequestUnsetCustomizedDictionaries(const std::vector& request_data); - void RequestSetChangedStringV2Flag(const std::vector& request_data); - void RequestSetMovedCursorV2Flag(const std::vector& request_data); + void RequestSetCustomizedDictionaries(std::span request_data); + void RequestUnsetCustomizedDictionaries(std::span request_data); + void RequestSetChangedStringV2Flag(std::span request_data); + void RequestSetMovedCursorV2Flag(std::span request_data); // Inline Software Keyboard Replies diff --git a/src/core/hle/service/am/frontend/applet_web_browser.cpp b/src/core/hle/service/am/frontend/applet_web_browser.cpp index 206f2fd495..98e3b9c66d 100644 --- a/src/core/hle/service/am/frontend/applet_web_browser.cpp +++ b/src/core/hle/service/am/frontend/applet_web_browser.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -34,22 +34,21 @@ namespace Service::AM::Frontend { namespace { template -void ParseRawValue(T& value, const std::vector& data) { +void ParseRawValue(T& value, std::span data) { static_assert(std::is_trivially_copyable_v, "It's undefined behavior to use memcpy with non-trivially copyable objects"); std::memcpy(&value, data.data(), data.size()); } template -T ParseRawValue(const std::vector& data) { +T ParseRawValue(std::span data) { T value; ParseRawValue(value, data); return value; } -std::string ParseStringValue(const std::vector& data) { - return Common::StringFromFixedZeroTerminatedBuffer(reinterpret_cast(data.data()), - data.size()); +std::string ParseStringValue(std::span data) { + return Common::StringFromFixedZeroTerminatedBuffer(reinterpret_cast(data.data()), data.size()); } std::string GetMainURL(const std::string& url) { @@ -72,7 +71,7 @@ std::string ResolveURL(const std::string& url) { return url.substr(0, index) + "lp1" + url.substr(index + 1); } -WebArgInputTLVMap ReadWebArgs(const std::vector& web_arg, WebArgHeader& web_arg_header) { +WebArgInputTLVMap ReadWebArgs(std::span web_arg, WebArgHeader& web_arg_header) { std::memcpy(&web_arg_header, web_arg.data(), sizeof(WebArgHeader)); if (web_arg.size() == sizeof(WebArgHeader)) { diff --git a/src/core/hle/service/lm/lm.cpp b/src/core/hle/service/lm/lm.cpp index 2fda8a3b90..0ff5ac0440 100644 --- a/src/core/hle/service/lm/lm.cpp +++ b/src/core/hle/service/lm/lm.cpp @@ -164,7 +164,7 @@ private: rb.Push(ResultSuccess); } - u64 ReadLeb128(const std::vector& data, std::size_t& offset) { + u64 ReadLeb128(std::span data, std::size_t& offset) { u64 result{}; u32 shift{}; @@ -180,7 +180,7 @@ private: return result; } - std::optional ReadString(const std::vector& data, std::size_t& offset, + std::optional ReadString(std::span data, std::size_t& offset, std::size_t length) { if (length == 0) { return std::nullopt; @@ -193,7 +193,7 @@ private: return output; } - u32_le ReadAsU32(const std::vector& data, std::size_t& offset, std::size_t length) { + u32_le ReadAsU32(std::span data, std::size_t& offset, std::size_t length) { ASSERT(length == sizeof(u32)); u32_le output{}; std::memcpy(&output, data.data() + offset, sizeof(u32)); @@ -201,7 +201,7 @@ private: return output; } - u64_le ReadAsU64(const std::vector& data, std::size_t& offset, std::size_t length) { + u64_le ReadAsU64(std::span data, std::size_t& offset, std::size_t length) { ASSERT(length == sizeof(u64)); u64_le output{}; std::memcpy(&output, data.data() + offset, sizeof(u64)); @@ -209,7 +209,7 @@ private: return output; } - void ParseLog(const LogPacketHeaderEntry entry, const std::vector& log_data) { + void ParseLog(const LogPacketHeaderEntry entry, std::span log_data) { // Possible entries std::optional text_log; std::optional line_number; diff --git a/src/core/hle/service/ns/platform_service_manager.cpp b/src/core/hle/service/ns/platform_service_manager.cpp index ec9f64945d..e91e6451a8 100644 --- a/src/core/hle/service/ns/platform_service_manager.cpp +++ b/src/core/hle/service/ns/platform_service_manager.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project @@ -21,7 +21,6 @@ #include "core/file_sys/system_archive/system_archive.h" #include "core/hle/kernel/k_shared_memory.h" #include "core/hle/kernel/kernel.h" -#include "core/hle/kernel/physical_memory.h" #include "core/hle/service/cmif_serialization.h" #include "core/hle/service/filesystem/filesystem.h" #include "core/hle/service/ns/platform_service_manager.h" diff --git a/src/core/hle/service/ro/ro.cpp b/src/core/hle/service/ro/ro.cpp index 041c0dbd87..cd50e69ce1 100644 --- a/src/core/hle/service/ro/ro.cpp +++ b/src/core/hle/service/ro/ro.cpp @@ -176,11 +176,9 @@ struct ProcessContext { // Calculate hash. Sha256Hash hash; { - const u64 size = nro_header->GetSize(); - + const u64 size = nro_header->m_size; std::vector nro_data(size); m_process->GetMemory().ReadBlock(base_address, nro_data.data(), size); - u32 hash_len = 0; EVP_Digest(nro_data.data(), nro_data.size(), hash.data(), &hash_len, EVP_sha256(), nullptr); } @@ -204,9 +202,7 @@ struct ProcessContext { R_THROW(RO::ResultNotAuthorized); } - Result ValidateNro(ModuleId* out_module_id, u64* out_rx_size, u64* out_ro_size, - u64* out_rw_size, u64 base_address, u64 expected_nro_size, - u64 expected_bss_size) { + Result ValidateNro(ModuleId* out_module_id, u64* out_rx_size, u64* out_ro_size, u64* out_rw_size, u64 base_address, u64 expected_nro_size, u64 expected_bss_size) { // Ensure we have a process to work on. R_UNLESS(m_process != nullptr, RO::ResultInvalidProcess); @@ -215,17 +211,17 @@ struct ProcessContext { m_process->GetMemory().ReadBlock(base_address, std::addressof(header), sizeof(header)); // Validate header. - R_UNLESS(header.IsMagicValid(), RO::ResultInvalidNro); + R_UNLESS(header.m_magic == NRO_HEADER_MAGIC, RO::ResultInvalidNro); // Read sizes from header. - const u64 nro_size = header.GetSize(); - const u64 text_ofs = header.GetTextOffset(); - const u64 text_size = header.GetTextSize(); - const u64 ro_ofs = header.GetRoOffset(); - const u64 ro_size = header.GetRoSize(); - const u64 rw_ofs = header.GetRwOffset(); - const u64 rw_size = header.GetRwSize(); - const u64 bss_size = header.GetBssSize(); + const u64 nro_size = header.m_size; + const u64 text_ofs = header.m_text_offset; + const u64 text_size = header.m_text_size; + const u64 ro_ofs = header.m_ro_offset; + const u64 ro_size = header.m_ro_size; + const u64 rw_ofs = header.m_rw_offset; + const u64 rw_size = header.m_rw_size; + const u64 bss_size = header.m_bss_size; // Validate sizes meet expected. R_UNLESS(nro_size == expected_nro_size, RO::ResultInvalidNro); @@ -251,7 +247,7 @@ struct ProcessContext { R_TRY(this->ValidateHasNroHash(base_address, std::addressof(header))); // Check if NRO has already been loaded. - const ModuleId* module_id = header.GetModuleId(); + const ModuleId* module_id = std::addressof(header.m_module_id); R_UNLESS(R_FAILED(this->GetNroInfoByModuleId(nullptr, module_id)), RO::ResultAlreadyLoaded); // Apply patches to NRO. diff --git a/src/core/hle/service/ro/ro_types.h b/src/core/hle/service/ro/ro_types.h index 624d52ee5f..50b424395a 100644 --- a/src/core/hle/service/ro/ro_types.h +++ b/src/core/hle/service/ro/ro_types.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -112,52 +115,8 @@ private: }; static_assert(sizeof(NrrHeader) == 0x350, "NrrHeader has wrong size"); -class NroHeader { -public: - static constexpr u32 Magic = Common::MakeMagic('N', 'R', 'O', '0'); - -public: - bool IsMagicValid() const { - return m_magic == Magic; - } - - u32 GetSize() const { - return m_size; - } - - u32 GetTextOffset() const { - return m_text_offset; - } - - u32 GetTextSize() const { - return m_text_size; - } - - u32 GetRoOffset() const { - return m_ro_offset; - } - - u32 GetRoSize() const { - return m_ro_size; - } - - u32 GetRwOffset() const { - return m_rw_offset; - } - - u32 GetRwSize() const { - return m_rw_size; - } - - u32 GetBssSize() const { - return m_bss_size; - } - - const ModuleId* GetModuleId() const { - return std::addressof(m_module_id); - } - -private: +static constexpr u32 NRO_HEADER_MAGIC = Common::MakeMagic('N', 'R', 'O', '0'); +struct NroHeader { u32 m_entrypoint_insn; u32 m_mod_offset; INSERT_PADDING_BYTES_NOINIT(0x8); diff --git a/src/core/loader/kip.cpp b/src/core/loader/kip.cpp index b61ce80bae..db6c98c5a3 100644 --- a/src/core/loader/kip.cpp +++ b/src/core/loader/kip.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project @@ -75,21 +75,16 @@ AppLoader::LoadResult AppLoader_KIP::Load(Kernel::KProcess& process, kip->GetKernelCapabilities()); Kernel::CodeSet codeset; - Kernel::PhysicalMemory program_image; - - const auto load_segment = [&program_image](Kernel::CodeSet::Segment& segment, const std::vector& data, u32 offset) { + codeset.memory.resize(PageAlignSize(kip->GetBSSOffset()) + kip->GetBSSSize()); + const auto load_segment = [&codeset](Kernel::CodeSet::Segment& segment, std::span data, u32 offset) { segment.addr = offset; segment.offset = offset; segment.size = PageAlignSize(u32(data.size())); - program_image.resize(offset + data.size()); - std::memcpy(program_image.data() + offset, data.data(), data.size()); + std::memcpy(codeset.memory.data() + offset, data.data(), data.size()); }; - load_segment(codeset.CodeSegment(), kip->GetTextSection(), kip->GetTextOffset()); load_segment(codeset.RODataSegment(), kip->GetRODataSection(), kip->GetRODataOffset()); load_segment(codeset.DataSegment(), kip->GetDataSection(), kip->GetDataOffset()); - - program_image.resize(PageAlignSize(kip->GetBSSOffset()) + kip->GetBSSSize()); codeset.DataSegment().size += kip->GetBSSSize(); // TODO: this is bad form of ASLR, it sucks @@ -98,13 +93,9 @@ AppLoader::LoadResult AppLoader_KIP::Load(Kernel::KProcess& process, : std::rand()) * 0x734287f27) & 0xfff000; // Setup the process code layout - if (process - .LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), program_image.size(), 0, aslr_offset, false) - .IsError()) { + if (process.LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), codeset.memory.size(), 0, aslr_offset, false).IsError()) { return {ResultStatus::ErrorNotInitialized, {}}; } - - codeset.memory = std::move(program_image); const VAddr base_address = GetInteger(process.GetEntryPoint()); process.LoadModule(std::move(codeset), base_address); diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp index a3cfa31be7..f5a77a726f 100644 --- a/src/core/loader/nro.cpp +++ b/src/core/loader/nro.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project @@ -160,7 +160,7 @@ static bool LoadNroImpl(Core::System& system, Kernel::KProcess& process, } // Build program image - Kernel::PhysicalMemory program_image(PageAlignSize(nro_header.file_size)); + std::vector program_image(PageAlignSize(nro_header.file_size)); std::memcpy(program_image.data(), data.data(), program_image.size()); if (program_image.size() != PageAlignSize(nro_header.file_size)) { return {}; diff --git a/src/core/loader/nso.cpp b/src/core/loader/nso.cpp index 458df110b6..f62b1f4957 100644 --- a/src/core/loader/nso.cpp +++ b/src/core/loader/nso.cpp @@ -4,6 +4,7 @@ // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +#include #include #include #include @@ -40,17 +41,6 @@ struct MODHeader { }; static_assert(sizeof(MODHeader) == 0x1c, "MODHeader has incorrect size."); -std::vector DecompressSegment(const std::vector& compressed_data, - const NSOSegmentHeader& header) { - std::vector uncompressed_data = - Common::Compression::DecompressDataLZ4(compressed_data, header.size); - - ASSERT_MSG(uncompressed_data.size() == header.size, "{} != {}", header.size, - uncompressed_data.size()); - - return uncompressed_data; -} - constexpr u32 PageAlignSize(u32 size) { return static_cast((size + Core::Memory::YUZU_PAGEMASK) & ~Core::Memory::YUZU_PAGEMASK); } @@ -76,24 +66,16 @@ FileType AppLoader_NSO::IdentifyType(const FileSys::VirtualFile& in_file) { return FileType::NSO; } -std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core::System& system, - const FileSys::VfsFile& nso_file, VAddr load_base, - bool should_pass_arguments, bool load_into_process, - std::optional pm, - std::vector* patches, - s32 patch_index) { - if (nso_file.GetSize() < sizeof(NSOHeader)) { +std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core::System& system, const FileSys::VfsFile& nso_file, VAddr load_base, bool should_pass_arguments, bool load_into_process, std::optional pm, std::vector* patches, s32 patch_index) { + if (nso_file.GetSize() < sizeof(NSOHeader)) return std::nullopt; - } - NSOHeader nso_header{}; - if (sizeof(NSOHeader) != nso_file.ReadObject(&nso_header)) { + if (sizeof(NSOHeader) != nso_file.ReadObject(&nso_header)) return std::nullopt; - } - - if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0')) { + if (nso_header.magic != Common::MakeMagic('N', 'S', 'O', '0')) + return std::nullopt; + if (nso_header.segments.empty()) return std::nullopt; - } // Allocate some space at the beginning if we are patching in PreText mode. const size_t module_start = [&]() -> size_t { @@ -110,42 +92,44 @@ std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: return 0; }(); - // Build program image + auto const last_segment_it = &nso_header.segments[nso_header.segments.size() - 1]; + // Build program image directly in codeset memory :) Kernel::CodeSet codeset; - Kernel::PhysicalMemory program_image; - for (std::size_t i = 0; i < nso_header.segments.size(); ++i) { - std::vector data = nso_file.ReadBytes(nso_header.segments_compressed_size[i], - nso_header.segments[i].offset); - if (nso_header.IsSegmentCompressed(i)) { - data = DecompressSegment(data, nso_header.segments[i]); + codeset.memory.resize(module_start + last_segment_it->location + last_segment_it->size); + { + std::vector compressed_data(*std::ranges::max_element(nso_header.segments_compressed_size)); + std::vector decompressed_size(std::ranges::max_element(nso_header.segments, [](auto const& a, auto const& b) { + return a.size < b.size; + })->size); + for (std::size_t i = 0; i < nso_header.segments.size(); ++i) { + nso_file.Read(compressed_data.data(), nso_header.segments_compressed_size[i], nso_header.segments[i].offset); + if (nso_header.IsSegmentCompressed(i)) { + int r = Common::Compression::DecompressDataLZ4(decompressed_size.data(), nso_header.segments[i].size, compressed_data.data(), nso_header.segments_compressed_size[i]); + ASSERT(r == int(nso_header.segments[i].size)); + std::memcpy(codeset.memory.data() + module_start + nso_header.segments[i].location, decompressed_size.data(), nso_header.segments[i].size); + } else { + std::memcpy(codeset.memory.data() + module_start + nso_header.segments[i].location, compressed_data.data(), nso_header.segments[i].size); + } + codeset.segments[i].addr = module_start + nso_header.segments[i].location; + codeset.segments[i].offset = module_start + nso_header.segments[i].location; + codeset.segments[i].size = nso_header.segments[i].size; } - program_image.resize(module_start + nso_header.segments[i].location + - static_cast(data.size())); - std::memcpy(program_image.data() + module_start + nso_header.segments[i].location, - data.data(), data.size()); - codeset.segments[i].addr = module_start + nso_header.segments[i].location; - codeset.segments[i].offset = module_start + nso_header.segments[i].location; - codeset.segments[i].size = nso_header.segments[i].size; } if (should_pass_arguments && !Settings::values.program_args.GetValue().empty()) { const auto arg_data{Settings::values.program_args.GetValue()}; codeset.DataSegment().size += NSO_ARGUMENT_DATA_ALLOCATION_SIZE; - NSOArgumentHeader args_header{ - NSO_ARGUMENT_DATA_ALLOCATION_SIZE, static_cast(arg_data.size()), {}}; - const auto end_offset = program_image.size(); - program_image.resize(static_cast(program_image.size()) + - NSO_ARGUMENT_DATA_ALLOCATION_SIZE); - std::memcpy(program_image.data() + end_offset, &args_header, sizeof(NSOArgumentHeader)); - std::memcpy(program_image.data() + end_offset + sizeof(NSOArgumentHeader), arg_data.data(), - arg_data.size()); + NSOArgumentHeader args_header{NSO_ARGUMENT_DATA_ALLOCATION_SIZE, static_cast(arg_data.size()), {}}; + const auto end_offset = codeset.memory.size(); + codeset.memory.resize(u32(codeset.memory.size()) + NSO_ARGUMENT_DATA_ALLOCATION_SIZE); + std::memcpy(codeset.memory.data() + end_offset, &args_header, sizeof(NSOArgumentHeader)); + std::memcpy(codeset.memory.data() + end_offset + sizeof(NSOArgumentHeader), arg_data.data(), arg_data.size()); } codeset.DataSegment().size += nso_header.segments[2].bss_size; - u32 image_size{ - PageAlignSize(static_cast(program_image.size()) + nso_header.segments[2].bss_size)}; - program_image.resize(image_size); + u32 image_size = PageAlignSize(u32(codeset.memory.size()) + nso_header.segments[2].bss_size); + codeset.memory.resize(image_size); for (std::size_t i = 0; i < nso_header.segments.size(); ++i) { codeset.segments[i].size = PageAlignSize(codeset.segments[i].size); @@ -154,8 +138,7 @@ std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: // Apply patches if necessary const auto name = nso_file.GetName(); if (pm && (pm->HasNSOPatch(nso_header.build_id, name) || Settings::values.dump_nso)) { - std::span patchable_section(program_image.data() + module_start, - program_image.size() - module_start); + std::span patchable_section(codeset.memory.data() + module_start, codeset.memory.size() - module_start); std::vector pi_header(sizeof(NSOHeader) + patchable_section.size()); std::memcpy(pi_header.data(), &nso_header, sizeof(NSOHeader)); std::memcpy(pi_header.data() + sizeof(NSOHeader), patchable_section.data(), @@ -174,15 +157,15 @@ std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: //Set module ID using build_id from the NSO header patch->SetModuleID(nso_header.build_id); // Patch SVCs and MRS calls in the guest code - while (!patch->PatchText(program_image, code)) { + while (!patch->PatchText(codeset.memory, code)) { patch = &patches->emplace_back(); patch->SetModuleID(nso_header.build_id); // In case the patcher is changed for big modules, the new patcher should also have the build_id } } else if (patch) { - // Relocate code patch and copy to the program_image. + // Relocate code patch and copy to the program image. // Save size before RelocateAndCopy (which may resize) - const size_t size_before_relocate = program_image.size(); - if (patch->RelocateAndCopy(load_base, code, program_image, &process.GetPostHandlers())) { + const size_t size_before_relocate = codeset.memory.size(); + if (patch->RelocateAndCopy(load_base, code, codeset.memory, &process.GetPostHandlers())) { // Update patch section. auto& patch_segment = codeset.PatchSegment(); auto& post_patch_segment = codeset.PostPatchSegment(); @@ -203,7 +186,7 @@ std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: } // Refresh image_size to take account the patch section if it was added by RelocateAndCopy - image_size = static_cast(program_image.size()); + image_size = static_cast(codeset.memory.size()); } #endif @@ -234,9 +217,7 @@ std::optional AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: } // Load codeset for current process - codeset.memory = std::move(program_image); process.LoadModule(std::move(codeset), load_base); - return load_base + image_size; } From 4a833e7206ea0a603def7f9a8538b1dc032eea8e Mon Sep 17 00:00:00 2001 From: smiRaphi Date: Sat, 28 Feb 2026 01:06:59 +0100 Subject: [PATCH 010/145] [desktop] port IR Camera to Qt6 & fix camera saving on windows (#3630) The camera was previously saved without escaping the name which made the values unusable after a settings load, for whatever reason replacing the backslashes when saving with / doesn't work but replacing them with | does. Also note that the OBS virtual cam (and any other cameras that only have directshow drivers) won't work because Qt6 dropped support for that and the ffmpeg backend doesn't seem to support it either. Closes #3468 Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3630 Reviewed-by: crueter Reviewed-by: DraVee Co-authored-by: smiRaphi Co-committed-by: smiRaphi --- CMakeLists.txt | 14 ++-- src/yuzu/CMakeLists.txt | 8 +- src/yuzu/bootmanager.cpp | 57 ++++++------- src/yuzu/bootmanager.h | 10 ++- src/yuzu/configuration/configure_camera.cpp | 80 +++++++++---------- src/yuzu/configuration/configure_camera.h | 11 ++- .../configure_input_advanced.cpp | 4 +- 7 files changed, 90 insertions(+), 94 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11d97724de..4490df21cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,7 +70,7 @@ endif() option(ENABLE_QT "Enable the Qt frontend" ON) option(ENABLE_QT_TRANSLATION "Enable translations for the Qt frontend" OFF) option(ENABLE_UPDATE_CHECKER "Enable update checker (for Qt and Android)" OFF) -# option(YUZU_USE_QT_MULTIMEDIA "Use QtMultimedia for Camera" OFF) +cmake_dependent_option(YUZU_USE_QT_MULTIMEDIA "Use QtMultimedia for Camera" OFF "NOT YUZU_USE_BUNDLED_QT" OFF) cmake_dependent_option(YUZU_USE_QT_WEB_ENGINE "Use QtWebEngine for web applet implementation" OFF "NOT YUZU_USE_BUNDLED_QT" OFF) set(YUZU_QT_MIRROR "" CACHE STRING "What mirror to use for downloading the bundled Qt libraries") cmake_dependent_option(YUZU_USE_BUNDLED_QT "Download bundled Qt binaries" "${MSVC}" "ENABLE_QT" OFF) @@ -577,9 +577,9 @@ if (ENABLE_QT) find_package(Qt6 CONFIG REQUIRED COMPONENTS Widgets Charts Concurrent) - # if (YUZU_USE_QT_MULTIMEDIA) - # find_package(Qt6 REQUIRED COMPONENTS Multimedia) - # endif() + if (YUZU_USE_QT_MULTIMEDIA) + find_package(Qt6 REQUIRED COMPONENTS Multimedia) + endif() if (PLATFORM_LINUX OR PLATFORM_FREEBSD) # yes Qt, we get it @@ -618,9 +618,9 @@ if (ENABLE_QT) if (PLATFORM_LINUX) list(APPEND YUZU_QT_COMPONENTS DBus) endif() - # if (YUZU_USE_QT_MULTIMEDIA) - # list(APPEND YUZU_QT_COMPONENTS Multimedia) - # endif() + if (YUZU_USE_QT_MULTIMEDIA) + list(APPEND YUZU_QT_COMPONENTS Multimedia) + endif() if (YUZU_USE_QT_WEB_ENGINE) list(APPEND YUZU_QT_COMPONENTS WebEngineCore WebEngineWidgets) endif() diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt index c85d43235a..99fb2fec15 100644 --- a/src/yuzu/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -412,10 +412,10 @@ if (ENABLE_WEB_SERVICE) target_compile_definitions(yuzu PRIVATE ENABLE_WEB_SERVICE) endif() -# if (YUZU_USE_QT_MULTIMEDIA) -# target_link_libraries(yuzu PRIVATE Qt6::Multimedia) -# target_compile_definitions(yuzu PRIVATE YUZU_USE_QT_MULTIMEDIA) -# endif () +if (YUZU_USE_QT_MULTIMEDIA) + target_link_libraries(yuzu PRIVATE Qt6::Multimedia) + target_compile_definitions(yuzu PRIVATE YUZU_USE_QT_MULTIMEDIA) +endif () if (YUZU_USE_QT_WEB_ENGINE) target_link_libraries(yuzu PRIVATE Qt6::WebEngineCore Qt6::WebEngineWidgets) diff --git a/src/yuzu/bootmanager.cpp b/src/yuzu/bootmanager.cpp index 1b88f4133f..72a5157fc4 100644 --- a/src/yuzu/bootmanager.cpp +++ b/src/yuzu/bootmanager.cpp @@ -13,10 +13,11 @@ #include #include "common/settings_enums.h" #include "qt_common/config/uisettings.h" -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA #include -#include -#include +#include +#include +#include #endif #include #include @@ -756,24 +757,25 @@ void GRenderWindow::TouchEndEvent() { } void GRenderWindow::InitializeCamera() { -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA constexpr auto camera_update_ms = std::chrono::milliseconds{50}; // (50ms, 20Hz) if (!Settings::values.enable_ir_sensor) { return; } bool camera_found = false; - const QList cameras = QCameraInfo::availableCameras(); - for (const QCameraInfo& cameraInfo : cameras) { - if (Settings::values.ir_sensor_device.GetValue() == cameraInfo.deviceName().toStdString() || - Settings::values.ir_sensor_device.GetValue() == "Auto") { - camera = std::make_unique(cameraInfo); - if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) && - !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { - LOG_ERROR(Frontend, - "Camera doesn't support CaptureViewfinder or CaptureStillImage"); + std::string current_device = Settings::values.ir_sensor_device.GetValue(); +#ifdef _WIN32 + std::replace(current_device.begin(), current_device.end(), '|', '\\'); +#endif + const QList cameras = QMediaDevices::videoInputs(); + for (const QCameraDevice& cameraDevice : cameras) { + if (current_device == cameraDevice.id().toStdString() || current_device == "auto") { + if (cameraDevice.videoFormats().isEmpty()) { + LOG_ERROR(Frontend, "Camera doesn't provide any video formats."); continue; } + camera = std::make_unique(cameraDevice); camera_found = true; break; } @@ -783,27 +785,16 @@ void GRenderWindow::InitializeCamera() { return; } - camera_capture = std::make_unique(camera.get()); - - if (!camera_capture->isCaptureDestinationSupported( - QCameraImageCapture::CaptureDestination::CaptureToBuffer)) { - LOG_ERROR(Frontend, "Camera doesn't support saving to buffer"); - return; - } + capture_session = std::make_unique(); + camera_capture = std::make_unique(); + capture_session->setCamera(camera.get()); + capture_session->setImageCapture(camera_capture.get()); const auto camera_width = input_subsystem->GetCamera()->getImageWidth(); const auto camera_height = input_subsystem->GetCamera()->getImageHeight(); camera_data.resize(camera_width * camera_height); - camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer); - connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this, + connect(camera_capture.get(), &QImageCapture::imageCaptured, this, &GRenderWindow::OnCameraCapture); - camera->unload(); - if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) { - camera->setCaptureMode(QCamera::CaptureViewfinder); - } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { - camera->setCaptureMode(QCamera::CaptureStillImage); - } - camera->load(); camera->start(); pending_camera_snapshots = 0; @@ -817,18 +808,18 @@ void GRenderWindow::InitializeCamera() { } void GRenderWindow::FinalizeCamera() { -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA if (camera_timer) { camera_timer->stop(); } if (camera) { - camera->unload(); + camera->stop(); } #endif } void GRenderWindow::RequestCameraCapture() { -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA if (!Settings::values.enable_ir_sensor) { return; } @@ -849,7 +840,7 @@ void GRenderWindow::RequestCameraCapture() { } void GRenderWindow::OnCameraCapture(int requestId, const QImage& img) { -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA // TODO: Capture directly in the format and resolution needed const auto camera_width = input_subsystem->GetCamera()->getImageWidth(); const auto camera_height = input_subsystem->GetCamera()->getImageHeight(); diff --git a/src/yuzu/bootmanager.h b/src/yuzu/bootmanager.h index 83d364df4b..837156a725 100644 --- a/src/yuzu/bootmanager.h +++ b/src/yuzu/bootmanager.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2014 Citra Emulator Project @@ -34,7 +34,8 @@ class MainWindow; class QCamera; -class QCameraImageCapture; +class QImageCapture; +class QMediaCaptureSession; class QCloseEvent; class QFocusEvent; class QKeyEvent; @@ -264,12 +265,13 @@ private: bool first_frame = false; InputCommon::TasInput::TasState last_tas_state; -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA bool is_virtual_camera; int pending_camera_snapshots; std::vector camera_data; std::unique_ptr camera; - std::unique_ptr camera_capture; + std::unique_ptr camera_capture; + std::unique_ptr capture_session; std::unique_ptr camera_timer; #endif diff --git a/src/yuzu/configuration/configure_camera.cpp b/src/yuzu/configuration/configure_camera.cpp index 3368f53f30..eb39bbdc9f 100644 --- a/src/yuzu/configuration/configure_camera.cpp +++ b/src/yuzu/configuration/configure_camera.cpp @@ -1,11 +1,16 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // Text : Copyright 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later #include #include -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA -#include -#include +#if YUZU_USE_QT_MULTIMEDIA +#include +#include +#include +#include #endif #include #include @@ -36,22 +41,20 @@ ConfigureCamera::ConfigureCamera(QWidget* parent, InputCommon::InputSubsystem* i ConfigureCamera::~ConfigureCamera() = default; void ConfigureCamera::PreviewCamera() { -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA const auto index = ui->ir_sensor_combo_box->currentIndex(); bool camera_found = false; - const QList cameras = QCameraInfo::availableCameras(); - for (const QCameraInfo& cameraInfo : cameras) { - if (input_devices[index] == cameraInfo.deviceName().toStdString() || - input_devices[index] == "Auto") { - LOG_INFO(Frontend, "Selected Camera {} {}", cameraInfo.description().toStdString(), - cameraInfo.deviceName().toStdString()); - camera = std::make_unique(cameraInfo); - if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) && - !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { - LOG_ERROR(Frontend, - "Camera doesn't support CaptureViewfinder or CaptureStillImage"); + const QList cameras = QMediaDevices::videoInputs(); + for (const QCameraDevice& cameraDevice : cameras) { + if (input_devices[index] == cameraDevice.id().toStdString() || + input_devices[index] == "auto") { + LOG_INFO(Frontend, "Selected Camera {} {}", cameraDevice.description().toStdString(), + cameraDevice.id().toStdString()); + if (cameraDevice.videoFormats().isEmpty()) { + LOG_ERROR(Frontend, "Camera doesn't provide any video formats."); continue; } + camera = std::make_unique(cameraDevice); camera_found = true; break; } @@ -66,24 +69,12 @@ void ConfigureCamera::PreviewCamera() { return; } - camera_capture = std::make_unique(camera.get()); - - if (!camera_capture->isCaptureDestinationSupported( - QCameraImageCapture::CaptureDestination::CaptureToBuffer)) { - LOG_ERROR(Frontend, "Camera doesn't support saving to buffer"); - return; - } - - camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer); - connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this, + capture_session = std::make_unique(); + camera_capture = std::make_unique(); + capture_session->setCamera(camera.get()); + capture_session->setImageCapture(camera_capture.get()); + connect(camera_capture.get(), &QImageCapture::imageCaptured, this, &ConfigureCamera::DisplayCapturedFrame); - camera->unload(); - if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) { - camera->setCaptureMode(QCamera::CaptureViewfinder); - } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { - camera->setCaptureMode(QCamera::CaptureStillImage); - } - camera->load(); camera->start(); pending_snapshots = 0; @@ -129,24 +120,31 @@ void ConfigureCamera::RetranslateUI() { } void ConfigureCamera::ApplyConfiguration() { - const auto index = ui->ir_sensor_combo_box->currentIndex(); - Settings::values.ir_sensor_device.SetValue(input_devices[index]); + std::string current_device = input_devices[ui->ir_sensor_combo_box->currentIndex()]; +#ifdef _WIN32 + // for whatever reason replacing with / isn't enough so we use | for saving + std::replace(current_device.begin(), current_device.end(), '\\', '|'); +#endif + Settings::values.ir_sensor_device.SetValue(current_device); } void ConfigureCamera::LoadConfiguration() { input_devices.clear(); ui->ir_sensor_combo_box->clear(); - input_devices.push_back("Auto"); + input_devices.push_back("auto"); ui->ir_sensor_combo_box->addItem(tr("Auto")); -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA - const auto cameras = QCameraInfo::availableCameras(); - for (const QCameraInfo& cameraInfo : cameras) { - input_devices.push_back(cameraInfo.deviceName().toStdString()); - ui->ir_sensor_combo_box->addItem(cameraInfo.description()); +#if YUZU_USE_QT_MULTIMEDIA + const auto cameras = QMediaDevices::videoInputs(); + for (const QCameraDevice& cameraDevice : cameras) { + input_devices.push_back(cameraDevice.id().toStdString()); + ui->ir_sensor_combo_box->addItem(cameraDevice.description()); } #endif - const auto current_device = Settings::values.ir_sensor_device.GetValue(); + std::string current_device = Settings::values.ir_sensor_device.GetValue(); +#ifdef _WIN32 + std::replace(current_device.begin(), current_device.end(), '|', '\\'); +#endif const auto devices_it = std::find_if( input_devices.begin(), input_devices.end(), diff --git a/src/yuzu/configuration/configure_camera.h b/src/yuzu/configuration/configure_camera.h index 3d822da7bb..610b362419 100644 --- a/src/yuzu/configuration/configure_camera.h +++ b/src/yuzu/configuration/configure_camera.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // Text : Copyright 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -8,7 +11,8 @@ class QTimer; class QCamera; -class QCameraImageCapture; +class QImageCapture; +class QMediaCaptureSession; namespace InputCommon { class InputSubsystem; @@ -46,9 +50,10 @@ private: bool is_virtual_camera; int pending_snapshots; -#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA +#if YUZU_USE_QT_MULTIMEDIA std::unique_ptr camera; - std::unique_ptr camera_capture; + std::unique_ptr camera_capture; + std::unique_ptr capture_session; #endif std::unique_ptr camera_timer; std::vector input_devices; diff --git a/src/yuzu/configuration/configure_input_advanced.cpp b/src/yuzu/configuration/configure_input_advanced.cpp index 241d445cea..b1c19114bf 100644 --- a/src/yuzu/configuration/configure_input_advanced.cpp +++ b/src/yuzu/configuration/configure_input_advanced.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -201,7 +201,7 @@ void ConfigureInputAdvanced::UpdateUIEnabled() { ui->debug_configure->setEnabled(ui->debug_enabled->isChecked()); ui->touchscreen_advanced->setEnabled(ui->touchscreen_enabled->isChecked()); ui->ring_controller_configure->setEnabled(ui->enable_ring_controller->isChecked()); -#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0) || !defined(YUZU_USE_QT_MULTIMEDIA) +#if !defined(YUZU_USE_QT_MULTIMEDIA) ui->enable_ir_sensor->setEnabled(false); ui->camera_configure->setEnabled(false); #endif From ac181b756f7c8e4abf67412cc2c61ba61f5e5301 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 28 Feb 2026 01:07:40 +0100 Subject: [PATCH 011/145] [Config] Update Rescale Toggle Description to Include Intel GPUs (#3650) The toggle hack has benefits for Intel GPU users in Luigi Mansion 3 as they also suffer from line artifacts. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3650 Reviewed-by: crueter Reviewed-by: DraVee Co-authored-by: John Co-committed-by: John --- src/qt_common/config/shared_translation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/qt_common/config/shared_translation.cpp b/src/qt_common/config/shared_translation.cpp index 5f3a6c18c0..f49c43ee2a 100644 --- a/src/qt_common/config/shared_translation.cpp +++ b/src/qt_common/config/shared_translation.cpp @@ -360,7 +360,7 @@ std::unique_ptr InitializeTranslations(QObject* parent) rescale_hack, tr("Enable Legacy Rescale Pass"), tr("May fix rescale issues in some games by relying on behavior from the previous implementation.\n" - "Legacy behavior workaround that fixes AMD GPU line artifacts and Nvidia GPU grey texture flicker in Luigis Mansion 3.")); + "Legacy behavior workaround that fixes line artifacts on AMD and Intel GPUs, and grey texture flicker on Nvidia GPUs in Luigis Mansion 3.")); // Renderer (Extensions) INSERT(Settings, dyna_state, tr("Extended Dynamic State"), From 7de5eb6884bd3c4b4f8912406e30dc26497e9fbc Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sat, 28 Feb 2026 16:05:06 +0100 Subject: [PATCH 012/145] [android] fix persist manual game pause after android sleep/wake (#3651) if user invokes the "pause game" option from the menu while in game, as expected this suspends the process till user manually hits resume.. except for one case: Android sleep/wake lifecycle. If user manually pauses a running game, then sleeps their device, then wakes their device; the game will self-resume without user pressing "resume game". Expected behavior IMO is that if user left the game process in manually paused state, app should respect this and persist the pause on system wake, so that user may manually press "resume game" to unfreeze the process. Simple fix is to have a few params for user initiated pause and resume, and update the pause and run methods to handle as described above. Please let me know if there is a cleaner way to implement! Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3651 Reviewed-by: crueter Reviewed-by: CamilleLaVey Reviewed-by: DraVee Co-authored-by: xXJSONDeruloXx Co-committed-by: xXJSONDeruloXx --- .../java/org/yuzu/yuzu_emu/NativeLibrary.kt | 4 + .../yuzu_emu/activities/EmulationActivity.kt | 8 +- .../yuzu_emu/fragments/EmulationFragment.kt | 144 +++++++++++++++--- .../org/yuzu/yuzu_emu/overlay/InputOverlay.kt | 7 +- .../src/main/jni/emu_window/emu_window.cpp | 11 ++ src/android/app/src/main/jni/native.cpp | 41 ++++- .../src/main/res/drawable/circle_white.xml | 4 + .../main/res/layout/fragment_emulation.xml | 28 ++++ 8 files changed, 220 insertions(+), 27 deletions(-) create mode 100644 src/android/app/src/main/res/drawable/circle_white.xml diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt index e49f466462..1f0acf2835 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt @@ -152,6 +152,10 @@ object NativeLibrary { external fun surfaceDestroyed() + external fun getAppletCaptureBuffer(): ByteArray + external fun getAppletCaptureWidth(): Int + external fun getAppletCaptureHeight(): Int + /** * Unpauses emulation from a paused state. */ diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt index 42d4f687f4..2764d7eac6 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2023 yuzu Emulator Project @@ -204,9 +204,9 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener, InputManager } override fun onPause() { - super.onPause() nfcReader.stopScanning() stopMotionSensorListener() + super.onPause() } override fun onDestroy() { @@ -339,6 +339,10 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener, InputManager } override fun onSensorChanged(event: SensorEvent) { + if (!NativeLibrary.isRunning() || NativeLibrary.isPaused()) { + return + } + val rotation = this.display?.rotation if (rotation == Surface.ROTATION_90) { flipMotionOrientation = true diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt index e8739e2d23..435fe5fe2c 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt @@ -15,6 +15,7 @@ import android.content.Intent import android.content.IntentFilter import android.content.pm.ActivityInfo import android.content.res.Configuration +import android.graphics.Bitmap import android.net.Uri import android.os.BatteryManager import android.os.BatteryManager.* @@ -97,6 +98,7 @@ import org.yuzu.yuzu_emu.utils.collect import org.yuzu.yuzu_emu.utils.CustomSettingsHandler import java.io.ByteArrayOutputStream import java.io.File +import java.nio.ByteBuffer import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.or @@ -141,6 +143,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { private var wasInputOverlayAutoHidden = false private var overlayTouchActive = false + private var pausedFrameBitmap: Bitmap? = null var shouldUseCustom = false private var isQuickSettingsMenuOpen = false @@ -703,6 +706,12 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { binding.inGameMenu.menu.findItem(R.id.menu_quick_settings)?.isVisible = BooleanSetting.ENABLE_QUICK_SETTINGS.getBoolean() + binding.pausedIcon.setOnClickListener { + if (this::emulationState.isInitialized && emulationState.isPaused) { + resumeEmulationFromUi() + } + } + binding.inGameMenu.menu.findItem(R.id.menu_lock_drawer).apply { val lockMode = IntSetting.LOCK_DRAWER.getInt() val titleId = if (lockMode == DrawerLayout.LOCK_MODE_LOCKED_CLOSED) { @@ -728,11 +737,9 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { when (it.itemId) { R.id.menu_pause_emulation -> { if (emulationState.isPaused) { - emulationState.run(false) - updatePauseMenuEntry(false) + resumeEmulationFromUi() } else { - emulationState.pause() - updatePauseMenuEntry(true) + pauseEmulationAndCaptureFrame() } binding.inGameMenu.requestFocus() true @@ -826,6 +833,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } R.id.menu_exit -> { + clearPausedFrame() emulationState.stop() NativeConfig.reloadGlobalConfig() emulationViewModel.setIsEmulationStopping(true) @@ -1197,6 +1205,71 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } } + private fun pauseEmulationAndCaptureFrame() { + emulationState.pause() + updatePauseMenuEntry(true) + capturePausedFrameFromCore() + updatePausedFrameVisibility() + } + + private fun capturePausedFrameFromCore() { + lifecycleScope.launch(Dispatchers.Default) { + val frameData = NativeLibrary.getAppletCaptureBuffer() + val width = NativeLibrary.getAppletCaptureWidth() + val height = NativeLibrary.getAppletCaptureHeight() + if (frameData.isEmpty() || width <= 0 || height <= 0) { + Log.warning( + "[EmulationFragment] Paused frame capture returned empty/invalid data. " + + "size=${frameData.size}, width=$width, height=$height" + ) + return@launch + } + + val expectedSize = width * height * 4 + if (frameData.size < expectedSize) { + Log.warning( + "[EmulationFragment] Paused frame buffer smaller than expected. " + + "size=${frameData.size}, expected=$expectedSize" + ) + return@launch + } + + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(frameData, 0, expectedSize)) + + withContext(Dispatchers.Main) { + pausedFrameBitmap?.recycle() + pausedFrameBitmap = bitmap + updatePausedFrameVisibility() + } + } + } + + private fun updatePausedFrameVisibility() { + val b = _binding ?: return + val showPausedUi = this::emulationState.isInitialized && emulationState.isPaused + b.pausedIcon.setVisible(showPausedUi) + + val bitmap = if (showPausedUi) pausedFrameBitmap else null + b.pausedFrameImage.setImageBitmap(bitmap) + b.pausedFrameImage.setVisible(bitmap != null) + } + + private fun resumeEmulationFromUi() { + clearPausedFrame() + emulationState.resume() + updatePauseMenuEntry(emulationState.isPaused) + updatePausedFrameVisibility() + } + + private fun clearPausedFrame() { + val b = _binding + b?.pausedFrameImage?.setVisible(false) + b?.pausedFrameImage?.setImageDrawable(null) + pausedFrameBitmap?.recycle() + pausedFrameBitmap = null + } + private fun handleLoadAmiiboSelection(): Boolean { val binding = _binding ?: return true @@ -1290,8 +1363,9 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { override fun onPause() { if (this::emulationState.isInitialized) { if (emulationState.isRunning && emulationActivity?.isInPictureInPictureMode != true) { - emulationState.pause() - updatePauseMenuEntry(true) + pauseEmulationAndCaptureFrame() + } else { + updatePausedFrameVisibility() } } super.onPause() @@ -1301,6 +1375,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { super.onDestroyView() amiiboLoadJob?.cancel() amiiboLoadJob = null + clearPausedFrame() _binding?.surfaceInputOverlay?.touchEventListener = null _binding = null isAmiiboPickerOpen = false @@ -1321,6 +1396,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { b.inGameMenu.post { if (!this::emulationState.isInitialized || _binding == null) return@post updatePauseMenuEntry(emulationState.isPaused) + updatePausedFrameVisibility() } } @@ -1760,6 +1836,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { // Only update surface reference, don't trigger state changes emulationState.updateSurfaceReference(holder.surface) } + updatePausedFrameVisibility() } override fun surfaceDestroyed(holder: SurfaceHolder) { @@ -2090,6 +2167,29 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } } + @Synchronized + fun resume() { + if (state != State.PAUSED) { + Log.warning("[EmulationFragment] Resume called while emulation is not paused.") + return + } + if (!emulationCanStart.invoke()) { + Log.warning("[EmulationFragment] Resume blocked by emulationCanStart check.") + return + } + val currentSurface = surface + if (currentSurface == null || !currentSurface.isValid) { + Log.debug("[EmulationFragment] Resume requested with invalid surface.") + return + } + + NativeLibrary.surfaceChanged(currentSurface) + Log.debug("[EmulationFragment] Resuming emulation.") + NativeLibrary.unpauseEmulation() + NativeLibrary.playTimeManagerStart() + state = State.RUNNING + } + @Synchronized fun changeProgram(programIndex: Int) { emulationThread.join() @@ -2111,7 +2211,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { @Synchronized fun updateSurface() { - if (surface != null) { + if (surface != null && state == State.RUNNING) { NativeLibrary.surfaceChanged(surface) } } @@ -2127,20 +2227,20 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { @Synchronized fun clearSurface() { if (surface == null) { - Log.warning("[EmulationFragment] clearSurface called, but surface already null.") + Log.debug("[EmulationFragment] clearSurface called, but surface already null.") } else { + if (state == State.RUNNING) { + pause() + } + NativeLibrary.surfaceDestroyed() surface = null Log.debug("[EmulationFragment] Surface destroyed.") when (state) { - State.RUNNING -> { - state = State.PAUSED - } - - State.PAUSED -> Log.warning( + State.PAUSED -> Log.debug( "[EmulationFragment] Surface cleared while emulation paused." ) - else -> Log.warning( + else -> Log.debug( "[EmulationFragment] Surface cleared while emulation stopped." ) } @@ -2148,29 +2248,35 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } private fun runWithValidSurface(programIndex: Int = 0) { - NativeLibrary.surfaceChanged(surface) if (!emulationCanStart.invoke()) { return } + val currentSurface = surface + if (currentSurface == null || !currentSurface.isValid) { + Log.debug("[EmulationFragment] runWithValidSurface called with invalid surface.") + return + } when (state) { State.STOPPED -> { + NativeLibrary.surfaceChanged(currentSurface) emulationThread = Thread({ Log.debug("[EmulationFragment] Starting emulation thread.") NativeLibrary.run(gamePath, programIndex, true) }, "NativeEmulation") emulationThread.start() + state = State.RUNNING } State.PAUSED -> { - Log.debug("[EmulationFragment] Resuming emulation.") - NativeLibrary.unpauseEmulation() - NativeLibrary.playTimeManagerStart() + Log.debug( + "[EmulationFragment] Surface restored while emulation paused; " + + "waiting for explicit resume." + ) } else -> Log.debug("[EmulationFragment] Bug, run called while already running.") } - state = State.RUNNING } private enum class State { diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt index e18077c673..d3b5d86174 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later package org.yuzu.yuzu_emu.overlay @@ -20,7 +20,6 @@ import android.os.Looper import android.util.AttributeSet import android.view.HapticFeedbackConstants import android.view.MotionEvent -import android.view.SurfaceView import android.view.View import android.view.View.OnTouchListener import android.view.WindowInsets @@ -42,10 +41,10 @@ import org.yuzu.yuzu_emu.utils.NativeConfig /** * Draws the interactive input overlay on top of the - * [SurfaceView] that is rendering emulation. + * emulation rendering surface. */ class InputOverlay(context: Context, attrs: AttributeSet?) : - SurfaceView(context, attrs), + View(context, attrs), OnTouchListener { private val overlayButtons: MutableSet = HashSet() private val overlayDpads: MutableSet = HashSet() diff --git a/src/android/app/src/main/jni/emu_window/emu_window.cpp b/src/android/app/src/main/jni/emu_window/emu_window.cpp index 06db553691..4e90cad570 100644 --- a/src/android/app/src/main/jni/emu_window/emu_window.cpp +++ b/src/android/app/src/main/jni/emu_window/emu_window.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -14,6 +17,14 @@ #include "jni/native.h" void EmuWindow_Android::OnSurfaceChanged(ANativeWindow* surface) { + if (!surface) { + LOG_INFO(Frontend, "EmuWindow_Android::OnSurfaceChanged received null surface"); + m_window_width = 0; + m_window_height = 0; + window_info.render_surface = nullptr; + return; + } + m_window_width = ANativeWindow_getWidth(surface); m_window_height = ANativeWindow_getHeight(surface); diff --git a/src/android/app/src/main/jni/native.cpp b/src/android/app/src/main/jni/native.cpp index 2e50bb1069..c429f4a1e4 100644 --- a/src/android/app/src/main/jni/native.cpp +++ b/src/android/app/src/main/jni/native.cpp @@ -89,6 +89,8 @@ #include "jni/native.h" #include "video_core/renderer_base.h" #include "video_core/renderer_vulkan/renderer_vulkan.h" +#include "video_core/capture.h" +#include "video_core/textures/decoders.h" #include "video_core/vulkan_common/vulkan_instance.h" #include "video_core/vulkan_common/vulkan_surface.h" #include "video_core/shader_notify.h" @@ -780,9 +782,10 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_surfaceChanged(JNIEnv* env, jobject i } void Java_org_yuzu_yuzu_1emu_NativeLibrary_surfaceDestroyed(JNIEnv* env, jobject instance) { - ANativeWindow_release(EmulationSession::GetInstance().NativeWindow()); + if (auto* native_window = EmulationSession::GetInstance().NativeWindow(); native_window) { + ANativeWindow_release(native_window); + } EmulationSession::GetInstance().SetNativeWindow(nullptr); - EmulationSession::GetInstance().SurfaceChanged(); } void Java_org_yuzu_yuzu_1emu_NativeLibrary_setAppDirectory(JNIEnv* env, jobject instance, @@ -969,6 +972,40 @@ jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_isPaused(JNIEnv* env, jclass claz return static_cast(EmulationSession::GetInstance().IsPaused()); } +jbyteArray Java_org_yuzu_yuzu_1emu_NativeLibrary_getAppletCaptureBuffer(JNIEnv* env, jclass clazz) { + using namespace VideoCore::Capture; + + if (!EmulationSession::GetInstance().IsRunning()) { + return env->NewByteArray(0); + } + + const auto tiled = EmulationSession::GetInstance().System().GPU().GetAppletCaptureBuffer(); + if (tiled.size() < TiledSize) { + return env->NewByteArray(0); + } + + std::vector linear(LinearWidth * LinearHeight * BytesPerPixel); + Tegra::Texture::UnswizzleTexture(linear, tiled, BytesPerPixel, LinearWidth, LinearHeight, + LinearDepth, BlockHeight, BlockDepth); + + auto buffer = env->NewByteArray(static_cast(linear.size())); + if (!buffer) { + return env->NewByteArray(0); + } + + env->SetByteArrayRegion(buffer, 0, static_cast(linear.size()), + reinterpret_cast(linear.data())); + return buffer; +} + +jint Java_org_yuzu_yuzu_1emu_NativeLibrary_getAppletCaptureWidth(JNIEnv* env, jclass clazz) { + return static_cast(VideoCore::Capture::LinearWidth); +} + +jint Java_org_yuzu_yuzu_1emu_NativeLibrary_getAppletCaptureHeight(JNIEnv* env, jclass clazz) { + return static_cast(VideoCore::Capture::LinearHeight); +} + void Java_org_yuzu_yuzu_1emu_NativeLibrary_initializeSystem(JNIEnv* env, jclass clazz, jboolean reload) { // Initialize the emulated system. diff --git a/src/android/app/src/main/res/drawable/circle_white.xml b/src/android/app/src/main/res/drawable/circle_white.xml new file mode 100644 index 0000000000..c94e68679a --- /dev/null +++ b/src/android/app/src/main/res/drawable/circle_white.xml @@ -0,0 +1,4 @@ + + + + diff --git a/src/android/app/src/main/res/layout/fragment_emulation.xml b/src/android/app/src/main/res/layout/fragment_emulation.xml index 7f5f039d5e..db363bc723 100644 --- a/src/android/app/src/main/res/layout/fragment_emulation.xml +++ b/src/android/app/src/main/res/layout/fragment_emulation.xml @@ -108,6 +108,22 @@ + + + + + + + + Date: Sat, 28 Feb 2026 19:34:55 +0100 Subject: [PATCH 013/145] [android] add IntSetting for static theme and set green as default (#3655) Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3655 Reviewed-by: CamilleLaVey Co-authored-by: PavelBARABANOV Co-committed-by: PavelBARABANOV --- .../features/settings/model/IntSetting.kt | 1 + .../settings/ui/SettingsFragmentPresenter.kt | 19 ++++++++++--------- .../yuzu_emu/utils/DirectoryInitialization.kt | 6 ++++++ .../org/yuzu/yuzu_emu/utils/ThemeHelper.kt | 4 ++-- .../app/src/main/jni/android_settings.h | 1 + .../app/src/main/res/values/strings.xml | 4 ++-- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/IntSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/IntSetting.kt index a24a2e1776..4c70d2b35b 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/IntSetting.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/IntSetting.kt @@ -34,6 +34,7 @@ enum class IntSetting(override val key: String) : AbstractIntSetting { MAX_ANISOTROPY("max_anisotropy"), THEME("theme"), THEME_MODE("theme_mode"), + STATIC_THEME_COLOR("static_theme_color"), APP_LANGUAGE("app_language"), OVERLAY_SCALE("control_scale"), OVERLAY_OPACITY("control_opacity"), diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt index 332617804e..0fc4fb0b7f 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt @@ -1124,23 +1124,24 @@ class SettingsFragmentPresenter( } val staticThemeColor: AbstractIntSetting = object : AbstractIntSetting { - val preferences = PreferenceManager.getDefaultSharedPreferences( - YuzuApplication.appContext - ) override fun getInt(needsGlobal: Boolean): Int = - preferences.getInt(Settings.PREF_STATIC_THEME_COLOR, 0) + IntSetting.STATIC_THEME_COLOR.getInt(needsGlobal) + override fun setInt(value: Int) { - preferences.edit() { putInt(Settings.PREF_STATIC_THEME_COLOR, value) } + IntSetting.STATIC_THEME_COLOR.setInt(value) settingsViewModel.setShouldRecreate(true) } - override val key: String = Settings.PREF_STATIC_THEME_COLOR + override val key: String = IntSetting.STATIC_THEME_COLOR.key override val isRuntimeModifiable: Boolean = true + override fun getValueAsString(needsGlobal: Boolean): String = - preferences.getInt(Settings.PREF_STATIC_THEME_COLOR, 0).toString() - override val defaultValue: Any = 0 + IntSetting.STATIC_THEME_COLOR.getValueAsString(needsGlobal) + + override val defaultValue: Any = IntSetting.STATIC_THEME_COLOR.defaultValue + override fun reset() { - preferences.edit() { putInt(Settings.PREF_STATIC_THEME_COLOR, 0) } + IntSetting.STATIC_THEME_COLOR.reset() settingsViewModel.setShouldRecreate(true) } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/DirectoryInitialization.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/DirectoryInitialization.kt index 6318aa71f2..f47c60491b 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/DirectoryInitialization.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/DirectoryInitialization.kt @@ -61,6 +61,12 @@ object DirectoryInitialization { saveConfig = true } + val staticThemeColor = preferences.migratePreference(Settings.PREF_STATIC_THEME_COLOR) + if (staticThemeColor != null) { + IntSetting.STATIC_THEME_COLOR.setInt(staticThemeColor) + saveConfig = true + } + val blackBackgrounds = preferences.migratePreference(Settings.PREF_BLACK_BACKGROUNDS) if (blackBackgrounds != null) { diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/ThemeHelper.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/ThemeHelper.kt index 3e138c0244..83335b5e1c 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/ThemeHelper.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/ThemeHelper.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later package org.yuzu.yuzu_emu.utils @@ -52,7 +52,7 @@ object ThemeHelper { } private fun getSelectedStaticThemeColor(): Int { - val themeIndex = preferences.getInt(Settings.PREF_STATIC_THEME_COLOR, 0) + val themeIndex = IntSetting.STATIC_THEME_COLOR.getInt(false) val themes = arrayOf( R.style.Theme_Eden_Main, R.style.Theme_Yuzu_Main_Violet, diff --git a/src/android/app/src/main/jni/android_settings.h b/src/android/app/src/main/jni/android_settings.h index 4090330d78..606ce2ce84 100644 --- a/src/android/app/src/main/jni/android_settings.h +++ b/src/android/app/src/main/jni/android_settings.h @@ -56,6 +56,7 @@ namespace AndroidSettings { Settings::Setting theme{linkage, 0, "theme", Settings::Category::Android}; Settings::Setting theme_mode{linkage, -1, "theme_mode", Settings::Category::Android}; + Settings::Setting static_theme_color{linkage, 5, "static_theme_color", Settings::Category::Android}; Settings::Setting black_backgrounds{linkage, false, "black_backgrounds", Settings::Category::Android}; Settings::Setting app_language{linkage, 0, "app_language", Settings::Category::Android}; diff --git a/src/android/app/src/main/res/values/strings.xml b/src/android/app/src/main/res/values/strings.xml index fc1334863d..7d094effcb 100644 --- a/src/android/app/src/main/res/values/strings.xml +++ b/src/android/app/src/main/res/values/strings.xml @@ -1222,12 +1222,12 @@ Theme Color - Eden (Default) + Eden Violet Blue Cyan Red - Green + Green (Default) Yellow Orange Pink From 281d7a468e3c61706f9687a4bcdd4c2c097f24c9 Mon Sep 17 00:00:00 2001 From: lizzie Date: Sun, 1 Mar 2026 01:53:04 +0100 Subject: [PATCH 014/145] [ports] Remove ENABLE_OPENSSL and mbedtls nixos remnants (#3638) shell.nix still had references to mbedtls Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3638 Reviewed-by: MaranBr Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- shell.nix | 2 +- src/android/app/build.gradle.kts | 1 - src/android/app/src/main/jni/CMakeLists.txt | 7 ++----- src/core/crypto/aes_util.cpp | 15 ++++----------- src/core/crypto/sha_util.cpp | 4 ---- src/core/crypto/sha_util.h | 19 ------------------- 6 files changed, 7 insertions(+), 41 deletions(-) delete mode 100644 src/core/crypto/sha_util.cpp delete mode 100644 src/core/crypto/sha_util.h diff --git a/shell.nix b/shell.nix index d835b43ed1..d8257b88d9 100644 --- a/shell.nix +++ b/shell.nix @@ -9,7 +9,7 @@ pkgs.mkShellNoCC { # libraries openssl boost fmt nlohmann_json lz4 zlib zstd enet libopus vulkan-headers vulkan-utility-libraries - spirv-tools spirv-headers vulkan-loader unzip mbedtls + spirv-tools spirv-headers vulkan-loader unzip glslang python3 httplib cpp-jwt ffmpeg-headless libusb1 cubeb # eden diff --git a/src/android/app/build.gradle.kts b/src/android/app/build.gradle.kts index 622ae53a77..3279a2202f 100644 --- a/src/android/app/build.gradle.kts +++ b/src/android/app/build.gradle.kts @@ -80,7 +80,6 @@ android { listOf( "-DENABLE_QT=0", // Don't use QT "-DENABLE_WEB_SERVICE=1", // Enable web service - "-DENABLE_OPENSSL=ON", "-DANDROID_ARM_NEON=true", // cryptopp requires Neon to work "-DYUZU_USE_CPM=ON", "-DCPMUTIL_FORCE_BUNDLED=ON", diff --git a/src/android/app/src/main/jni/CMakeLists.txt b/src/android/app/src/main/jni/CMakeLists.txt index 6cdacea320..c68e206d24 100644 --- a/src/android/app/src/main/jni/CMakeLists.txt +++ b/src/android/app/src/main/jni/CMakeLists.txt @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +# SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project # SPDX-License-Identifier: GPL-3.0-or-later # SPDX-FileCopyrightText: 2023 yuzu Emulator Project @@ -27,10 +27,7 @@ if (ARCHITECTURE_arm64) target_link_libraries(yuzu-android PRIVATE adrenotools) endif() -if (ENABLE_OPENSSL OR ENABLE_WEB_SERVICE) - target_link_libraries(yuzu-android PRIVATE OpenSSL::SSL cpp-jwt::cpp-jwt) -endif() - +target_link_libraries(yuzu-android PRIVATE OpenSSL::SSL cpp-jwt::cpp-jwt) if (ENABLE_UPDATE_CHECKER) target_compile_definitions(yuzu-android PUBLIC ENABLE_UPDATE_CHECKER) endif() diff --git a/src/core/crypto/aes_util.cpp b/src/core/crypto/aes_util.cpp index 1189e45bd8..55f436f532 100644 --- a/src/core/crypto/aes_util.cpp +++ b/src/core/crypto/aes_util.cpp @@ -38,7 +38,6 @@ struct CipherContext { static inline const std::string GetCipherName(Mode mode, u32 key_size) { std::string cipher; std::size_t effective_bits = key_size * 8; - switch (mode) { case Mode::CTR: cipher = "CTR"; @@ -53,7 +52,6 @@ static inline const std::string GetCipherName(Mode mode, u32 key_size) { default: UNREACHABLE(); } - return fmt::format("AES-{}-{}", effective_bits, cipher); }; @@ -87,8 +85,7 @@ static EVP_CIPHER *GetCipher(Mode mode, u32 key_size) { // TODO: WHY TEMPLATE??????? template -Crypto::AESCipher::AESCipher(Key key, Mode mode) - : ctx(std::make_unique()) { +Crypto::AESCipher::AESCipher(Key key, Mode mode) : ctx(std::make_unique()) { ctx->encryption_context = EVP_CIPHER_CTX_new(); ctx->decryption_context = EVP_CIPHER_CTX_new(); @@ -99,9 +96,7 @@ Crypto::AESCipher::AESCipher(Key key, Mode mode) UNIMPLEMENTED(); } - ASSERT_MSG(ctx->encryption_context && ctx->decryption_context && ctx->cipher, - "OpenSSL cipher context failed init!"); - + ASSERT(ctx->encryption_context && ctx->decryption_context && ctx->cipher && "OpenSSL cipher context failed init!"); // now init ciphers ASSERT(EVP_CipherInit_ex2(ctx->encryption_context, ctx->cipher, key.data(), NULL, 1, NULL)); ASSERT(EVP_CipherInit_ex2(ctx->decryption_context, ctx->cipher, key.data(), NULL, 0, NULL)); @@ -165,8 +160,7 @@ void AESCipher::Transcode(const u8* src, std::size_t size, u8* des template void AESCipher::XTSTranscode(const u8* src, std::size_t size, u8* dest, std::size_t sector_id, std::size_t sector_size, Op op) { - ASSERT_MSG(size % sector_size == 0, "XTS decryption size must be a multiple of sector size."); - + ASSERT(size % sector_size == 0 && "XTS decryption size must be a multiple of sector size."); for (std::size_t i = 0; i < size; i += sector_size) { SetIV(CalculateNintendoTweak(sector_id++)); Transcode(src + i, sector_size, dest + i, op); @@ -177,8 +171,7 @@ template void AESCipher::SetIV(std::span data) { const int ret_enc = EVP_CipherInit_ex(ctx->encryption_context, nullptr, nullptr, nullptr, data.data(), -1); const int ret_dec = EVP_CipherInit_ex(ctx->decryption_context, nullptr, nullptr, nullptr, data.data(), -1); - - ASSERT_MSG(ret_enc == 1 && ret_dec == 1, "Failed to set IV on OpenSSL contexts"); + ASSERT(ret_enc == 1 && ret_dec == 1 && "Failed to set IV on OpenSSL contexts"); } template class AESCipher; diff --git a/src/core/crypto/sha_util.cpp b/src/core/crypto/sha_util.cpp deleted file mode 100644 index 7a2c048389..0000000000 --- a/src/core/crypto/sha_util.cpp +++ /dev/null @@ -1,4 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -namespace Crypto {} // namespace Crypto diff --git a/src/core/crypto/sha_util.h b/src/core/crypto/sha_util.h deleted file mode 100644 index 5c2c43dbdb..0000000000 --- a/src/core/crypto/sha_util.h +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#pragma once - -#include "common/assert.h" -#include "core/file_sys/vfs.h" -#include "key_manager.h" -#include "mbedtls/cipher.h" - -namespace Crypto { -typedef std::array SHA256Hash; - -inline SHA256Hash operator"" _HASH(const char* data, size_t len) { - if (len != 0x40) - return {}; -} - -} // namespace Crypto From 2991bd18ef18d46069344e816591e34f05dff397 Mon Sep 17 00:00:00 2001 From: lizzie Date: Sun, 1 Mar 2026 01:53:15 +0100 Subject: [PATCH 015/145] [vk] Enable VK_IMG_filter_cubic on powervr (#3643) in powervr, the enum for cubic filtering is an alias for an ext, however in true powervr fashion they want you to use their stupid VK_IMG and knowing powevr it probably bugs out if you dont Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3643 Reviewed-by: DraVee Reviewed-by: MaranBr Co-authored-by: lizzie Co-committed-by: lizzie --- src/video_core/renderer_vulkan/present/util.cpp | 7 ++++--- src/video_core/vulkan_common/vulkan_device.h | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/video_core/renderer_vulkan/present/util.cpp b/src/video_core/renderer_vulkan/present/util.cpp index 29a1c34976..a2c4727703 100644 --- a/src/video_core/renderer_vulkan/present/util.cpp +++ b/src/video_core/renderer_vulkan/present/util.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project @@ -6,6 +6,7 @@ #include "common/assert.h" #include +#include #include "video_core/renderer_vulkan/present/util.h" namespace Vulkan { @@ -629,8 +630,8 @@ vk::Sampler CreateCubicSampler(const Device& device, VkCubicFilterWeightsQCOM qc .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .pNext = nullptr, .flags = 0, - .magFilter = VK_FILTER_CUBIC_EXT, - .minFilter = VK_FILTER_CUBIC_EXT, + .magFilter = device.IsExtFilterCubicSupported() ? VK_FILTER_CUBIC_EXT : VK_FILTER_LINEAR, + .minFilter = device.IsExtFilterCubicSupported() ? VK_FILTER_CUBIC_EXT : VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index 7d738a81df..d3623d1186 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -107,6 +107,7 @@ VK_DEFINE_HANDLE(VmaAllocator) EXTENSION(NV, VIEWPORT_SWIZZLE, viewport_swizzle) \ EXTENSION(EXT, DESCRIPTOR_INDEXING, descriptor_indexing) \ EXTENSION(EXT, FILTER_CUBIC, filter_cubic) \ + EXTENSION(IMG, FILTER_CUBIC, filter_cubic_img) \ EXTENSION(QCOM, FILTER_CUBIC_WEIGHTS, filter_cubic_weights) // Define extensions which must be supported. From a8fc994c0b60be5a823da6466fefb8fb2d689e33 Mon Sep 17 00:00:00 2001 From: xbzk Date: Sun, 1 Mar 2026 23:21:26 +0100 Subject: [PATCH 016/145] pr3655 gradientbordercardview fix (#3658) This complements PR3655, where a change in theme setting caused gradientbordercardview theme color setting mismatch. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3658 Reviewed-by: CamilleLaVey Co-authored-by: xbzk Co-committed-by: xbzk --- .../yuzu/yuzu_emu/views/GradientBorderCardView.kt | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/views/GradientBorderCardView.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/views/GradientBorderCardView.kt index 8121cfb6fa..d6c0709d57 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/views/GradientBorderCardView.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/views/GradientBorderCardView.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2023 yuzu Emulator Project @@ -11,8 +11,7 @@ import android.graphics.* import android.util.AttributeSet import com.google.android.material.card.MaterialCardView import org.yuzu.yuzu_emu.R -import org.yuzu.yuzu_emu.features.settings.model.Settings -import androidx.preference.PreferenceManager +import org.yuzu.yuzu_emu.features.settings.model.IntSetting class GradientBorderCardView @JvmOverloads constructor( context: Context, @@ -44,12 +43,7 @@ class GradientBorderCardView @JvmOverloads constructor( } private fun updateThemeState() { - val prefs = PreferenceManager.getDefaultSharedPreferences(context) - val themeIndex = try { - prefs.getInt(Settings.PREF_STATIC_THEME_COLOR, 0) - } catch (e: Exception) { - 0 // Default to Eden theme if error - } + val themeIndex = IntSetting.STATIC_THEME_COLOR.getInt(false) isEdenTheme = themeIndex == 0 invalidate() } From b5f9f8b7438a6a79644d712e267399d618f5d0e1 Mon Sep 17 00:00:00 2001 From: MaranBr Date: Mon, 2 Mar 2026 02:51:50 +0100 Subject: [PATCH 017/145] [vulkan] Fix Vulkan rendering, image layout, and synchronization issues (#3511) This fixes a visual corruption issue that occurred intermittently after loading screens, where some games would start the scene with vertex explosions, artifacts or with all colors blown out, resembling neon. Among the known games affected by this bug are Mario Kart 8 Deluxe, The Legend of Zelda: Breath of the Wild, The Legend of Zelda: Tears of the Kingdom, Kirby and the Forgotten Land, Luigi's Mansion 3, Xenoblade Chronicles 3 and possibly others as well. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3511 Reviewed-by: DraVee Reviewed-by: Lizzie Co-authored-by: MaranBr Co-committed-by: MaranBr --- .../renderer_vulkan/vk_blit_screen.cpp | 45 +++++++++---------- .../renderer_vulkan/vk_master_semaphore.cpp | 10 ++--- .../renderer_vulkan/vk_scheduler.cpp | 16 +++---- .../renderer_vulkan/vk_texture_cache.cpp | 2 +- .../vulkan_common/vulkan_device.cpp | 8 ---- 5 files changed, 31 insertions(+), 50 deletions(-) diff --git a/src/video_core/renderer_vulkan/vk_blit_screen.cpp b/src/video_core/renderer_vulkan/vk_blit_screen.cpp index 0f54dd5ade..bb7eb9bdaa 100644 --- a/src/video_core/renderer_vulkan/vk_blit_screen.cpp +++ b/src/video_core/renderer_vulkan/vk_blit_screen.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2024 Torzu Emulator Project @@ -22,7 +22,8 @@ BlitScreen::BlitScreen(Tegra::MaxwellDeviceMemoryManager& device_memory_, const MemoryAllocator& memory_allocator_, PresentManager& present_manager_, Scheduler& scheduler_, const PresentFilters& filters_) : device_memory{device_memory_}, device{device_}, memory_allocator{memory_allocator_}, - present_manager{present_manager_}, scheduler{scheduler_}, filters{filters_}, image_count{1}, + present_manager{present_manager_}, scheduler{scheduler_}, filters{filters_}, + image_count{1}, image_index{0}, swapchain_view_format{VK_FORMAT_B8G8R8A8_UNORM} {} BlitScreen::~BlitScreen() = default; @@ -87,57 +88,49 @@ void BlitScreen::DrawToFrame(RasterizerVulkan& rasterizer, Frame* frame, bool resource_update_required = false; bool presentation_recreate_required = false; - // Recreate dynamic resources if the adapting filter changed if (!window_adapt || scaling_filter != filters.get_scaling_filter()) { resource_update_required = true; } - // Recreate dynamic resources if the image count changed - const size_t old_swapchain_image_count = - std::exchange(image_count, current_swapchain_image_count); - if (old_swapchain_image_count != current_swapchain_image_count) { + if (image_count != current_swapchain_image_count) { resource_update_required = true; + image_count = current_swapchain_image_count; } - // Recreate the presentation frame if the format or dimensions of the window changed - const VkFormat old_swapchain_view_format = - std::exchange(swapchain_view_format, current_swapchain_view_format); - if (old_swapchain_view_format != current_swapchain_view_format || + if (swapchain_view_format != current_swapchain_view_format || layout.width != frame->width || layout.height != frame->height) { resource_update_required = true; presentation_recreate_required = true; + swapchain_view_format = current_swapchain_view_format; } - // If we have a pending resource update, perform it if (resource_update_required) { - // Wait for idle to ensure no resources are in use WaitIdle(); - - // Update window adapt pass SetWindowAdaptPass(); - // Update frame format if needed if (presentation_recreate_required) { present_manager.RecreateFrame(frame, layout.width, layout.height, swapchain_view_format, window_adapt->GetRenderPass()); } + + image_index = 0; } - // Add additional layers if needed const VkExtent2D window_size{ .width = layout.screen.GetWidth(), .height = layout.screen.GetHeight(), }; - while (layers.size() < framebuffers.size()) { - layers.emplace_back(device, memory_allocator, scheduler, device_memory, image_count, - window_size, window_adapt->GetDescriptorSetLayout(), filters); + if (layers.size() != framebuffers.size()) { + layers.clear(); + for (size_t i = 0; i < framebuffers.size(); ++i) { + layers.emplace_back(device, memory_allocator, scheduler, device_memory, image_count, + window_size, window_adapt->GetDescriptorSetLayout(), filters); + } } - // Perform the draw window_adapt->Draw(rasterizer, scheduler, image_index, layers, framebuffers, layout, frame); - // Advance to next image if (++image_index >= image_count) { image_index = 0; } @@ -146,16 +139,20 @@ void BlitScreen::DrawToFrame(RasterizerVulkan& rasterizer, Frame* frame, vk::Framebuffer BlitScreen::CreateFramebuffer(const Layout::FramebufferLayout& layout, VkImageView image_view, VkFormat current_view_format) { - const bool format_updated = - std::exchange(swapchain_view_format, current_view_format) != current_view_format; + bool format_updated = swapchain_view_format != current_view_format; + swapchain_view_format = current_view_format; + if (!window_adapt || scaling_filter != filters.get_scaling_filter() || format_updated) { WaitIdle(); SetWindowAdaptPass(); + image_index = 0; } + const VkExtent2D extent{ .width = layout.width, .height = layout.height, }; + return CreateFramebuffer(image_view, extent, window_adapt->GetRenderPass()); } diff --git a/src/video_core/renderer_vulkan/vk_master_semaphore.cpp b/src/video_core/renderer_vulkan/vk_master_semaphore.cpp index 13ecfd20a6..b535097b36 100644 --- a/src/video_core/renderer_vulkan/vk_master_semaphore.cpp +++ b/src/video_core/renderer_vulkan/vk_master_semaphore.cpp @@ -121,10 +121,8 @@ VkResult MasterSemaphore::SubmitQueue(vk::CommandBuffer& cmdbuf, vk::CommandBuff } } -static constexpr std::array wait_stage_masks{ - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, -}; +static constexpr VkPipelineStageFlags wait_stage_mask = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkResult MasterSemaphore::SubmitQueueTimeline(vk::CommandBuffer& cmdbuf, vk::CommandBuffer& upload_cmdbuf, @@ -143,7 +141,7 @@ VkResult MasterSemaphore::SubmitQueueTimeline(vk::CommandBuffer& cmdbuf, const VkSemaphore* p_wait_sems = (num_wait_semaphores > 0) ? &wait_semaphore : nullptr; const VkPipelineStageFlags* p_wait_masks = - (num_wait_semaphores > 0) ? wait_stage_masks.data() : nullptr; + (num_wait_semaphores > 0) ? &wait_stage_mask : nullptr; const VkSemaphore* p_signal_sems = (num_signal_semaphores > 0) ? signal_semaphores.data() : nullptr; const u64 wait_zero = 0; // dummy for binary wait @@ -180,7 +178,7 @@ VkResult MasterSemaphore::SubmitQueueFence(vk::CommandBuffer& cmdbuf, const VkSemaphore* p_wait_sems = (num_wait_semaphores > 0) ? &wait_semaphore : nullptr; const VkPipelineStageFlags* p_wait_masks = - (num_wait_semaphores > 0) ? wait_stage_masks.data() : nullptr; + (num_wait_semaphores > 0) ? &wait_stage_mask : nullptr; const VkSemaphore* p_signal_sems = (num_signal_semaphores > 0) ? &signal_semaphore : nullptr; const std::array cmdbuffers{*upload_cmdbuf, *cmdbuf}; diff --git a/src/video_core/renderer_vulkan/vk_scheduler.cpp b/src/video_core/renderer_vulkan/vk_scheduler.cpp index e526d606dc..0a032cdae0 100644 --- a/src/video_core/renderer_vulkan/vk_scheduler.cpp +++ b/src/video_core/renderer_vulkan/vk_scheduler.cpp @@ -270,8 +270,8 @@ u64 Scheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_se .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, }; - upload_cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, WRITE_BARRIER); + upload_cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, WRITE_BARRIER); upload_cmdbuf.End(); cmdbuf.End(); @@ -372,15 +372,9 @@ void Scheduler::EndRenderPass() }; } cmdbuf.EndRenderPass(); - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - 0, - nullptr, - nullptr, - vk::Span(barriers.data(), num_images) // Batched image barriers - ); + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, nullptr, nullptr, vk::Span(barriers.data(), num_images)); }); state.renderpass = nullptr; diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp index 348e49fb6d..d51564dcb3 100644 --- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp @@ -2500,7 +2500,7 @@ void TextureCacheRuntime::TransitionImageLayout(Image& image) { }; scheduler.RequestOutsideRenderPassOperationContext(); scheduler.Record([barrier](vk::CommandBuffer cmdbuf) { - cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, barrier); }); } diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index 3d98f2cbf7..15f48ca8f4 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -557,20 +557,12 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR } if (is_nvidia) { - const u32 nv_major_version = (properties.properties.driverVersion >> 22) & 0x3ff; const auto arch = GetNvidiaArch(); if (arch >= NvidiaArchitecture::Arch_AmpereOrNewer) { LOG_WARNING(Render_Vulkan, "Ampere and newer have broken float16 math"); features.shader_float16_int8.shaderFloat16 = false; } - if (nv_major_version >= 510) { - LOG_WARNING(Render_Vulkan, - "NVIDIA Drivers >= 510 do not support MSAA->MSAA image blits. " - "MSAA scaling will use 3D helpers. MSAA resolves work normally."); - cant_blit_msaa = true; - } - // Mali/ NVIDIA proprietary drivers: Shader stencil export not supported // Use hardware depth/stencil blits instead when available if (!extensions.shader_stencil_export) { From ea209e6dabdcd99f51dd2ae8b11adeb715b9668f Mon Sep 17 00:00:00 2001 From: MaranBr Date: Mon, 2 Mar 2026 02:53:01 +0100 Subject: [PATCH 018/145] [vulkan] Fine-tuning of frame pacing logic (#3628) It makes fine adjustments to the frame pacing, ensuring better stability and precision. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3628 Reviewed-by: crueter Reviewed-by: Lizzie Co-authored-by: MaranBr Co-committed-by: MaranBr --- src/video_core/renderer_vulkan/vk_scheduler.h | 47 +++++++++++-------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/src/video_core/renderer_vulkan/vk_scheduler.h b/src/video_core/renderer_vulkan/vk_scheduler.h index 2913211480..667f136ee6 100644 --- a/src/video_core/renderer_vulkan/vk_scheduler.h +++ b/src/video_core/renderer_vulkan/vk_scheduler.h @@ -16,8 +16,8 @@ #include "common/alignment.h" #include "common/common_types.h" -#include "common/settings.h" #include "common/polyfill_thread.h" +#include "common/settings.h" #include "video_core/renderer_vulkan/vk_master_semaphore.h" #include "video_core/vulkan_common/vulkan_wrapper.h" @@ -114,29 +114,36 @@ public: /// Waits for the given GPU tick, optionally pacing frames. void Wait(u64 tick, double target_fps = 0.0) { - if (Settings::values.use_speed_limit.GetValue() && target_fps > 0.0) { - const auto now = std::chrono::steady_clock::now(); - if (start_time == std::chrono::steady_clock::time_point{} || current_target_fps != target_fps) { - start_time = now; - frame_counter = 0; - current_target_fps = target_fps; - } - frame_counter++; - std::chrono::duration frame_interval(1.0 / current_target_fps); - auto target_time = start_time + frame_interval * frame_counter; - if (target_time > now) { - std::this_thread::sleep_until(target_time); - } else { - start_time = now; - frame_counter = 0; - } - } if (tick > 0) { if (tick >= master_semaphore->CurrentTick()) { Flush(); } master_semaphore->Wait(tick); } + if (Settings::values.use_speed_limit.GetValue() && target_fps > 0.0) { + auto now = std::chrono::steady_clock::now(); + if (last_target_fps != target_fps) { + frame_interval = std::chrono::duration_cast(std::chrono::duration(1.0 / target_fps)); + max_frame_count = static_cast(0.1 * target_fps); + last_target_fps = target_fps; + frame_counter = 0; + start_time = now; + } + frame_counter++; + auto target_time = start_time + frame_interval * frame_counter; + if (target_time >= now) { + auto sleep_time = target_time - now; + if (sleep_time > std::chrono::milliseconds(15)) { + std::this_thread::sleep_for(sleep_time - std::chrono::milliseconds(1)); + } + while (std::chrono::steady_clock::now() < target_time) { + std::this_thread::yield(); + } + } else if (frame_counter > max_frame_count) { + frame_counter = 0; + start_time = now; + } + } } /// Returns the master timeline semaphore. @@ -281,9 +288,11 @@ private: std::condition_variable_any event_cv; std::jthread worker_thread; + std::chrono::steady_clock::duration frame_interval{}; std::chrono::steady_clock::time_point start_time{}; + double last_target_fps{}; + u64 max_frame_count{}; u64 frame_counter{}; - double current_target_fps{}; }; } // namespace Vulkan From 464212393e296c59488171692df1d096ecfa5607 Mon Sep 17 00:00:00 2001 From: crueter Date: Mon, 2 Mar 2026 05:28:26 +0100 Subject: [PATCH 019/145] [gitignore] add *.tar.zst (#3663) the amount of times I've accidentally committed a tar.zst to this repository... Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3663 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0be76d85cd..67bdd8adf4 100644 --- a/.gitignore +++ b/.gitignore @@ -63,3 +63,4 @@ artifacts *.AppImage* /install* vulkansdk*.exe +*.tar.zst From d720a7b4b4e3c2bc4f7e2c1b16e282ec91766aa8 Mon Sep 17 00:00:00 2001 From: tarako Date: Tue, 3 Mar 2026 01:54:57 +0100 Subject: [PATCH 020/145] [vulkan] Fixed dual-source blending to correctly map shader outputs. (#3637) Fixes Skyward Sword HD eye gitch and a related MoltenVK crash due to the incorrect output mapping. Verified working on mac and android. The test in vk_pipeline_cache.cpp is a bit ugly, but it didn't seem worth it to go lambda/macro just to make it look cleaner. Could change if necessary. Co-authored-by: tarako Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3637 Reviewed-by: CamilleLaVey Co-authored-by: tarako Co-committed-by: tarako --- .../backend/spirv/emit_spirv_special.cpp | 14 +++++++++ .../backend/spirv/spirv_emit_context.cpp | 15 ++++++++-- src/shader_recompiler/runtime_info.h | 3 ++ .../renderer_vulkan/vk_pipeline_cache.cpp | 30 ++++++++++++++++++- 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp index fe5e70a63b..8eca1fac29 100644 --- a/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp +++ b/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -91,6 +94,17 @@ void AlphaTest(EmitContext& ctx) { } // Anonymous namespace void EmitPrologue(EmitContext& ctx) { + if (ctx.stage == Stage::Fragment && ctx.runtime_info.dual_source_blend) { + // Initialize dual-source blending outputs - prevents MoltenVK crash. + const Id zero{ctx.Const(0.0f)}; + const Id one{ctx.Const(1.0f)}; + const Id default_color{ctx.ConstantComposite(ctx.F32[4], zero, zero, zero, one)}; + for (u32 i = 0; i < 2; ++i) { + if (Sirit::ValidId(ctx.frag_color[i])) { + ctx.OpStore(ctx.frag_color[i], default_color); + } + } + } if (ctx.stage == Stage::VertexB) { const Id zero{ctx.Const(0.0f)}; const Id one{ctx.Const(1.0f)}; diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp index cd3394bdf0..b9a24496c9 100644 --- a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp +++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp @@ -1670,13 +1670,22 @@ void EmitContext::DefineOutputs(const IR::Program& program) { break; case Stage::Fragment: for (u32 index = 0; index < 8; ++index) { - if (!info.stores_frag_color[index] && !profile.need_declared_frag_colors) { + const bool need_dual_source = runtime_info.dual_source_blend && index <= 1; + if (!need_dual_source && !info.stores_frag_color[index] && + !profile.need_declared_frag_colors) { continue; } const Id type{GetAttributeType(*this, runtime_info.color_output_types[index])}; frag_color[index] = DefineOutput(*this, type, std::nullopt); - Decorate(frag_color[index], spv::Decoration::Location, index); - Name(frag_color[index], fmt::format("frag_color{}", index)); + // Correct mapping for dual-source blending + if (runtime_info.dual_source_blend && index <= 1) { + Decorate(frag_color[index], spv::Decoration::Location, 0u); + Decorate(frag_color[index], spv::Decoration::Index, index); + Name(frag_color[index], index == 0 ? "frag_color0" : "frag_color0_secondary"); + } else { + Decorate(frag_color[index], spv::Decoration::Location, index); + Name(frag_color[index], fmt::format("frag_color{}", index)); + } } if (info.stores_frag_depth) { frag_depth = DefineOutput(*this, F32[1], std::nullopt); diff --git a/src/shader_recompiler/runtime_info.h b/src/shader_recompiler/runtime_info.h index 613c598d0c..be10a9bb08 100644 --- a/src/shader_recompiler/runtime_info.h +++ b/src/shader_recompiler/runtime_info.h @@ -110,6 +110,9 @@ struct RuntimeInfo { /// Output types for each color attachment std::array color_output_types{}; + + /// Dual source blending + bool dual_source_blend{}; }; } // namespace Shader diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp index f3dd0f90d8..77a4e8616a 100644 --- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp @@ -237,11 +237,38 @@ Shader::RuntimeInfo MakeRuntimeInfo(std::span program } info.convert_depth_mode = gl_ndc; break; - case Shader::Stage::Fragment: + case Shader::Stage::Fragment: { info.alpha_test_func = MaxwellToCompareFunction( key.state.UnpackComparisonOp(key.state.alpha_test_func.Value())); info.alpha_test_reference = std::bit_cast(key.state.alpha_test_ref); + // Check for dual source blending + const auto& blend0 = key.state.attachments[0]; + if (blend0.enable != 0) { + using F = Maxwell::Blend::Factor; + const auto src_rgb = blend0.SourceRGBFactor(); + const auto dst_rgb = blend0.DestRGBFactor(); + const auto src_a = blend0.SourceAlphaFactor(); + const auto dst_a = blend0.DestAlphaFactor(); + info.dual_source_blend = + src_rgb == F::Source1Color_D3D || src_rgb == F::OneMinusSource1Color_D3D || + src_rgb == F::Source1Alpha_D3D || src_rgb == F::OneMinusSource1Alpha_D3D || + src_rgb == F::Source1Color_GL || src_rgb == F::OneMinusSource1Color_GL || + src_rgb == F::Source1Alpha_GL || src_rgb == F::OneMinusSource1Alpha_GL || + dst_rgb == F::Source1Color_D3D || dst_rgb == F::OneMinusSource1Color_D3D || + dst_rgb == F::Source1Alpha_D3D || dst_rgb == F::OneMinusSource1Alpha_D3D || + dst_rgb == F::Source1Color_GL || dst_rgb == F::OneMinusSource1Color_GL || + dst_rgb == F::Source1Alpha_GL || dst_rgb == F::OneMinusSource1Alpha_GL || + src_a == F::Source1Color_D3D || src_a == F::OneMinusSource1Color_D3D || + src_a == F::Source1Alpha_D3D || src_a == F::OneMinusSource1Alpha_D3D || + src_a == F::Source1Color_GL || src_a == F::OneMinusSource1Color_GL || + src_a == F::Source1Alpha_GL || src_a == F::OneMinusSource1Alpha_GL || + dst_a == F::Source1Color_D3D || dst_a == F::OneMinusSource1Color_D3D || + dst_a == F::Source1Alpha_D3D || dst_a == F::OneMinusSource1Alpha_D3D || + dst_a == F::Source1Color_GL || dst_a == F::OneMinusSource1Color_GL || + dst_a == F::Source1Alpha_GL || dst_a == F::OneMinusSource1Alpha_GL; + } + if (device.IsMoltenVK()) { for (size_t i = 0; i < 8; ++i) { const auto format = static_cast(key.state.color_formats[i]); @@ -258,6 +285,7 @@ Shader::RuntimeInfo MakeRuntimeInfo(std::span program } } break; + } default: break; } From 9d2341eaeafb275d3d3e4692812fe121ae24e2e3 Mon Sep 17 00:00:00 2001 From: PavelBARABANOV Date: Tue, 3 Mar 2026 14:27:47 +0100 Subject: [PATCH 021/145] [vk] Disable float16 math on non-MESA AMD drivers as 2026+ versions are broken (#3661) thanks MaranBR Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3661 Reviewed-by: MaranBr Reviewed-by: Maufeat Co-authored-by: PavelBARABANOV Co-committed-by: PavelBARABANOV --- src/video_core/vulkan_common/vulkan_device.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index 15f48ca8f4..a2ff3ee6ed 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -586,12 +586,20 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR if (is_amd_driver) { // AMD drivers need a higher amount of Sets per Pool in certain circumstances like in XC2. sets_per_pool = 96; + // Disable VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT on AMD GCN4 and lower as it is broken. if (!features.shader_float16_int8.shaderFloat16) { LOG_WARNING(Render_Vulkan, "AMD GCN4 and earlier have broken VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT"); has_broken_cube_compatibility = true; } + + // AMD drivers (2026+) have broken float16 math on DKCR + if (features.shader_float16_int8.shaderFloat16) { + LOG_WARNING(Render_Vulkan, + "AMD drivers (2026+) have broken float16 math"); + features.shader_float16_int8.shaderFloat16 = false; + } } if (is_qualcomm) { From c682306788055c57953aea38fdded95a0c6dfc09 Mon Sep 17 00:00:00 2001 From: wildcard Date: Wed, 4 Mar 2026 22:46:55 +0100 Subject: [PATCH 022/145] [vulkan] Implement push descriptors for compute pipelines (#3666) Implements push descriptor for compute pipelines along with a bug fix, the increment logic was, offset += sizeof(DescriptorUpdateEntry); This only advances the byte offset by a single descriptor slot, regardless of the array's size (descriptorCount).Now suppose if a shader utilized an array of descriptors (eg, layout(binding = 0) uniform sampler2D textures[4]) and if this happened to fit within the MaxPushDescriptors limit, the template would consume 4 * sizeof(DescriptorUpdateEntry) bytes, but the offset for the next binding would only advance by 1 slot. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3666 Reviewed-by: MaranBr Co-authored-by: wildcard Co-committed-by: wildcard --- .../renderer_vulkan/pipeline_helper.h | 8 +++++-- .../renderer_vulkan/vk_compute_pipeline.cpp | 24 ++++++++++++------- .../renderer_vulkan/vk_compute_pipeline.h | 4 ++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/video_core/renderer_vulkan/pipeline_helper.h b/src/video_core/renderer_vulkan/pipeline_helper.h index 910e07a606..e88b27b273 100644 --- a/src/video_core/renderer_vulkan/pipeline_helper.h +++ b/src/video_core/renderer_vulkan/pipeline_helper.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -61,7 +64,8 @@ public: .pDescriptorUpdateEntries = entries.data(), .templateType = type, .descriptorSetLayout = descriptor_set_layout, - .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .pipelineBindPoint = + is_compute ? VK_PIPELINE_BIND_POINT_COMPUTE : VK_PIPELINE_BIND_POINT_GRAPHICS, .pipelineLayout = pipeline_layout, .set = 0, }); @@ -122,7 +126,7 @@ private: }); ++binding; num_descriptors += descriptors[i].count; - offset += sizeof(DescriptorUpdateEntry); + offset += sizeof(DescriptorUpdateEntry) * descriptors[i].count; } } diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp index 51b5141a06..6a6fe2b830 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp @@ -50,11 +50,14 @@ ComputePipeline::ComputePipeline(const Device& device_, vk::PipelineCache& pipel DescriptorLayoutBuilder builder{device}; builder.Add(info, VK_SHADER_STAGE_COMPUTE_BIT); - descriptor_set_layout = builder.CreateDescriptorSetLayout(false); + uses_push_descriptor = builder.CanUsePushDescriptor(); + descriptor_set_layout = builder.CreateDescriptorSetLayout(uses_push_descriptor); pipeline_layout = builder.CreatePipelineLayout(*descriptor_set_layout); descriptor_update_template = - builder.CreateTemplate(*descriptor_set_layout, *pipeline_layout, false); - descriptor_allocator = descriptor_pool.Allocator(*descriptor_set_layout, info); + builder.CreateTemplate(*descriptor_set_layout, *pipeline_layout, uses_push_descriptor); + if (!uses_push_descriptor) { + descriptor_allocator = descriptor_pool.Allocator(*descriptor_set_layout, info); + } const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT subgroup_size_ci{ .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT, .pNext = nullptr, @@ -241,11 +244,16 @@ void ComputePipeline::Configure(Tegra::Engines::KeplerCompute& kepler_compute, RESCALING_LAYOUT_WORDS_OFFSET, sizeof(rescaling_data), rescaling_data.data()); } - const VkDescriptorSet descriptor_set{descriptor_allocator.Commit()}; - const vk::Device& dev{device.GetLogical()}; - dev.UpdateDescriptorSet(descriptor_set, *descriptor_update_template, descriptor_data); - cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline_layout, 0, - descriptor_set, nullptr); + if (uses_push_descriptor) { + cmdbuf.PushDescriptorSetWithTemplateKHR(*descriptor_update_template, *pipeline_layout, + 0, descriptor_data); + } else { + const VkDescriptorSet descriptor_set{descriptor_allocator.Commit()}; + const vk::Device& dev{device.GetLogical()}; + dev.UpdateDescriptorSet(descriptor_set, *descriptor_update_template, descriptor_data); + cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline_layout, 0, + descriptor_set, nullptr); + } }); } diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.h b/src/video_core/renderer_vulkan/vk_compute_pipeline.h index d1a1e2c46d..aa84c00e12 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pipeline.h +++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -55,6 +58,7 @@ private: vk::ShaderModule spv_module; vk::DescriptorSetLayout descriptor_set_layout; + bool uses_push_descriptor{false}; DescriptorAllocator descriptor_allocator; vk::PipelineLayout pipeline_layout; vk::DescriptorUpdateTemplate descriptor_update_template; From 7f5de6bcd651f8145e4746c76d0531b6560fd5e4 Mon Sep 17 00:00:00 2001 From: xbzk Date: Wed, 4 Mar 2026 22:51:35 +0100 Subject: [PATCH 023/145] [android/fs] external content loader + nca/xci patches (#3596) Foreword: WHY DON'T EVERYBODY USE ONE FOLDER FOR EACH GAME+CONTENTS? AIN'T THIS THE FORMAT GAMES COME WHEN YOU BUE THEM? DO YOU LIVE WITH ALL YOUR FRIENDS AND HAVE A 2ND HOUSE FOR ALL THE CHILDREN? Nice, i feel better now. This feat extends Maufeat's work on external content loading. It harmonically additions: "...also, if in each game folder X, you find a folder Y, and in this folder Y you detect ONLY a single game, then mount all external content for that game found in that folder Y and its subfolders." Permanent (not toggleable). External Content folders are supported equally. Also: -Reworked several routines for preserving single source of truth between android and other systems; -Fixed the annoying unknown format error for content files, by providing proper format detection. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3596 Reviewed-by: MaranBr Reviewed-by: Lizzie Co-authored-by: xbzk Co-committed-by: xbzk --- .../java/org/yuzu/yuzu_emu/NativeLibrary.kt | 6 + .../org/yuzu/yuzu_emu/model/AddonViewModel.kt | 6 +- .../org/yuzu/yuzu_emu/ui/main/MainActivity.kt | 4 +- .../org/yuzu/yuzu_emu/utils/GameHelper.kt | 64 ++- .../app/src/main/jni/android_config.cpp | 6 + .../app/src/main/jni/game_metadata.cpp | 5 + src/android/app/src/main/jni/native.cpp | 116 +---- src/android/app/src/main/jni/native.h | 4 + src/common/settings.h | 2 + src/core/file_sys/patch_manager.cpp | 27 +- src/core/file_sys/registered_cache.cpp | 473 +++++++++--------- src/core/file_sys/registered_cache.h | 5 +- src/core/loader/loader.cpp | 70 ++- src/core/loader/loader.h | 22 +- src/core/loader/nsp.cpp | 36 +- src/core/loader/xci.cpp | 14 +- src/yuzu/game/game_list_worker.cpp | 22 +- src/yuzu/main_window.cpp | 19 +- 18 files changed, 477 insertions(+), 424 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt index 1f0acf2835..397b44c9f9 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt @@ -607,6 +607,12 @@ object NativeLibrary { */ external fun addFileToFilesystemProvider(path: String) + /** + * Adds a game-folder file to the manual filesystem provider, respecting the internal gate for + * game-folder external-content mounting. + */ + external fun addGameFolderFileToFilesystemProvider(path: String) + /** * Clears all files added to the manual filesystem provider in our EmulationSession instance */ diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/AddonViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/AddonViewModel.kt index c682a13cfc..2a0e72be26 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/AddonViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/AddonViewModel.kt @@ -127,10 +127,6 @@ class AddonViewModel : ViewModel() { return } - // Check if there are multiple update versions - val updates = _patchList.value.filter { PatchType.from(it.type) == PatchType.Update } - val hasMultipleUpdates = updates.size > 1 - NativeConfig.setDisabledAddons( game!!.programId, _patchList.value.mapNotNull { @@ -140,7 +136,7 @@ class AddonViewModel : ViewModel() { if (PatchType.from(it.type) == PatchType.Update) { if (it.name.contains("(NAND)") || it.name.contains("(SDMC)")) { it.name - } else if (hasMultipleUpdates) { + } else if (it.numericVersion != 0L) { "Update@${it.numericVersion}" } else { it.name diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt index 8a4262ebe7..db4cc0f60e 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt @@ -424,7 +424,9 @@ class MainActivity : AppCompatActivity(), ThemeProvider { ) val uriString = result.toString() - val folder = gamesViewModel.folders.value.firstOrNull { it.uriString == uriString } + val folder = gamesViewModel.folders.value.firstOrNull { + it.uriString == uriString && it.type == org.yuzu.yuzu_emu.model.DirectoryType.EXTERNAL_CONTENT + } if (folder != null) { Toast.makeText( applicationContext, diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameHelper.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameHelper.kt index fff5fdfb9b..4a3cf61daa 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameHelper.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameHelper.kt @@ -51,11 +51,24 @@ object GameHelper { // Scan External Content directories and register all NSP/XCI files val externalContentDirs = NativeConfig.getExternalContentDirs() - for (externalDir in externalContentDirs) { + val uniqueExternalContentDirs = linkedSetOf() + externalContentDirs.forEach { externalDir -> + if (externalDir.isNotEmpty()) { + uniqueExternalContentDirs.add(externalDir) + } + } + + val mountedContainerUris = mutableSetOf() + for (externalDir in uniqueExternalContentDirs) { if (externalDir.isNotEmpty()) { val externalDirUri = externalDir.toUri() if (FileUtil.isTreeUriValid(externalDirUri)) { - scanExternalContentRecursive(FileUtil.listFiles(externalDirUri), 3) + scanContentContainersRecursive(FileUtil.listFiles(externalDirUri), 3) { + val containerUri = it.uri.toString() + if (mountedContainerUris.add(containerUri)) { + NativeLibrary.addFileToFilesystemProvider(containerUri) + } + } } } } @@ -65,10 +78,13 @@ object GameHelper { val gameDirUri = gameDir.uriString.toUri() val isValid = FileUtil.isTreeUriValid(gameDirUri) if (isValid) { + val scanDepth = if (gameDir.deepScan) 3 else 1 + addGamesRecursive( games, FileUtil.listFiles(gameDirUri), - if (gameDir.deepScan) 3 else 1 + scanDepth, + mountedContainerUris ) } else { badDirs.add(index) @@ -103,9 +119,10 @@ object GameHelper { // be done better imo. private val externalContentExtensions = setOf("nsp", "xci") - private fun scanExternalContentRecursive( + private fun scanContentContainersRecursive( files: Array, - depth: Int + depth: Int, + onContainerFound: (MinimalDocumentFile) -> Unit ) { if (depth <= 0) { return @@ -113,14 +130,15 @@ object GameHelper { files.forEach { if (it.isDirectory) { - scanExternalContentRecursive( + scanContentContainersRecursive( FileUtil.listFiles(it.uri), - depth - 1 + depth - 1, + onContainerFound ) } else { val extension = FileUtil.getExtension(it.uri).lowercase() if (externalContentExtensions.contains(extension)) { - NativeLibrary.addFileToFilesystemProvider(it.uri.toString()) + onContainerFound(it) } } } @@ -129,7 +147,8 @@ object GameHelper { private fun addGamesRecursive( games: MutableList, files: Array, - depth: Int + depth: Int, + mountedContainerUris: MutableSet ) { if (depth <= 0) { return @@ -140,11 +159,20 @@ object GameHelper { addGamesRecursive( games, FileUtil.listFiles(it.uri), - depth - 1 + depth - 1, + mountedContainerUris ) } else { - if (Game.extensions.contains(FileUtil.getExtension(it.uri))) { - val game = getGame(it.uri, true) + val extension = FileUtil.getExtension(it.uri).lowercase() + val filePath = it.uri.toString() + + if (externalContentExtensions.contains(extension) && + mountedContainerUris.add(filePath)) { + NativeLibrary.addGameFolderFileToFilesystemProvider(filePath) + } + + if (Game.extensions.contains(extension)) { + val game = getGame(it.uri, true, false) if (game != null) { games.add(game) } @@ -153,14 +181,20 @@ object GameHelper { } } - fun getGame(uri: Uri, addedToLibrary: Boolean): Game? { + fun getGame( + uri: Uri, + addedToLibrary: Boolean, + registerFilesystemProvider: Boolean = true + ): Game? { val filePath = uri.toString() if (!GameMetadata.getIsValid(filePath)) { return null } - // Needed to update installed content information - NativeLibrary.addFileToFilesystemProvider(filePath) + if (registerFilesystemProvider) { + // Needed to update installed content information + NativeLibrary.addFileToFilesystemProvider(filePath) + } var name = GameMetadata.getTitle(filePath) diff --git a/src/android/app/src/main/jni/android_config.cpp b/src/android/app/src/main/jni/android_config.cpp index 0171e2a7b3..0c5696ef3f 100644 --- a/src/android/app/src/main/jni/android_config.cpp +++ b/src/android/app/src/main/jni/android_config.cpp @@ -33,6 +33,12 @@ void AndroidConfig::ReadAndroidValues() { if (global) { ReadAndroidUIValues(); ReadUIValues(); + BeginGroup(Settings::TranslateCategory(Settings::Category::DataStorage)); + Settings::values.ext_content_from_game_dirs = ReadBooleanSetting( + std::string("ext_content_from_game_dirs"), + std::make_optional( + Settings::values.ext_content_from_game_dirs.GetDefault())); + EndGroup(); ReadOverlayValues(); } ReadDriverValues(); diff --git a/src/android/app/src/main/jni/game_metadata.cpp b/src/android/app/src/main/jni/game_metadata.cpp index e9c03b6440..9acba456f1 100644 --- a/src/android/app/src/main/jni/game_metadata.cpp +++ b/src/android/app/src/main/jni/game_metadata.cpp @@ -96,6 +96,11 @@ jboolean Java_org_yuzu_yuzu_1emu_utils_GameMetadata_getIsValid(JNIEnv* env, jobj return false; } + if ((file_type == Loader::FileType::NSP || file_type == Loader::FileType::XCI) && + !Loader::IsBootableGameContainer(file, file_type)) { + return false; + } + u64 program_id = 0; Loader::ResultStatus res = loader->ReadProgramId(program_id); if (res != Loader::ResultStatus::Success) { diff --git a/src/android/app/src/main/jni/native.cpp b/src/android/app/src/main/jni/native.cpp index c429f4a1e4..3f0029c78a 100644 --- a/src/android/app/src/main/jni/native.cpp +++ b/src/android/app/src/main/jni/native.cpp @@ -217,107 +217,8 @@ void EmulationSession::ConfigureFilesystemProvider(const std::string& filepath) return; } - const auto extension = Common::ToLower(filepath.substr(filepath.find_last_of('.') + 1)); - - if (extension == "nsp") { - auto nsp = std::make_shared(file); - if (nsp->GetStatus() == Loader::ResultStatus::Success) { - std::map nsp_versions; - std::map nsp_version_strings; - - for (const auto& [title_id, nca_map] : nsp->GetNCAs()) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (content_type == FileSys::ContentRecordType::Meta) { - const auto meta_nca = std::make_shared(nca->GetBaseFile()); - if (meta_nca->GetStatus() == Loader::ResultStatus::Success) { - const auto section0 = meta_nca->GetSubdirectories(); - if (!section0.empty()) { - for (const auto& meta_file : section0[0]->GetFiles()) { - if (meta_file->GetExtension() == "cnmt") { - FileSys::CNMT cnmt(meta_file); - nsp_versions[cnmt.GetTitleID()] = cnmt.GetTitleVersion(); - } - } - } - } - } - - if (content_type == FileSys::ContentRecordType::Control && - title_type == FileSys::TitleType::Update) { - auto romfs = nca->GetRomFS(); - if (romfs) { - auto extracted = FileSys::ExtractRomFS(romfs); - if (extracted) { - auto nacp_file = extracted->GetFile("control.nacp"); - if (!nacp_file) { - nacp_file = extracted->GetFile("Control.nacp"); - } - if (nacp_file) { - FileSys::NACP nacp(nacp_file); - auto ver_str = nacp.GetVersionString(); - if (!ver_str.empty()) { - nsp_version_strings[title_id] = ver_str; - } - } - } - } - } - } - } - - for (const auto& [title_id, nca_map] : nsp->GetNCAs()) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (title_type == FileSys::TitleType::Update) { - u32 version = 0; - auto ver_it = nsp_versions.find(title_id); - if (ver_it != nsp_versions.end()) { - version = ver_it->second; - } - - std::string version_string; - auto str_it = nsp_version_strings.find(title_id); - if (str_it != nsp_version_strings.end()) { - version_string = str_it->second; - } - - m_manual_provider->AddEntryWithVersion( - title_type, content_type, title_id, version, version_string, - nca->GetBaseFile()); - - LOG_DEBUG(Frontend, "Added NSP update entry - TitleID: {:016X}, Version: {}, VersionStr: {}", - title_id, version, version_string); - } else { - // Use regular AddEntry for non-updates - m_manual_provider->AddEntry(title_type, content_type, title_id, - nca->GetBaseFile()); - LOG_DEBUG(Frontend, "Added NSP entry - TitleID: {:016X}, TitleType: {}, ContentType: {}", - title_id, static_cast(title_type), static_cast(content_type)); - } - } - } - return; - } - } - - // Handle XCI files - if (extension == "xci") { - FileSys::XCI xci{file}; - if (xci.GetStatus() == Loader::ResultStatus::Success) { - const auto nsp = xci.GetSecurePartitionNSP(); - if (nsp) { - for (const auto& title : nsp->GetNCAs()) { - for (const auto& entry : title.second) { - m_manual_provider->AddEntry(entry.first.first, entry.first.second, title.first, - entry.second->GetBaseFile()); - } - } - } - return; - } + if (m_manual_provider->AddEntriesFromContainer(file)) { + return; } auto loader = Loader::GetLoader(m_system, file); @@ -339,6 +240,13 @@ void EmulationSession::ConfigureFilesystemProvider(const std::string& filepath) } } +void EmulationSession::ConfigureFilesystemProviderFromGameFolder(const std::string& filepath) { + if (!Settings::values.ext_content_from_game_dirs.GetValue()) { + return; + } + ConfigureFilesystemProvider(filepath); +} + void EmulationSession::InitializeSystem(bool reload) { if (!reload) { // Initialize logging system @@ -1609,6 +1517,12 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_addFileToFilesystemProvider(JNIEnv* e Common::Android::GetJString(env, jpath)); } +void Java_org_yuzu_yuzu_1emu_NativeLibrary_addGameFolderFileToFilesystemProvider( + JNIEnv* env, jobject jobj, jstring jpath) { + EmulationSession::GetInstance().ConfigureFilesystemProviderFromGameFolder( + Common::Android::GetJString(env, jpath)); +} + void Java_org_yuzu_yuzu_1emu_NativeLibrary_clearFilesystemProvider(JNIEnv* env, jobject jobj) { EmulationSession::GetInstance().GetContentProvider()->ClearAllEntries(); } diff --git a/src/android/app/src/main/jni/native.h b/src/android/app/src/main/jni/native.h index dfbc8b2943..f2e5c2cfd6 100644 --- a/src/android/app/src/main/jni/native.h +++ b/src/android/app/src/main/jni/native.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -46,6 +49,7 @@ public: const Core::PerfStatsResults& PerfStats(); int ShadersBuilding(); void ConfigureFilesystemProvider(const std::string& filepath); + void ConfigureFilesystemProviderFromGameFolder(const std::string& filepath); void InitializeSystem(bool reload); void SetAppletId(int applet_id); Core::SystemResultStatus InitializeEmulation(const std::string& filepath, diff --git a/src/common/settings.h b/src/common/settings.h index 7ea4136576..7c6c0d062f 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -756,6 +756,8 @@ struct Values { Category::DataStorage}; Setting gamecard_path{linkage, std::string(), "gamecard_path", Category::DataStorage}; + Setting ext_content_from_game_dirs{linkage, true, "ext_content_from_game_dirs", + Category::DataStorage}; std::vector external_content_dirs; // Debugging diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp index 82944ceceb..e9c3bb75c2 100644 --- a/src/core/file_sys/patch_manager.cpp +++ b/src/core/file_sys/patch_manager.cpp @@ -117,6 +117,12 @@ void AppendCommaIfNotEmpty(std::string& to, std::string_view with) { bool IsDirValidAndNonEmpty(const VirtualDir& dir) { return dir != nullptr && (!dir->GetFiles().empty() || !dir->GetSubdirectories().empty()); } + +bool IsVersionedExternalUpdateDisabled(const std::vector& disabled, u32 version) { + const std::string disabled_key = fmt::format("Update@{}", version); + return std::find(disabled.cbegin(), disabled.cend(), disabled_key) != disabled.cend() || + std::find(disabled.cbegin(), disabled.cend(), "Update") != disabled.cend(); +} } // Anonymous namespace PatchManager::PatchManager(u64 title_id_, @@ -155,8 +161,7 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const { if (!update_versions.empty()) { checked_external = true; for (const auto& update_entry : update_versions) { - std::string disabled_key = fmt::format("Update@{}", update_entry.version); - if (std::find(disabled.cbegin(), disabled.cend(), disabled_key) == disabled.cend()) { + if (!IsVersionedExternalUpdateDisabled(disabled, update_entry.version)) { update_disabled = false; enabled_version = update_entry.version; break; @@ -175,8 +180,7 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const { if (!manual_update_versions.empty()) { checked_manual = true; for (const auto& update_entry : manual_update_versions) { - std::string disabled_key = fmt::format("Update@{}", update_entry.version); - if (std::find(disabled.cbegin(), disabled.cend(), disabled_key) == disabled.cend()) { + if (!IsVersionedExternalUpdateDisabled(disabled, update_entry.version)) { update_disabled = false; enabled_version = update_entry.version; break; @@ -580,8 +584,7 @@ VirtualFile PatchManager::PatchRomFS(const NCA* base_nca, VirtualFile base_romfs if (!update_versions.empty()) { checked_external = true; for (const auto& update_entry : update_versions) { - std::string disabled_key = fmt::format("Update@{}", update_entry.version); - if (std::find(disabled.cbegin(), disabled.cend(), disabled_key) == disabled.cend()) { + if (!IsVersionedExternalUpdateDisabled(disabled, update_entry.version)) { update_disabled = false; enabled_version = update_entry.version; update_raw = external_provider->GetEntryForVersion(update_tid, type, update_entry.version); @@ -600,8 +603,7 @@ VirtualFile PatchManager::PatchRomFS(const NCA* base_nca, VirtualFile base_romfs if (!manual_update_versions.empty()) { checked_manual = true; for (const auto& update_entry : manual_update_versions) { - std::string disabled_key = fmt::format("Update@{}", update_entry.version); - if (std::find(disabled.cbegin(), disabled.cend(), disabled_key) == disabled.cend()) { + if (!IsVersionedExternalUpdateDisabled(disabled, update_entry.version)) { update_disabled = false; enabled_version = update_entry.version; update_raw = manual_provider->GetEntryForVersion(update_tid, type, update_entry.version); @@ -704,9 +706,8 @@ std::vector PatchManager::GetPatches(VirtualFile update_raw) const { version_str = FormatTitleVersion(update_entry.version); } - std::string disabled_key = fmt::format("Update@{}", update_entry.version); const auto update_disabled = - std::find(disabled.cbegin(), disabled.cend(), disabled_key) != disabled.cend(); + IsVersionedExternalUpdateDisabled(disabled, update_entry.version); Patch update_patch = {.enabled = !update_disabled, .name = "Update", @@ -732,9 +733,8 @@ std::vector PatchManager::GetPatches(VirtualFile update_raw) const { version_str = FormatTitleVersion(update_entry.version); } - std::string disabled_key = fmt::format("Update@{}", update_entry.version); const auto update_disabled = - std::find(disabled.cbegin(), disabled.cend(), disabled_key) != disabled.cend(); + IsVersionedExternalUpdateDisabled(disabled, update_entry.version); Patch update_patch = {.enabled = !update_disabled, @@ -771,7 +771,8 @@ std::vector PatchManager::GetPatches(VirtualFile update_raw) const { std::nullopt, std::nullopt, ContentRecordType::Program, update_tid); for (const auto& [slot, entry] : all_updates) { - if (slot == ContentProviderUnionSlot::External) { + if (slot == ContentProviderUnionSlot::External || + slot == ContentProviderUnionSlot::FrontendManual) { continue; } diff --git a/src/core/file_sys/registered_cache.cpp b/src/core/file_sys/registered_cache.cpp index 7bf2ad8fcd..020d403c95 100644 --- a/src/core/file_sys/registered_cache.cpp +++ b/src/core/file_sys/registered_cache.cpp @@ -104,6 +104,206 @@ static std::string GetCNMTName(TitleType type, u64 title_id) { return fmt::format("{}_{:016x}.cnmt", TITLE_TYPE_NAMES[index], title_id); } +static std::shared_ptr OpenContainerAsNsp(const VirtualFile& file, Loader::FileType type) { + if (!file) { + return nullptr; + } + + if (type == Loader::FileType::Unknown || type == Loader::FileType::Error) { + type = Loader::IdentifyFile(file); + if (type == Loader::FileType::Unknown) { + type = Loader::GuessFromFilename(file->GetName()); + } + } + + if (type == Loader::FileType::NSP) { + auto nsp = std::make_shared(file); + return nsp->GetStatus() == Loader::ResultStatus::Success ? nsp : nullptr; + } + + if (type == Loader::FileType::XCI) { + XCI xci(file); + if (xci.GetStatus() != Loader::ResultStatus::Success) { + return nullptr; + } + + auto secure_partition = xci.GetSecurePartitionNSP(); + if (secure_partition == nullptr) { + return nullptr; + } + + return secure_partition; + } + + // SAF-backed files can occasionally fail type-guessing despite being valid NSP/XCI. + // As a last resort, probe both container parsers directly. + { + auto nsp = std::make_shared(file); + if (nsp->GetStatus() == Loader::ResultStatus::Success) { + return nsp; + } + } + { + XCI xci(file); + if (xci.GetStatus() == Loader::ResultStatus::Success) { + auto secure_partition = xci.GetSecurePartitionNSP(); + if (secure_partition != nullptr) { + return secure_partition; + } + } + } + + return nullptr; +} + +template +bool ForEachContainerEntry(const std::shared_ptr& nsp, bool only_content, + std::optional base_program_id, Callback&& on_entry) { + if (!nsp) { + return false; + } + + const auto& ncas = nsp->GetNCAs(); + if (ncas.empty()) { + return false; + } + + std::map versions; + std::map version_strings; + + for (const auto& [title_id, nca_map] : ncas) { + for (const auto& [type_pair, nca] : nca_map) { + if (!nca) { + continue; + } + + const auto& [title_type, content_type] = type_pair; + + if (content_type == ContentRecordType::Meta) { + const auto subdirs = nca->GetSubdirectories(); + if (!subdirs.empty()) { + for (const auto& inner_file : subdirs[0]->GetFiles()) { + if (inner_file->GetExtension() == "cnmt") { + const CNMT cnmt(inner_file); + versions[cnmt.GetTitleID()] = cnmt.GetTitleVersion(); + break; + } + } + } + } + + if (title_type == TitleType::Update && content_type == ContentRecordType::Control) { + const auto romfs = nca->GetRomFS(); + if (!romfs) { + continue; + } + + const auto extracted = ExtractRomFS(romfs); + if (!extracted) { + continue; + } + + auto nacp_file = extracted->GetFile("control.nacp"); + if (!nacp_file) { + nacp_file = extracted->GetFile("Control.nacp"); + } + if (!nacp_file) { + continue; + } + + const NACP nacp(nacp_file); + auto version_string = nacp.GetVersionString(); + if (!version_string.empty()) { + version_strings[title_id] = std::move(version_string); + } + } + } + } + + bool added_entries = false; + for (const auto& [title_id, nca_map] : ncas) { + if (base_program_id.has_value() && GetBaseTitleID(title_id) != *base_program_id) { + continue; + } + + for (const auto& [type_pair, nca] : nca_map) { + const auto& [title_type, content_type] = type_pair; + if (only_content && title_type != TitleType::Update && title_type != TitleType::AOC) { + continue; + } + + auto entry_file = nca ? nca->GetBaseFile() : nullptr; + if (!entry_file) { + continue; + } + + u32 version = 0; + std::string version_string; + + if (title_type == TitleType::Update) { + if (const auto version_it = versions.find(title_id); version_it != versions.end()) { + version = version_it->second; + } + + if (const auto version_str_it = version_strings.find(title_id); + version_str_it != version_strings.end()) { + version_string = version_str_it->second; + } + } + + on_entry(title_type, content_type, title_id, entry_file, version, version_string); + added_entries = true; + } + } + + return added_entries; +} + +static void UpsertExternalVersionEntry(std::vector& multi_version_entries, + u64 title_id, u32 version, + const std::string& version_string, + ContentRecordType content_type, const VirtualFile& file) { + auto it = std::find_if(multi_version_entries.begin(), multi_version_entries.end(), + [title_id, version](const ExternalUpdateEntry& entry) { + return entry.title_id == title_id && entry.version == version; + }); + + if (it == multi_version_entries.end()) { + ExternalUpdateEntry update_entry; + update_entry.title_id = title_id; + update_entry.version = version; + update_entry.version_string = version_string; + update_entry.files[static_cast(content_type)] = file; + multi_version_entries.push_back(std::move(update_entry)); + return; + } + + it->files[static_cast(content_type)] = file; + if (it->version_string.empty() && !version_string.empty()) { + it->version_string = version_string; + } +} + +template +static bool AddExternalEntriesFromContainer(const std::shared_ptr& nsp, EntryMap& entries, + VersionMap& versions, + std::vector& multi_version_entries) { + return ForEachContainerEntry( + nsp, true, std::nullopt, + [&entries, &versions, + &multi_version_entries](TitleType title_type, ContentRecordType content_type, u64 title_id, + const VirtualFile& file, u32 version, + const std::string& version_string) { + entries[{title_id, content_type, title_type}] = file; + + if (title_type == TitleType::Update) { + versions[title_id] = version; + UpsertExternalVersionEntry(multi_version_entries, title_id, version, version_string, + content_type, file); + } + }); +} + ContentRecordType GetCRTypeFromNCAType(NCAContentType type) { switch (type) { case NCAContentType::Program: @@ -1008,6 +1208,26 @@ void ManualContentProvider::AddEntryWithVersion(TitleType title_type, ContentRec } } +bool ManualContentProvider::AddEntriesFromContainer(VirtualFile file, bool only_content, + std::optional base_program_id) { + const auto nsp = OpenContainerAsNsp(file, Loader::FileType::Unknown); + if (!nsp) { + return false; + } + + return ForEachContainerEntry( + nsp, only_content, base_program_id, + [this](TitleType title_type, ContentRecordType content_type, u64 title_id, + const VirtualFile& entry_file, u32 version, const std::string& version_string) { + if (title_type == TitleType::Update) { + AddEntryWithVersion(title_type, content_type, title_id, version, version_string, + entry_file); + } else { + AddEntry(title_type, content_type, title_id, entry_file); + } + }); +} + void ManualContentProvider::ClearAllEntries() { entries.clear(); multi_version_entries.clear(); @@ -1091,14 +1311,6 @@ VirtualFile ManualContentProvider::GetEntryForVersion(u64 title_id, ContentRecor return nullptr; } -bool ManualContentProvider::HasMultipleVersions(u64 title_id, ContentRecordType type) const { - size_t count = 0; - for (const auto& entry : multi_version_entries) - if (entry.title_id == title_id && entry.files[size_t(type)]) - ++count; - return count > 0; -} - ExternalContentProvider::ExternalContentProvider(std::vector load_directories) : load_dirs(std::move(load_directories)) { ExternalContentProvider::Refresh(); @@ -1159,247 +1371,22 @@ void ExternalContentProvider::ScanDirectory(const VirtualDir& dir) { } void ExternalContentProvider::ProcessNSP(const VirtualFile& file) { - auto nsp = NSP(file); - if (nsp.GetStatus() != Loader::ResultStatus::Success) { + const auto nsp = OpenContainerAsNsp(file, Loader::FileType::NSP); + if (!nsp) { return; } LOG_DEBUG(Service_FS, "Processing NSP file: {}", file->GetName()); - - const auto ncas = nsp.GetNCAs(); - - std::map nsp_versions; - std::map nsp_version_strings; // title_id -> NACP version string - - for (const auto& [title_id, nca_map] : ncas) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (content_type == ContentRecordType::Meta) { - const auto subdirs = nca->GetSubdirectories(); - if (!subdirs.empty()) { - const auto section0 = subdirs[0]; - const auto files = section0->GetFiles(); - for (const auto& inner_file : files) { - if (inner_file->GetExtension() == "cnmt") { - const CNMT cnmt(inner_file); - const auto cnmt_title_id = cnmt.GetTitleID(); - const auto version = cnmt.GetTitleVersion(); - nsp_versions[cnmt_title_id] = version; - versions[cnmt_title_id] = version; - break; - } - } - } - } - - if (content_type == ContentRecordType::Control && title_type == TitleType::Update) { - auto romfs = nca->GetRomFS(); - if (romfs) { - auto extracted = ExtractRomFS(romfs); - if (extracted) { - auto nacp_file = extracted->GetFile("control.nacp"); - if (!nacp_file) { - nacp_file = extracted->GetFile("Control.nacp"); - } - if (nacp_file) { - NACP nacp(nacp_file); - auto ver_str = nacp.GetVersionString(); - if (!ver_str.empty()) { - nsp_version_strings[title_id] = ver_str; - } - } - } - } - } - } - } - - std::map, std::array> version_files; - - for (const auto& [title_id, nca_map] : ncas) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (title_type != TitleType::AOC && title_type != TitleType::Update) { - continue; - } - - auto nca_file = nsp.GetNCAFile(title_id, content_type, title_type); - if (nca_file != nullptr) { - entries[{title_id, content_type, title_type}] = nca_file; - - if (title_type == TitleType::Update) { - u32 version = 0; - auto ver_it = nsp_versions.find(title_id); - if (ver_it != nsp_versions.end()) { - version = ver_it->second; - } - - version_files[{title_id, version}][size_t(content_type)] = nca_file; - } - - LOG_DEBUG(Service_FS, "Added entry - Title ID: {:016X}, Type: {}, Content: {}", - title_id, static_cast(title_type), static_cast(content_type)); - } - } - } - - for (const auto& [key, files_map] : version_files) { - const auto& [title_id, version] = key; - - std::string ver_str; - auto str_it = nsp_version_strings.find(title_id); - if (str_it != nsp_version_strings.end()) { - ver_str = str_it->second; - } - - bool version_exists = false; - for (auto& existing : multi_version_entries) { - if (existing.title_id == title_id && existing.version == version) { - existing.files = files_map; - if (existing.version_string.empty() && !ver_str.empty()) { - existing.version_string = ver_str; - } - version_exists = true; - break; - } - } - - if (!version_exists && !files_map.empty()) { - ExternalUpdateEntry update_entry{ - .title_id = title_id, - .version = version, - .version_string = ver_str, - .files = files_map - }; - multi_version_entries.push_back(update_entry); - LOG_DEBUG(Service_FS, "Added multi-version update - Title ID: {:016X}, Version: {}, VersionStr: {}, Content types: {}", - title_id, version, ver_str, files_map.size()); - } - } + AddExternalEntriesFromContainer(nsp, entries, versions, multi_version_entries); } void ExternalContentProvider::ProcessXCI(const VirtualFile& file) { - auto xci = XCI(file); - if (xci.GetStatus() != Loader::ResultStatus::Success) { + const auto nsp = OpenContainerAsNsp(file, Loader::FileType::XCI); + if (!nsp) { return; } - auto nsp = xci.GetSecurePartitionNSP(); - if (nsp == nullptr) { - return; - } - - const auto ncas = nsp->GetNCAs(); - - std::map xci_versions; - std::map xci_version_strings; - - for (const auto& [title_id, nca_map] : ncas) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (content_type == ContentRecordType::Meta) { - const auto subdirs = nca->GetSubdirectories(); - if (!subdirs.empty()) { - const auto section0 = subdirs[0]; - const auto files = section0->GetFiles(); - for (const auto& inner_file : files) { - if (inner_file->GetExtension() == "cnmt") { - const CNMT cnmt(inner_file); - const auto cnmt_title_id = cnmt.GetTitleID(); - const auto version = cnmt.GetTitleVersion(); - xci_versions[cnmt_title_id] = version; - versions[cnmt_title_id] = version; - break; - } - } - } - } - - if (content_type == ContentRecordType::Control && title_type == TitleType::Update) { - auto romfs = nca->GetRomFS(); - if (romfs) { - auto extracted = ExtractRomFS(romfs); - if (extracted) { - auto nacp_file = extracted->GetFile("control.nacp"); - if (!nacp_file) { - nacp_file = extracted->GetFile("Control.nacp"); - } - if (nacp_file) { - NACP nacp(nacp_file); - auto ver_str = nacp.GetVersionString(); - if (!ver_str.empty()) { - xci_version_strings[title_id] = ver_str; - } - } - } - } - } - } - } - - std::map, std::array> version_files; - - for (const auto& [title_id, nca_map] : ncas) { - for (const auto& [type_pair, nca] : nca_map) { - const auto& [title_type, content_type] = type_pair; - - if (title_type != TitleType::AOC && title_type != TitleType::Update) { - continue; - } - - auto nca_file = nsp->GetNCAFile(title_id, content_type, title_type); - if (nca_file != nullptr) { - entries[{title_id, content_type, title_type}] = nca_file; - - if (title_type == TitleType::Update) { - u32 version = 0; - auto ver_it = xci_versions.find(title_id); - if (ver_it != xci_versions.end()) { - version = ver_it->second; - } - - version_files[{title_id, version}][size_t(content_type)] = nca_file; - } - } - } - } - - for (const auto& [key, files_map] : version_files) { - const auto& [title_id, version] = key; - - std::string ver_str; - auto str_it = xci_version_strings.find(title_id); - if (str_it != xci_version_strings.end()) { - ver_str = str_it->second; - } - - bool version_exists = false; - for (auto& existing : multi_version_entries) { - if (existing.title_id == title_id && existing.version == version) { - existing.files = files_map; - if (existing.version_string.empty() && !ver_str.empty()) { - existing.version_string = ver_str; - } - version_exists = true; - break; - } - } - - if (!version_exists && !files_map.empty()) { - ExternalUpdateEntry update_entry{ - .title_id = title_id, - .version = version, - .version_string = ver_str, - .files = files_map - }; - multi_version_entries.push_back(update_entry); - LOG_DEBUG(Service_FS, "Added multi-version update from XCI - Title ID: {:016X}, Version: {}, VersionStr: {}, Content types: {}", - title_id, version, ver_str, files_map.size()); - } - } + AddExternalEntriesFromContainer(nsp, entries, versions, multi_version_entries); } bool ExternalContentProvider::HasEntry(u64 title_id, ContentRecordType type) const { @@ -1491,12 +1478,4 @@ VirtualFile ExternalContentProvider::GetEntryForVersion(u64 title_id, ContentRec return nullptr; } -bool ExternalContentProvider::HasMultipleVersions(u64 title_id, ContentRecordType type) const { - size_t count = 0; - for (const auto& entry : multi_version_entries) - if (entry.title_id == title_id && entry.files[size_t(type)]) - ++count; - return count > 1; -} - } // namespace FileSys diff --git a/src/core/file_sys/registered_cache.h b/src/core/file_sys/registered_cache.h index 2e39f74db8..32134d1c48 100644 --- a/src/core/file_sys/registered_cache.h +++ b/src/core/file_sys/registered_cache.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -262,6 +263,8 @@ public: VirtualFile file); void AddEntryWithVersion(TitleType title_type, ContentRecordType content_type, u64 title_id, u32 version, const std::string& version_string, VirtualFile file); + bool AddEntriesFromContainer(VirtualFile file, bool only_content = false, + std::optional base_program_id = std::nullopt); void ClearAllEntries(); void Refresh() override; @@ -276,7 +279,6 @@ public: std::vector ListUpdateVersions(u64 title_id) const; VirtualFile GetEntryForVersion(u64 title_id, ContentRecordType type, u32 version) const; - bool HasMultipleVersions(u64 title_id, ContentRecordType type) const; private: std::map, VirtualFile> entries; @@ -303,7 +305,6 @@ public: std::vector ListUpdateVersions(u64 title_id) const; VirtualFile GetEntryForVersion(u64 title_id, ContentRecordType type, u32 version) const; - bool HasMultipleVersions(u64 title_id, ContentRecordType type) const; private: void ScanDirectory(const VirtualDir& dir); diff --git a/src/core/loader/loader.cpp b/src/core/loader/loader.cpp index 4379634d03..b4d50227d3 100644 --- a/src/core/loader/loader.cpp +++ b/src/core/loader/loader.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project @@ -9,11 +9,15 @@ #include #include #include +#include #include "common/concepts.h" #include "common/fs/path_util.h" #include "common/logging/log.h" #include "common/string_util.h" #include "core/core.h" +#include "core/file_sys/card_image.h" +#include "core/file_sys/common_funcs.h" +#include "core/file_sys/submission_package.h" #include "core/hle/kernel/k_process.h" #include "core/loader/deconstructed_rom_directory.h" #include "core/loader/kip.h" @@ -37,6 +41,49 @@ std::optional IdentifyFileLoader(FileSys::VirtualFile file) { return std::nullopt; } +std::shared_ptr OpenContainerAsNsp(FileSys::VirtualFile file, FileType type, + u64 program_id = 0, + std::size_t program_index = 0) { + if (!file) { + return nullptr; + } + + if (type == FileType::NSP) { + auto nsp = std::make_shared(file, program_id, program_index); + return nsp->GetStatus() == ResultStatus::Success ? nsp : nullptr; + } + + if (type == FileType::XCI) { + FileSys::XCI xci{file, program_id, program_index}; + if (xci.GetStatus() != ResultStatus::Success) { + return nullptr; + } + + auto secure_nsp = xci.GetSecurePartitionNSP(); + if (secure_nsp == nullptr || secure_nsp->GetStatus() != ResultStatus::Success) { + return nullptr; + } + + return secure_nsp; + } + + return nullptr; +} + +bool HasApplicationProgramContent(const std::shared_ptr& nsp) { + if (!nsp) { + return false; + } + + const auto& ncas = nsp->GetNCAs(); + return std::any_of(ncas.cbegin(), ncas.cend(), [](const auto& title_entry) { + const auto& nca_map = title_entry.second; + return nca_map.find( + {FileSys::TitleType::Application, FileSys::ContentRecordType::Program}) != + nca_map.end(); + }); +} + } // namespace FileType IdentifyFile(FileSys::VirtualFile file) { @@ -62,6 +109,27 @@ FileType IdentifyFile(FileSys::VirtualFile file) { } } +bool IsContainerType(FileType type) { + return type == FileType::NSP || type == FileType::XCI; +} + +bool IsBootableGameContainer(FileSys::VirtualFile file, FileType type, u64 program_id, + std::size_t program_index) { + if (!file) { + return false; + } + + if (type == FileType::Unknown) { + type = IdentifyFile(file); + } + + if (!IsContainerType(type)) { + return false; + } + + return HasApplicationProgramContent(OpenContainerAsNsp(file, type, program_id, program_index)); +} + FileType GuessFromFilename(const std::string& name) { if (name == "main") return FileType::DeconstructedRomDirectory; diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h index f4e932cec9..95ce638da0 100644 --- a/src/core/loader/loader.h +++ b/src/core/loader/loader.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -46,12 +49,29 @@ enum class FileType { }; /** - * Identifies the type of a bootable file based on the magic value in its header. + * Identifies the type of a supported file/container based on its structure. * @param file open file * @return FileType of file */ FileType IdentifyFile(FileSys::VirtualFile file); +/** + * Returns whether the file type represents a container format that can bundle multiple titles + * (currently NSP/XCI). + */ +bool IsContainerType(FileType type); + +/** + * Returns whether a container file is bootable as a game (has Application/Program content). + * + * @param file open file + * @param type optional file type; if Unknown it is auto-detected. + * @param program_id optional program id hint for multi-program containers. + * @param program_index optional program index hint for multi-program containers. + */ +bool IsBootableGameContainer(FileSys::VirtualFile file, FileType type = FileType::Unknown, + u64 program_id = 0, std::size_t program_index = 0); + /** * Guess the type of a bootable file from its name * @param name String name of bootable file diff --git a/src/core/loader/nsp.cpp b/src/core/loader/nsp.cpp index 3016d5f25f..4333acb70c 100644 --- a/src/core/loader/nsp.cpp +++ b/src/core/loader/nsp.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -55,19 +58,30 @@ AppLoader_NSP::~AppLoader_NSP() = default; FileType AppLoader_NSP::IdentifyType(const FileSys::VirtualFile& nsp_file) { const FileSys::NSP nsp(nsp_file); - if (nsp.GetStatus() == ResultStatus::Success) { - // Extracted Type case - if (nsp.IsExtractedType() && nsp.GetExeFS() != nullptr && - FileSys::IsDirectoryExeFS(nsp.GetExeFS())) { - return FileType::NSP; + if (nsp.GetStatus() != ResultStatus::Success) { + return FileType::Error; + } + + // Extracted Type case + if (nsp.IsExtractedType() && nsp.GetExeFS() != nullptr && + FileSys::IsDirectoryExeFS(nsp.GetExeFS())) { + return FileType::NSP; + } + + // Non-extracted NSPs can legitimately contain only update/DLC content. + // Identify the container format itself; bootability is validated by Load(). + if (!nsp.GetNCAs().empty()) { + return FileType::NSP; + } + + // Fallback when NCAs couldn't be parsed (e.g. missing keys) but the PFS still contains NCAs. + for (const auto& entry : nsp.GetFiles()) { + if (entry == nullptr) { + continue; } - // Non-Extracted Type case - const auto program_id = nsp.GetProgramTitleID(); - if (!nsp.IsExtractedType() && - nsp.GetNCA(program_id, FileSys::ContentRecordType::Program) != nullptr && - AppLoader_NCA::IdentifyType( - nsp.GetNCAFile(program_id, FileSys::ContentRecordType::Program)) == FileType::NCA) { + const auto& name = entry->GetName(); + if (name.size() >= 4 && name.substr(name.size() - 4) == ".nca") { return FileType::NSP; } } diff --git a/src/core/loader/xci.cpp b/src/core/loader/xci.cpp index e9abb199a1..983184a226 100644 --- a/src/core/loader/xci.cpp +++ b/src/core/loader/xci.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -44,10 +47,13 @@ AppLoader_XCI::~AppLoader_XCI() = default; FileType AppLoader_XCI::IdentifyType(const FileSys::VirtualFile& xci_file) { const FileSys::XCI xci(xci_file); - if (xci.GetStatus() == ResultStatus::Success && - xci.GetNCAByType(FileSys::NCAContentType::Program) != nullptr && - AppLoader_NCA::IdentifyType(xci.GetNCAFileByType(FileSys::NCAContentType::Program)) == - FileType::NCA) { + if (xci.GetStatus() != ResultStatus::Success) { + return FileType::Error; + } + + // Identify XCI as a valid container even when it does not include a bootable Program NCA. + // Bootability is handled by AppLoader_XCI::Load(). + if (xci.GetSecurePartitionNSP() != nullptr) { return FileType::XCI; } diff --git a/src/yuzu/game/game_list_worker.cpp b/src/yuzu/game/game_list_worker.cpp index c4504a0d5e..81012e4374 100644 --- a/src/yuzu/game/game_list_worker.cpp +++ b/src/yuzu/game/game_list_worker.cpp @@ -4,6 +4,7 @@ // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +#include #include #include #include @@ -16,14 +17,17 @@ #include "common/fs/fs.h" #include "common/fs/path_util.h" +#include "common/settings.h" #include "core/core.h" #include "core/file_sys/card_image.h" +#include "core/file_sys/common_funcs.h" #include "core/file_sys/content_archive.h" #include "core/file_sys/control_metadata.h" #include "core/file_sys/fs_filesystem.h" #include "core/file_sys/nca_metadata.h" #include "core/file_sys/patch_manager.h" #include "core/file_sys/registered_cache.h" +#include "core/file_sys/romfs.h" #include "core/file_sys/submission_package.h" #include "core/loader/loader.h" #include "yuzu/compatibility_list.h" @@ -375,6 +379,12 @@ void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_pa return true; } + if (target == ScanTarget::PopulateGameList && + (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP) && + !Loader::IsBootableGameContainer(file, file_type)) { + return true; + } + u64 program_id = 0; const auto res2 = loader->ReadProgramId(program_id); @@ -383,18 +393,10 @@ void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_pa provider->AddEntry(FileSys::TitleType::Application, FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()), program_id, file); - } else if (res2 == Loader::ResultStatus::Success && + } else if (Settings::values.ext_content_from_game_dirs.GetValue() && (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) { - const auto nsp = file_type == Loader::FileType::NSP - ? std::make_shared(file) - : FileSys::XCI{file}.GetSecurePartitionNSP(); - for (const auto& title : nsp->GetNCAs()) { - for (const auto& entry : title.second) { - provider->AddEntry(entry.first.first, entry.first.second, title.first, - entry.second->GetBaseFile()); - } - } + void(provider->AddEntriesFromContainer(file)); } } else { std::vector program_ids; diff --git a/src/yuzu/main_window.cpp b/src/yuzu/main_window.cpp index 6ead3c4130..e02e02b413 100644 --- a/src/yuzu/main_window.cpp +++ b/src/yuzu/main_window.cpp @@ -2019,6 +2019,10 @@ void MainWindow::ConfigureFilesystemProvider(const std::string& filepath) { return; } + if (QtCommon::provider->AddEntriesFromContainer(file)) { + return; + } + auto loader = Loader::GetLoader(*QtCommon::system, file); if (!loader) { return; @@ -2033,19 +2037,8 @@ void MainWindow::ConfigureFilesystemProvider(const std::string& filepath) { const auto res2 = loader->ReadProgramId(program_id); if (res2 == Loader::ResultStatus::Success && file_type == Loader::FileType::NCA) { QtCommon::provider->AddEntry(FileSys::TitleType::Application, - FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()), program_id, - file); - } else if (res2 == Loader::ResultStatus::Success && - (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) { - const auto nsp = file_type == Loader::FileType::NSP - ? std::make_shared(file) - : FileSys::XCI{file}.GetSecurePartitionNSP(); - for (const auto& title : nsp->GetNCAs()) { - for (const auto& entry : title.second) { - QtCommon::provider->AddEntry(entry.first.first, entry.first.second, title.first, - entry.second->GetBaseFile()); - } - } + FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()), + program_id, file); } } From cdf9b556b25b33cf558c0ed3085d99e129a2fb1c Mon Sep 17 00:00:00 2001 From: wildcard Date: Thu, 5 Mar 2026 00:54:26 +0100 Subject: [PATCH 024/145] [vulkan]fix vuid 02751 (#3573) Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3573 Reviewed-by: CamilleLaVey Reviewed-by: DraVee Co-authored-by: wildcard Co-committed-by: wildcard --- src/video_core/renderer_vulkan/vk_buffer_cache.cpp | 8 ++++++++ src/video_core/vulkan_common/vulkan_device.h | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index 6256bc8bd8..f4345262fb 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -108,6 +108,14 @@ VkBufferView Buffer::View(u32 offset, u32 size, VideoCore::Surface::PixelFormat // Null buffer not supported, adjust offset and size offset = 0; size = 0; + } else { + // Align offset down to minTexelBufferOffsetAlignment + const u32 alignment = static_cast(device->GetMinTexelBufferOffsetAlignment()); + if (alignment > 1) { + const u32 aligned_offset = offset & ~(alignment - 1); + size += offset - aligned_offset; + offset = aligned_offset; + } } const auto it{std::ranges::find_if(views, [offset, size, format](const BufferView& view) { return offset == view.offset && size == view.size && format == view.format; diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h index d3623d1186..d29a8cd3f3 100644 --- a/src/video_core/vulkan_common/vulkan_device.h +++ b/src/video_core/vulkan_common/vulkan_device.h @@ -318,6 +318,11 @@ public: return properties.properties.limits.minStorageBufferOffsetAlignment; } + /// Returns texel buffer offset alignment requirement. + VkDeviceSize GetMinTexelBufferOffsetAlignment() const { + return properties.properties.limits.minTexelBufferOffsetAlignment; + } + /// Returns the maximum range for storage buffers. VkDeviceSize GetMaxStorageBufferRange() const { return properties.properties.limits.maxStorageBufferRange; From 69e47bd2c0c04e0e18c29a23533e8e7724436226 Mon Sep 17 00:00:00 2001 From: wildcard Date: Thu, 5 Mar 2026 00:54:48 +0100 Subject: [PATCH 025/145] [vulkan] Fix wrong stage index in prepare_stage render area check (#3672) The OpenGL correctly uses const auto& info{stage_infos[stage]}; Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3672 Reviewed-by: MaranBr Reviewed-by: DraVee Co-authored-by: wildcard Co-committed-by: wildcard --- src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp index d156baa77b..5b11a34232 100644 --- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp +++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp @@ -474,7 +474,7 @@ bool GraphicsPipeline::ConfigureImpl(bool is_indexed) { buffer_cache.BindHostStageBuffers(stage); PushImageDescriptors(texture_cache, guest_descriptor_queue, stage_infos[stage], rescaling, samplers_it, views_it); - const auto& info{stage_infos[0]}; + const auto& info{stage_infos[stage]}; if (info.uses_render_area) { render_area.uses_render_area = true; render_area.words = {static_cast(regs.surface_clip.width), From 70c1e9abed3dc70284c4eece3786922b2fc144ed Mon Sep 17 00:00:00 2001 From: nekle Date: Thu, 5 Mar 2026 00:56:25 +0100 Subject: [PATCH 026/145] [android] Try and fix SD Card storage mount points for external paths (#3436) Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3436 Reviewed-by: DraVee Reviewed-by: MaranBr Co-authored-by: nekle Co-committed-by: nekle --- .../java/org/yuzu/yuzu_emu/utils/PathUtil.kt | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/PathUtil.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/PathUtil.kt index a840b3b846..744e1d149c 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/PathUtil.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/PathUtil.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later package org.yuzu.yuzu_emu.utils @@ -80,16 +80,14 @@ object PathUtil { } } - // This really shouldn't be necessary, but the Android API seemingly - // doesn't have a way of doing this? - // Apparently, on certain devices the mount location can vary, so add - // extra cases here if we discover any new ones. fun getRemovableStoragePath(idString: String): String? { - var pathFile: File + val possibleMountPaths = listOf("/mnt/media_rw/$idString", "/storage/$idString") - pathFile = File("/mnt/media_rw/$idString"); - if (pathFile.exists()) { - return pathFile.absolutePath + for (mountPath in possibleMountPaths) { + val pathFile = File(mountPath); + if (pathFile.exists()) { + return pathFile.absolutePath + } } return null From 05f6942befe0ab1209ecc5e2ddb9716f49d65574 Mon Sep 17 00:00:00 2001 From: xbzk Date: Thu, 5 Mar 2026 00:58:49 +0100 Subject: [PATCH 027/145] [android, ui] fixed setting reset to defaults infinite loop (#3659) fixed a bug discovered by Pavel in which the settings' "reset to defaults" dialog would get stuck in a infinite loop, due to a recall prior to cleaning state. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3659 Reviewed-by: MaranBr Reviewed-by: DraVee Reviewed-by: CamilleLaVey Co-authored-by: xbzk Co-committed-by: xbzk --- .../settings/ui/SettingsDialogFragment.kt | 42 +++++++------------ .../settings/ui/SettingsFragmentPresenter.kt | 5 ++- 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt index f66f4bac7f..4dcb35c010 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2023 yuzu Emulator Project @@ -68,7 +68,9 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener MaterialAlertDialogBuilder(requireContext()) .setMessage(R.string.reset_setting_confirmation) .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> - when (val item = settingsViewModel.clickedItem) { + val item = settingsViewModel.clickedItem ?: return@setPositiveButton + clearDialogState() + when (item) { is AnalogInputSetting -> { val stickParam = NativeInput.getStickParam( item.playerIndex, @@ -107,12 +109,17 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener } else -> { - settingsViewModel.clickedItem!!.setting.reset() + item.setting.reset() settingsViewModel.setAdapterItemChanged(position) } } } - .setNegativeButton(android.R.string.cancel, null) + .setNegativeButton(android.R.string.cancel) { _: DialogInterface, _: Int -> + clearDialogState() + } + .setOnCancelListener { + clearDialogState() + } .create() } @@ -186,27 +193,6 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener updateButtonState(isValid) } - /* - * xbzk: these two events, along with attachRepeat feature, - * were causing spinbox buttons to respond twice per press - * cutting these out to retain accelerated press functionality - * TODO: clean this out later if no issues arise - * - spinboxBinding.buttonDecrement.setOnClickListener { - val current = spinboxBinding.editValue.text.toString().toIntOrNull() ?: currentValue - val newValue = current - 1 - spinboxBinding.editValue.setText(newValue.toString()) - updateValidity(newValue) - } - - spinboxBinding.buttonIncrement.setOnClickListener { - val current = spinboxBinding.editValue.text.toString().toIntOrNull() ?: currentValue - val newValue = current + 1 - spinboxBinding.editValue.setText(newValue.toString()) - updateValidity(newValue) - } - */ - fun attachRepeat(button: View, delta: Int) { val handler = Handler(Looper.getMainLooper()) var runnable: Runnable? = null @@ -439,9 +425,13 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener private fun closeDialog() { settingsViewModel.setAdapterItemChanged(position) + clearDialogState() + dismiss() + } + + private fun clearDialogState() { settingsViewModel.clickedItem = null settingsViewModel.setSliderProgress(-1f) - dismiss() } private fun getValueForSingleChoiceSelection(item: SingleChoiceSetting, which: Int): Int { diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt index 0fc4fb0b7f..77104e0614 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt @@ -1066,7 +1066,10 @@ class SettingsFragmentPresenter( IntSetting.THEME.getValueAsString() override val defaultValue: Int = IntSetting.THEME.defaultValue - override fun reset() = IntSetting.THEME.setInt(defaultValue) + override fun reset() { + IntSetting.THEME.setInt(defaultValue) + settingsViewModel.setShouldRecreate(true) + } } add(HeaderSetting(R.string.app_settings)) From 9a07bd0570ceba262b4a918f4927e5674b6f7269 Mon Sep 17 00:00:00 2001 From: lizzie Date: Thu, 5 Mar 2026 07:32:18 +0100 Subject: [PATCH 028/145] [vk] unify VkSurfaceKHR with Android and the rest of platforms; remove technically incorrect nullptr() ctor for handles (#2971) Removes some odd #ifdef-ing that just can use a shrimple opaque type. Also removes nullptr() ctor'ing for vulkan handles and such; it's not incorrect per se like how `void *p = 0;` isn't incorrect, just that, y'know, any static analyzer will go "woah". Also there isn't any guarantee that handles `sizeof(Handle) == sizeof(void*)` so may as well :) Signed-off-by: lizzie lizzie@eden-emu.dev Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/2971 Reviewed-by: CamilleLaVey Reviewed-by: MaranBr Co-authored-by: lizzie Co-committed-by: lizzie --- src/video_core/renderer_vulkan/blit_image.cpp | 8 +-- .../renderer_vulkan/renderer_vulkan.cpp | 8 +-- .../renderer_vulkan/vk_compute_pass.cpp | 8 +-- .../renderer_vulkan/vk_compute_pipeline.cpp | 36 ++++++------- .../renderer_vulkan/vk_graphics_pipeline.cpp | 44 ++++++++------- .../renderer_vulkan/vk_present_manager.cpp | 20 ++----- .../renderer_vulkan/vk_present_manager.h | 16 ++---- .../renderer_vulkan/vk_query_cache.cpp | 2 +- .../renderer_vulkan/vk_query_cache.h | 5 +- .../renderer_vulkan/vk_scheduler.cpp | 2 +- src/video_core/renderer_vulkan/vk_scheduler.h | 8 +-- .../renderer_vulkan/vk_swapchain.cpp | 54 +++---------------- src/video_core/renderer_vulkan/vk_swapchain.h | 22 ++------ src/video_core/vulkan_common/vulkan.h | 5 +- .../vulkan_common/vulkan_device.cpp | 2 +- .../vulkan_common/vulkan_surface.cpp | 2 +- src/video_core/vulkan_common/vulkan_wrapper.h | 44 +++++++-------- 17 files changed, 104 insertions(+), 182 deletions(-) diff --git a/src/video_core/renderer_vulkan/blit_image.cpp b/src/video_core/renderer_vulkan/blit_image.cpp index 07611ef98c..789f4da2ed 100644 --- a/src/video_core/renderer_vulkan/blit_image.cpp +++ b/src/video_core/renderer_vulkan/blit_image.cpp @@ -1032,7 +1032,7 @@ void BlitImageHelper::ConvertDepthToColorPipeline(vk::Pipeline& pipeline, VkRend VkShaderModule frag_shader = *convert_float_to_depth_frag; const std::array stages = MakeStages(*full_screen_vert, frag_shader); const VkPipelineInputAssemblyStateCreateInfo input_assembly_ci = GetPipelineInputAssemblyStateCreateInfo(device); - pipeline = device.GetLogical().CreateGraphicsPipeline({ + pipeline = device.GetLogical().CreateGraphicsPipeline(VkGraphicsPipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -1062,7 +1062,7 @@ void BlitImageHelper::ConvertColorToDepthPipeline(vk::Pipeline& pipeline, VkRend VkShaderModule frag_shader = *convert_depth_to_float_frag; const std::array stages = MakeStages(*full_screen_vert, frag_shader); const VkPipelineInputAssemblyStateCreateInfo input_assembly_ci = GetPipelineInputAssemblyStateCreateInfo(device); - pipeline = device.GetLogical().CreateGraphicsPipeline({ + pipeline = device.GetLogical().CreateGraphicsPipeline(VkGraphicsPipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -1093,7 +1093,7 @@ void BlitImageHelper::ConvertPipelineEx(vk::Pipeline& pipeline, VkRenderPass ren } const std::array stages = MakeStages(*full_screen_vert, *module); const VkPipelineInputAssemblyStateCreateInfo input_assembly_ci = GetPipelineInputAssemblyStateCreateInfo(device); - pipeline = device.GetLogical().CreateGraphicsPipeline({ + pipeline = device.GetLogical().CreateGraphicsPipeline(VkGraphicsPipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -1135,7 +1135,7 @@ void BlitImageHelper::ConvertPipeline(vk::Pipeline& pipeline, VkRenderPass rende is_target_depth ? *convert_float_to_depth_frag : *convert_depth_to_float_frag; const std::array stages = MakeStages(*full_screen_vert, frag_shader); const VkPipelineInputAssemblyStateCreateInfo input_assembly_ci = GetPipelineInputAssemblyStateCreateInfo(device); - pipeline = device.GetLogical().CreateGraphicsPipeline({ + pipeline = device.GetLogical().CreateGraphicsPipeline(VkGraphicsPipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.cpp b/src/video_core/renderer_vulkan/renderer_vulkan.cpp index d1e607e75f..cb1b1a5362 100644 --- a/src/video_core/renderer_vulkan/renderer_vulkan.cpp +++ b/src/video_core/renderer_vulkan/renderer_vulkan.cpp @@ -137,14 +137,8 @@ try memory_allocator, scheduler, swapchain, -#ifdef ANDROID - surface) - , -#else *surface) - , -#endif - blit_swapchain(device_memory, + , blit_swapchain(device_memory, device, memory_allocator, present_manager, diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp index 22e646afe9..d45a57f7bb 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp @@ -285,7 +285,7 @@ ComputePass::ComputePass(const Device& device_, DescriptorPool& descriptor_pool, .requiredSubgroupSize = optional_subgroup_size ? *optional_subgroup_size : 32U, }; bool use_setup_size = device.IsExtSubgroupSizeControlSupported() && optional_subgroup_size; - pipeline = device.GetLogical().CreateComputePipeline({ + pipeline = device.GetLogical().CreateComputePipeline(VkComputePipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -299,7 +299,7 @@ ComputePass::ComputePass(const Device& device_, DescriptorPool& descriptor_pool, .pSpecializationInfo = nullptr, }, .layout = *layout, - .basePipelineHandle = nullptr, + .basePipelineHandle = {}, .basePipelineIndex = 0, }); } @@ -944,7 +944,7 @@ MSAACopyPass::MSAACopyPass(const Device& device_, Scheduler& scheduler_, .codeSize = static_cast(code.size_bytes()), .pCode = code.data(), }); - pipelines[i] = device.GetLogical().CreateComputePipeline({ + pipelines[i] = device.GetLogical().CreateComputePipeline(VkComputePipelineCreateInfo{ .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -958,7 +958,7 @@ MSAACopyPass::MSAACopyPass(const Device& device_, Scheduler& scheduler_, .pSpecializationInfo = nullptr, }, .layout = *layout, - .basePipelineHandle = nullptr, + .basePipelineHandle = {}, .basePipelineIndex = 0, }); }; diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp index 6a6fe2b830..1a62324c95 100644 --- a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp +++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp @@ -67,26 +67,24 @@ ComputePipeline::ComputePipeline(const Device& device_, vk::PipelineCache& pipel if (device.IsKhrPipelineExecutablePropertiesEnabled() && Settings::values.renderer_debug.GetValue()) { flags |= VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR; } - pipeline = device.GetLogical().CreateComputePipeline( - { - .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, - .pNext = nullptr, - .flags = flags, - .stage{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .pNext = - device.IsExtSubgroupSizeControlSupported() ? &subgroup_size_ci : nullptr, - .flags = 0, - .stage = VK_SHADER_STAGE_COMPUTE_BIT, - .module = *spv_module, - .pName = "main", - .pSpecializationInfo = nullptr, - }, - .layout = *pipeline_layout, - .basePipelineHandle = 0, - .basePipelineIndex = 0, + pipeline = device.GetLogical().CreateComputePipeline(VkComputePipelineCreateInfo{ + .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .pNext = nullptr, + .flags = flags, + .stage{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = + device.IsExtSubgroupSizeControlSupported() ? &subgroup_size_ci : nullptr, + .flags = 0, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, + .module = *spv_module, + .pName = "main", + .pSpecializationInfo = nullptr, }, - *pipeline_cache); + .layout = *pipeline_layout, + .basePipelineHandle = 0, + .basePipelineIndex = 0, + }, *pipeline_cache); // Log compute pipeline creation if (Settings::values.gpu_logging_enabled.GetValue()) { diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp index 5b11a34232..e989bf6b31 100644 --- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp +++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp @@ -946,29 +946,27 @@ void GraphicsPipeline::MakePipeline(VkRenderPass render_pass) { flags |= VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR; } - pipeline = device.GetLogical().CreateGraphicsPipeline( - { - .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, - .pNext = nullptr, - .flags = flags, - .stageCount = static_cast(shader_stages.size()), - .pStages = shader_stages.data(), - .pVertexInputState = &vertex_input_ci, - .pInputAssemblyState = &input_assembly_ci, - .pTessellationState = &tessellation_ci, - .pViewportState = &viewport_ci, - .pRasterizationState = &rasterization_ci, - .pMultisampleState = &multisample_ci, - .pDepthStencilState = &depth_stencil_ci, - .pColorBlendState = &color_blend_ci, - .pDynamicState = &dynamic_state_ci, - .layout = *pipeline_layout, - .renderPass = render_pass, - .subpass = 0, - .basePipelineHandle = nullptr, - .basePipelineIndex = 0, - }, - *pipeline_cache); + pipeline = device.GetLogical().CreateGraphicsPipeline({ + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .pNext = nullptr, + .flags = flags, + .stageCount = static_cast(shader_stages.size()), + .pStages = shader_stages.data(), + .pVertexInputState = &vertex_input_ci, + .pInputAssemblyState = &input_assembly_ci, + .pTessellationState = &tessellation_ci, + .pViewportState = &viewport_ci, + .pRasterizationState = &rasterization_ci, + .pMultisampleState = &multisample_ci, + .pDepthStencilState = &depth_stencil_ci, + .pColorBlendState = &color_blend_ci, + .pDynamicState = &dynamic_state_ci, + .layout = *pipeline_layout, + .renderPass = render_pass, + .subpass = 0, + .basePipelineHandle = nullptr, + .basePipelineIndex = 0, + }, *pipeline_cache); // Log graphics pipeline creation if (Settings::values.gpu_logging_enabled.GetValue()) { diff --git a/src/video_core/renderer_vulkan/vk_present_manager.cpp b/src/video_core/renderer_vulkan/vk_present_manager.cpp index 3b5c2e3c01..aa019a4160 100644 --- a/src/video_core/renderer_vulkan/vk_present_manager.cpp +++ b/src/video_core/renderer_vulkan/vk_present_manager.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project @@ -101,22 +101,14 @@ PresentManager::PresentManager(const vk::Instance& instance_, MemoryAllocator& memory_allocator_, Scheduler& scheduler_, Swapchain& swapchain_, -#ifdef ANDROID - vk::SurfaceKHR& surface_) -#else - VkSurfaceKHR_T* surface_handle_) -#endif + VkSurfaceKHR_T* surface_) : instance{instance_} , render_window{render_window_} , device{device_} , memory_allocator{memory_allocator_} , scheduler{scheduler_} , swapchain{swapchain_} -#ifdef ANDROID , surface{surface_} -#else - , surface_handle{surface_handle_} -#endif , blit_supported{CanBlitToSwapchain(device.GetPhysical(), swapchain.GetImageViewFormat())} , use_present_thread{Settings::values.async_presentation.GetValue()} { @@ -299,11 +291,7 @@ void PresentManager::PresentThread(std::stop_token token) { } void PresentManager::RecreateSwapchain(Frame* frame) { -#ifndef ANDROID - swapchain.Create(surface_handle, frame->width, frame->height); // Pass raw pointer -#else - swapchain.Create(*surface, frame->width, frame->height); // Pass raw pointer -#endif + swapchain.Create(surface, frame->width, frame->height); // Pass raw pointer SetImageCount(); } @@ -322,7 +310,7 @@ void PresentManager::CopyToSwapchain(Frame* frame) { // Recreate surface and swapchain if needed. if (requires_recreation) { #ifdef ANDROID - surface = CreateSurface(instance, render_window.GetWindowInfo()); + surface = *CreateSurface(instance, render_window.GetWindowInfo()).address(); #endif RecreateSwapchain(frame); } diff --git a/src/video_core/renderer_vulkan/vk_present_manager.h b/src/video_core/renderer_vulkan/vk_present_manager.h index aacc9b025a..3d5cc32102 100644 --- a/src/video_core/renderer_vulkan/vk_present_manager.h +++ b/src/video_core/renderer_vulkan/vk_present_manager.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project @@ -15,8 +15,6 @@ #include "video_core/vulkan_common/vulkan_memory_allocator.h" #include "video_core/vulkan_common/vulkan_wrapper.h" -struct VkSurfaceKHR_T; - namespace Core::Frontend { class EmuWindow; } // namespace Core::Frontend @@ -46,11 +44,7 @@ public: MemoryAllocator& memory_allocator, Scheduler& scheduler, Swapchain& swapchain, -#ifdef ANDROID - vk::SurfaceKHR& surface); -#else - VkSurfaceKHR_T* surface_handle); -#endif + VkSurfaceKHR_T* surface); ~PresentManager(); /// Returns the last used presentation frame @@ -84,11 +78,7 @@ private: MemoryAllocator& memory_allocator; Scheduler& scheduler; Swapchain& swapchain; -#ifdef ANDROID - vk::SurfaceKHR& surface; -#else - VkSurfaceKHR_T* surface_handle; -#endif + VkSurfaceKHR_T* surface; vk::CommandPool cmdpool; std::vector frames; boost::container::deque present_queue; diff --git a/src/video_core/renderer_vulkan/vk_query_cache.cpp b/src/video_core/renderer_vulkan/vk_query_cache.cpp index 415259c72c..7cdb3acadd 100644 --- a/src/video_core/renderer_vulkan/vk_query_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_query_cache.cpp @@ -1280,7 +1280,7 @@ void QueryCacheRuntime::EndHostConditionalRendering() { PauseHostConditionalRendering(); impl->hcr_is_set = false; impl->is_hcr_running = false; - impl->hcr_buffer = nullptr; + impl->hcr_buffer = VkBuffer{}; impl->hcr_offset = 0; } diff --git a/src/video_core/renderer_vulkan/vk_query_cache.h b/src/video_core/renderer_vulkan/vk_query_cache.h index b8dae9bc2d..e2aa4d991e 100644 --- a/src/video_core/renderer_vulkan/vk_query_cache.h +++ b/src/video_core/renderer_vulkan/vk_query_cache.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -35,7 +38,7 @@ public: ~QueryCacheRuntime(); template - void SyncValues(std::span values, VkBuffer base_src_buffer = nullptr); + void SyncValues(std::span values, VkBuffer base_src_buffer = VkBuffer{}); void Barriers(bool is_prebarrier); diff --git a/src/video_core/renderer_vulkan/vk_scheduler.cpp b/src/video_core/renderer_vulkan/vk_scheduler.cpp index 0a032cdae0..947de6a80e 100644 --- a/src/video_core/renderer_vulkan/vk_scheduler.cpp +++ b/src/video_core/renderer_vulkan/vk_scheduler.cpp @@ -377,7 +377,7 @@ void Scheduler::EndRenderPass() VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, nullptr, nullptr, vk::Span(barriers.data(), num_images)); }); - state.renderpass = nullptr; + state.renderpass = VkRenderPass{}; num_renderpass_images = 0; } diff --git a/src/video_core/renderer_vulkan/vk_scheduler.h b/src/video_core/renderer_vulkan/vk_scheduler.h index 667f136ee6..00a912f2cd 100644 --- a/src/video_core/renderer_vulkan/vk_scheduler.h +++ b/src/video_core/renderer_vulkan/vk_scheduler.h @@ -44,10 +44,10 @@ public: ~Scheduler(); /// Sends the current execution context to the GPU. - u64 Flush(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr); + u64 Flush(VkSemaphore signal_semaphore = {}, VkSemaphore wait_semaphore = {}); /// Sends the current execution context to the GPU and waits for it to complete. - void Finish(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr); + void Finish(VkSemaphore signal_semaphore = {}, VkSemaphore wait_semaphore = {}); /// Waits for the worker thread to finish executing everything. After this function returns it's /// safe to touch worker resources. @@ -237,8 +237,8 @@ private: }; struct State { - VkRenderPass renderpass = nullptr; - VkFramebuffer framebuffer = nullptr; + VkRenderPass renderpass{}; + VkFramebuffer framebuffer{}; VkExtent2D render_area = {0, 0}; GraphicsPipeline* graphics_pipeline = nullptr; bool is_rescaling = false; diff --git a/src/video_core/renderer_vulkan/vk_swapchain.cpp b/src/video_core/renderer_vulkan/vk_swapchain.cpp index b89e981444..cd8f948d8b 100644 --- a/src/video_core/renderer_vulkan/vk_swapchain.cpp +++ b/src/video_core/renderer_vulkan/vk_swapchain.cpp @@ -109,38 +109,22 @@ VkCompositeAlphaFlagBitsKHR ChooseAlphaFlags(const VkSurfaceCapabilitiesKHR& cap } // Anonymous namespace Swapchain::Swapchain( -#ifdef ANDROID - VkSurfaceKHR surface_, -#else - VkSurfaceKHR_T* surface_handle_, -#endif + VkSurfaceKHR_T* surface_, const Device& device_, Scheduler& scheduler_, u32 width_, u32 height_) -#ifdef ANDROID : surface(surface_) -#else - : surface_handle{surface_handle_} -#endif , device{device_} , scheduler{scheduler_} { -#ifdef ANDROID Create(surface, width_, height_); -#else - Create(surface_handle, width_, height_); -#endif } Swapchain::~Swapchain() = default; void Swapchain::Create( -#ifdef ANDROID - VkSurfaceKHR surface_, -#else - VkSurfaceKHR_T* surface_handle_, -#endif + VkSurfaceKHR_T* surface_, u32 width_, u32 height_) { @@ -148,18 +132,10 @@ void Swapchain::Create( is_suboptimal = false; width = width_; height = height_; -#ifdef ANDROID surface = surface_; -#else - surface_handle = surface_handle_; -#endif const auto physical_device = device.GetPhysical(); -#ifdef ANDROID - const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(surface)}; -#else - const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(surface_handle)}; -#endif + const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(VkSurfaceKHR(surface))}; if (capabilities.maxImageExtent.width == 0 || capabilities.maxImageExtent.height == 0) { return; } @@ -254,14 +230,8 @@ void Swapchain::Present(VkSemaphore render_semaphore) { void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities) { const auto physical_device{device.GetPhysical()}; - -#ifdef ANDROID - const auto formats{physical_device.GetSurfaceFormatsKHR(surface)}; - const auto present_modes = physical_device.GetSurfacePresentModesKHR(surface); -#else - const auto formats{physical_device.GetSurfaceFormatsKHR(surface_handle)}; - const auto present_modes = physical_device.GetSurfacePresentModesKHR(surface_handle); -#endif + const auto formats{physical_device.GetSurfaceFormatsKHR(VkSurfaceKHR(surface))}; + const auto present_modes = physical_device.GetSurfacePresentModesKHR(VkSurfaceKHR(surface)); has_mailbox = std::find(present_modes.begin(), present_modes.end(), VK_PRESENT_MODE_MAILBOX_KHR) != present_modes.end(); @@ -290,11 +260,7 @@ void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities) { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .pNext = nullptr, .flags = 0, -#ifdef ANDROID - .surface = surface, -#else - .surface = surface_handle, -#endif + .surface = VkSurfaceKHR(surface), .minImageCount = requested_image_count, .imageFormat = surface_format.format, .imageColorSpace = surface_format.colorSpace, @@ -313,7 +279,7 @@ void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities) { .compositeAlpha = alpha_flags, .presentMode = present_mode, .clipped = VK_FALSE, - .oldSwapchain = nullptr, + .oldSwapchain = VkSwapchainKHR{}, }; const u32 graphics_family{device.GetGraphicsFamily()}; const u32 present_family{device.GetPresentFamily()}; @@ -345,11 +311,7 @@ void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities) { swapchain_ci.flags |= VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR; } // Request the size again to reduce the possibility of a TOCTOU race condition. -#ifdef ANDROID - const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(surface); -#else - const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(surface_handle); -#endif + const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(VkSurfaceKHR(surface)); swapchain_ci.imageExtent = ChooseSwapExtent(updated_capabilities, width, height); // Don't add code within this and the swapchain creation. swapchain = device.GetLogical().CreateSwapchainKHR(swapchain_ci); diff --git a/src/video_core/renderer_vulkan/vk_swapchain.h b/src/video_core/renderer_vulkan/vk_swapchain.h index 7e99bf8fa7..d926cc118a 100644 --- a/src/video_core/renderer_vulkan/vk_swapchain.h +++ b/src/video_core/renderer_vulkan/vk_swapchain.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project @@ -11,8 +11,6 @@ #include "common/common_types.h" #include "video_core/vulkan_common/vulkan_wrapper.h" -struct VkSurfaceKHR_T; - namespace Layout { struct FramebufferLayout; } @@ -25,11 +23,7 @@ class Scheduler; class Swapchain { public: explicit Swapchain( -#ifdef ANDROID - VkSurfaceKHR surface, -#else - VkSurfaceKHR_T* surface_handle, -#endif + VkSurfaceKHR_T* surface, const Device& device, Scheduler& scheduler, u32 width, @@ -38,11 +32,7 @@ public: /// Creates (or recreates) the swapchain with a given size. void Create( -#ifdef ANDROID - VkSurfaceKHR surface, -#else - VkSurfaceKHR_T* surface_handle, -#endif + VkSurfaceKHR_T* surface, u32 width, u32 height); @@ -128,11 +118,7 @@ private: bool NeedsPresentModeUpdate() const; -#ifdef ANDROID - VkSurfaceKHR surface; -#else - VkSurfaceKHR_T* surface_handle; -#endif + VkSurfaceKHR_T* surface; const Device& device; Scheduler& scheduler; diff --git a/src/video_core/vulkan_common/vulkan.h b/src/video_core/vulkan_common/vulkan.h index 8d2e8e2a37..2cc0f0d7f0 100644 --- a/src/video_core/vulkan_common/vulkan.h +++ b/src/video_core/vulkan_common/vulkan.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project @@ -40,3 +40,6 @@ #undef False #undef None #undef True + +// "Catch-all" handle for both Android and.. the rest of platforms +struct VkSurfaceKHR_T; diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp index a2ff3ee6ed..b51c57d380 100644 --- a/src/video_core/vulkan_common/vulkan_device.cpp +++ b/src/video_core/vulkan_common/vulkan_device.cpp @@ -419,7 +419,7 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR : instance{instance_}, dld{dld_}, physical{physical_}, format_properties(GetFormatProperties(physical)) { // Get suitability and device properties. - const bool is_suitable = GetSuitability(surface != nullptr); + const bool is_suitable = GetSuitability(surface != VkSurfaceKHR{}); const VkDriverId driver_id = properties.driver.driverID; diff --git a/src/video_core/vulkan_common/vulkan_surface.cpp b/src/video_core/vulkan_common/vulkan_surface.cpp index dc65d3960a..761b7759c8 100644 --- a/src/video_core/vulkan_common/vulkan_surface.cpp +++ b/src/video_core/vulkan_common/vulkan_surface.cpp @@ -15,7 +15,7 @@ vk::SurfaceKHR CreateSurface( const vk::Instance& instance, [[maybe_unused]] const Core::Frontend::EmuWindow::WindowSystemInfo& window_info) { [[maybe_unused]] const vk::InstanceDispatch& dld = instance.Dispatch(); - VkSurfaceKHR unsafe_surface = nullptr; + VkSurfaceKHR unsafe_surface = VkSurfaceKHR{}; #ifdef _WIN32 if (window_info.type == Core::Frontend::WindowSystemType::Windows) { diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h index 5c04132f7b..872fbd858e 100644 --- a/src/video_core/vulkan_common/vulkan_wrapper.h +++ b/src/video_core/vulkan_common/vulkan_wrapper.h @@ -404,13 +404,13 @@ public: /// Construct a handle transferring the ownership from another handle. Handle(Handle&& rhs) noexcept - : handle{std::exchange(rhs.handle, nullptr)}, owner{rhs.owner}, dld{rhs.dld} {} + : handle{std::exchange(rhs.handle, Type{})}, owner{rhs.owner}, dld{rhs.dld} {} /// Assign the current handle transferring the ownership from another handle. /// Destroys any previously held object. Handle& operator=(Handle&& rhs) noexcept { Release(); - handle = std::exchange(rhs.handle, nullptr); + handle = std::exchange(rhs.handle, Type{}); owner = rhs.owner; dld = rhs.dld; return *this; @@ -424,7 +424,7 @@ public: /// Destroys any held object. void reset() noexcept { Release(); - handle = nullptr; + handle = Type{}; } /// Returns the address of the held object. @@ -440,7 +440,7 @@ public: /// Returns true when there's a held object. explicit operator bool() const noexcept { - return handle != nullptr; + return handle != Type{}; } #ifndef ANDROID @@ -455,7 +455,7 @@ public: #endif protected: - Type handle = nullptr; + Type handle{}; OwnerType owner = nullptr; const Dispatch* dld = nullptr; @@ -463,7 +463,7 @@ private: /// Destroys the held object if it exists. void Release() noexcept { if (handle) { - Destroy(owner, handle, *dld); + Destroy(OwnerType(owner), Type(handle), *dld); } } }; @@ -506,7 +506,7 @@ public: /// Destroys any held object. void reset() noexcept { Release(); - handle = nullptr; + handle = {}; } /// Returns the address of the held object. @@ -522,7 +522,7 @@ public: /// Returns true when there's a held object. explicit operator bool() const noexcept { - return handle != nullptr; + return handle != Type{}; } #ifndef ANDROID @@ -537,7 +537,7 @@ public: #endif protected: - Type handle = nullptr; + Type handle{}; const Dispatch* dld = nullptr; private: @@ -607,7 +607,7 @@ private: std::unique_ptr allocations; std::size_t num = 0; VkDevice device = nullptr; - PoolType pool = nullptr; + PoolType pool{}; const DeviceDispatch* dld = nullptr; }; @@ -669,12 +669,12 @@ public: Image& operator=(const Image&) = delete; Image(Image&& rhs) noexcept - : handle{std::exchange(rhs.handle, nullptr)}, usage{rhs.usage}, owner{rhs.owner}, + : handle{std::exchange(rhs.handle, VkImage{})}, usage{rhs.usage}, owner{rhs.owner}, allocator{rhs.allocator}, allocation{rhs.allocation}, dld{rhs.dld} {} Image& operator=(Image&& rhs) noexcept { Release(); - handle = std::exchange(rhs.handle, nullptr); + handle = std::exchange(rhs.handle, VkImage{}); usage = rhs.usage; owner = rhs.owner; allocator = rhs.allocator; @@ -693,11 +693,11 @@ public: void reset() noexcept { Release(); - handle = nullptr; + handle = VkImage{}; } explicit operator bool() const noexcept { - return handle != nullptr; + return handle != VkImage{}; } void SetObjectNameEXT(const char* name) const; @@ -709,7 +709,7 @@ public: private: void Release() const noexcept; - VkImage handle = nullptr; + VkImage handle{}; VkImageUsageFlags usage{}; VkDevice owner = nullptr; VmaAllocator allocator = nullptr; @@ -730,13 +730,13 @@ public: Buffer& operator=(const Buffer&) = delete; Buffer(Buffer&& rhs) noexcept - : handle{std::exchange(rhs.handle, nullptr)}, owner{rhs.owner}, allocator{rhs.allocator}, + : handle{std::exchange(rhs.handle, VkBuffer{})}, owner{rhs.owner}, allocator{rhs.allocator}, allocation{rhs.allocation}, mapped{rhs.mapped}, is_coherent{rhs.is_coherent}, dld{rhs.dld} {} Buffer& operator=(Buffer&& rhs) noexcept { Release(); - handle = std::exchange(rhs.handle, nullptr); + handle = std::exchange(rhs.handle, VkBuffer{}); owner = rhs.owner; allocator = rhs.allocator; allocation = rhs.allocation; @@ -756,11 +756,11 @@ public: void reset() noexcept { Release(); - handle = nullptr; + handle = VkBuffer{}; } explicit operator bool() const noexcept { - return handle != nullptr; + return handle != VkBuffer{}; } /// Returns the host mapped memory, an empty span otherwise. @@ -786,7 +786,7 @@ public: private: void Release() const noexcept; - VkBuffer handle = nullptr; + VkBuffer handle{}; VkDevice owner = nullptr; VmaAllocator allocator = nullptr; VmaAllocation allocation = nullptr; @@ -1020,10 +1020,10 @@ public: [[nodiscard]] PipelineLayout CreatePipelineLayout(const VkPipelineLayoutCreateInfo& ci) const; [[nodiscard]] Pipeline CreateGraphicsPipeline(const VkGraphicsPipelineCreateInfo& ci, - VkPipelineCache cache = nullptr) const; + VkPipelineCache cache = {}) const; [[nodiscard]] Pipeline CreateComputePipeline(const VkComputePipelineCreateInfo& ci, - VkPipelineCache cache = nullptr) const; + VkPipelineCache cache = {}) const; [[nodiscard]] Sampler CreateSampler(const VkSamplerCreateInfo& ci) const; From 529b0694995c84c51515022c52a66c67ceacdc65 Mon Sep 17 00:00:00 2001 From: xbzk Date: Thu, 5 Mar 2026 13:58:46 +0100 Subject: [PATCH 029/145] [android,ui] fixed top disalignment between buttons of each column in settings fragment (#3675) this silly little thing tickles obsessive compulsive disturbed fellas a lot hu3 was shipped along PR 3660, which was rediscussed for other reason, hence this tiny lonely PR. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3675 Reviewed-by: DraVee Reviewed-by: MaranBr Co-authored-by: xbzk Co-committed-by: xbzk --- .../features/fetcher/SpacingItemDecoration.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/fetcher/SpacingItemDecoration.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/fetcher/SpacingItemDecoration.kt index f3d000a739..b3ffcc2a35 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/fetcher/SpacingItemDecoration.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/fetcher/SpacingItemDecoration.kt @@ -1,10 +1,11 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later package org.yuzu.yuzu_emu.features.fetcher import android.graphics.Rect import android.view.View +import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView class SpacingItemDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() { @@ -15,8 +16,20 @@ class SpacingItemDecoration(private val spacing: Int) : RecyclerView.ItemDecorat state: RecyclerView.State ) { outRect.bottom = spacing - if (parent.getChildAdapterPosition(view) == 0) { + + val position = parent.getChildAdapterPosition(view) + if (position == RecyclerView.NO_POSITION) return + + if (position == 0) { outRect.top = spacing + return + } + + // If the item is in the first row, but NOT in first column add top spacing as well + val layoutManager = parent.layoutManager + if (layoutManager is GridLayoutManager && layoutManager.spanSizeLookup.getSpanGroupIndex(position, layoutManager.spanCount) == 0) { + outRect.top = spacing + return } } } From 23566a1f7dc639946e6d3935f4951d4d2bce8461 Mon Sep 17 00:00:00 2001 From: MaranBr Date: Fri, 6 Mar 2026 15:02:59 +0100 Subject: [PATCH 030/145] [prepo] Add support for missing PlayReport commands (#3674) This fixes: `[ 433.095195] Debug core\hle\service\service.cpp:operator ():69: Assertion Failed! Unknown / unimplemented function '10107': port='prepo:u' cmd_buf={[0]=0x110006, [1]=0x80000014, [2]=0x1, [3]=0x0, [4]=0x0, [5]=0x191080, [6]=0x5A7350F8, [7]=0x112, [8]=0x5A735158}` Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3674 Reviewed-by: CamilleLaVey Reviewed-by: DraVee Reviewed-by: Maufeat Co-authored-by: MaranBr Co-committed-by: MaranBr --- src/core/hle/service/prepo/prepo.cpp | 8 +++++--- src/core/reporter.h | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/core/hle/service/prepo/prepo.cpp b/src/core/hle/service/prepo/prepo.cpp index 4fc59d0e10..bfc5539903 100644 --- a/src/core/hle/service/prepo/prepo.cpp +++ b/src/core/hle/service/prepo/prepo.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project @@ -28,8 +28,10 @@ public: {10101, &PlayReport::SaveReportWithUser, "SaveReportWithUserOld"}, {10102, &PlayReport::SaveReport, "SaveReportOld2"}, {10103, &PlayReport::SaveReportWithUser, "SaveReportWithUserOld2"}, - {10104, &PlayReport::SaveReport, "SaveReport"}, - {10105, &PlayReport::SaveReportWithUser, "SaveReportWithUser"}, + {10104, &PlayReport::SaveReport, "SaveReportOld3"}, + {10105, &PlayReport::SaveReportWithUser, "SaveReportWithUserOld3"}, + {10106, &PlayReport::SaveReport, "SaveReport"}, + {10107, &PlayReport::SaveReportWithUser, "SaveReportWithUser"}, {10200, &PlayReport::RequestImmediateTransmission, "RequestImmediateTransmission"}, {10300, &PlayReport::GetTransmissionStatus, "GetTransmissionStatus"}, {10400, &PlayReport::GetSystemSessionId, "GetSystemSessionId"}, diff --git a/src/core/reporter.h b/src/core/reporter.h index db1ca3ba0c..1eee8da31f 100644 --- a/src/core/reporter.h +++ b/src/core/reporter.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later @@ -53,6 +56,7 @@ public: enum class PlayReportType { Old, Old2, + Old3, New, System, }; From c70b857c4f8324621c3d3f7dfe659856c8000878 Mon Sep 17 00:00:00 2001 From: lizzie Date: Fri, 6 Mar 2026 15:04:38 +0100 Subject: [PATCH 031/145] [video_core/engines] Macro HLE inline (#3653) Should slightly boost perf on android, Desktop is mainly unaffected (for now) Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3653 Reviewed-by: CamilleLaVey Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- src/video_core/engines/maxwell_3d.cpp | 21 +- src/video_core/engines/maxwell_3d.h | 2 +- src/video_core/macro.cpp | 1103 ++++++++++--------------- src/video_core/macro.h | 166 +++- 4 files changed, 586 insertions(+), 706 deletions(-) diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp index 7dbb8f6617..e48f294a5a 100644 --- a/src/video_core/engines/maxwell_3d.cpp +++ b/src/video_core/engines/maxwell_3d.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project @@ -26,8 +26,15 @@ namespace Tegra::Engines { constexpr u32 MacroRegistersStart = 0xE00; Maxwell3D::Maxwell3D(Core::System& system_, MemoryManager& memory_manager_) - : draw_manager{std::make_unique(this)}, system{system_}, - memory_manager{memory_manager_}, macro_engine{GetMacroEngine(*this)}, upload_state{memory_manager, regs.upload} { + : draw_manager{std::make_unique(this)}, system{system_} + , memory_manager{memory_manager_} +#ifdef ARCHITECTURE_x86_64 + , macro_engine(bool(Settings::values.disable_macro_jit)) +#else + , macro_engine(true) +#endif + , upload_state{memory_manager, regs.upload} +{ dirty.flags.flip(); InitializeRegisterDefaults(); execution_mask.reset(); @@ -328,9 +335,9 @@ void Maxwell3D::ProcessMethodCall(u32 method, u32 argument, u32 nonshadow_argume shadow_state.shadow_ram_control = static_cast(nonshadow_argument); return; case MAXWELL3D_REG_INDEX(load_mme.instruction_ptr): - return macro_engine->ClearCode(regs.load_mme.instruction_ptr); + return macro_engine.ClearCode(regs.load_mme.instruction_ptr); case MAXWELL3D_REG_INDEX(load_mme.instruction): - return macro_engine->AddCode(regs.load_mme.instruction_ptr, argument); + return macro_engine.AddCode(regs.load_mme.instruction_ptr, argument); case MAXWELL3D_REG_INDEX(load_mme.start_address): return ProcessMacroBind(argument); case MAXWELL3D_REG_INDEX(falcon[4]): @@ -398,7 +405,7 @@ void Maxwell3D::CallMacroMethod(u32 method, const std::vector& parameters) ((method - MacroRegistersStart) >> 1) % static_cast(macro_positions.size()); // Execute the current macro. - macro_engine->Execute(macro_positions[entry], parameters); + macro_engine.Execute(*this, macro_positions[entry], parameters); draw_manager->DrawDeferred(); } @@ -464,7 +471,7 @@ void Maxwell3D::CallMultiMethod(u32 method, const u32* base_start, u32 amount, } void Maxwell3D::ProcessMacroUpload(u32 data) { - macro_engine->AddCode(regs.load_mme.instruction_ptr++, data); + macro_engine.AddCode(regs.load_mme.instruction_ptr++, data); } void Maxwell3D::ProcessMacroBind(u32 data) { diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h index 5312c04b6f..52546e4279 100644 --- a/src/video_core/engines/maxwell_3d.h +++ b/src/video_core/engines/maxwell_3d.h @@ -3203,7 +3203,7 @@ private: std::vector macro_params; /// Interpreter for the macro codes uploaded to the GPU. - std::optional macro_engine; + MacroEngine macro_engine; Upload::State upload_state; diff --git a/src/video_core/macro.cpp b/src/video_core/macro.cpp index 3fe69be4dd..0d1fe0a52b 100644 --- a/src/video_core/macro.cpp +++ b/src/video_core/macro.cpp @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -10,6 +10,7 @@ #include #include +#include #ifdef ARCHITECTURE_x86_64 // xbyak hates human beings #ifdef __GNUC__ @@ -73,601 +74,411 @@ bool IsTopologySafe(Maxwell3D::Regs::PrimitiveTopology topology) { } } -class HLEMacroImpl : public CachedMacro { -public: - explicit HLEMacroImpl(Maxwell3D& maxwell3d_) - : CachedMacro(maxwell3d_) - {} -}; +} // Anonymous namespace -/// @note: these macros have two versions, a normal and extended version, with the extended version -/// also assigning the base vertex/instance. -template -class HLE_DrawArraysIndirect final : public HLEMacroImpl { -public: - explicit HLE_DrawArraysIndirect(Maxwell3D& maxwell3d_) - : HLEMacroImpl(maxwell3d_) - {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - auto topology = static_cast(parameters[0]); - if (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology)) { - Fallback(parameters); - return; - } - - auto& params = maxwell3d.draw_manager->GetIndirectParams(); - params.is_byte_count = false; - params.is_indexed = false; - params.include_count = false; - params.count_start_address = 0; - params.indirect_start_address = maxwell3d.GetMacroAddress(1); - params.buffer_size = 4 * sizeof(u32); - params.max_draw_counts = 1; - params.stride = 0; - - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - } - - maxwell3d.draw_manager->DrawArrayIndirect(topology); - - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::None; - maxwell3d.replace_table.clear(); - } +void HLE_DrawArraysIndirect::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + auto topology = static_cast(parameters[0]); + if (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology)) { + Fallback(maxwell3d, parameters); + return; } -private: - void Fallback(const std::vector& parameters) { - SCOPE_EXIT { - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::None; - maxwell3d.replace_table.clear(); - } - }; - maxwell3d.RefreshParameters(); - const u32 instance_count = (maxwell3d.GetRegisterValue(0xD1B) & parameters[2]); + auto& params = maxwell3d.draw_manager->GetIndirectParams(); + params.is_byte_count = false; + params.is_indexed = false; + params.include_count = false; + params.count_start_address = 0; + params.indirect_start_address = maxwell3d.GetMacroAddress(1); + params.buffer_size = 4 * sizeof(u32); + params.max_draw_counts = 1; + params.stride = 0; - auto topology = static_cast(parameters[0]); - const u32 vertex_first = parameters[3]; - const u32 vertex_count = parameters[1]; - - if (!IsTopologySafe(topology) && size_t(maxwell3d.GetMaxCurrentVertices()) < size_t(vertex_first) + size_t(vertex_count)) { - ASSERT(false && "Faulty draw!"); - return; - } - - const u32 base_instance = parameters[4]; - if (extended) { - maxwell3d.regs.global_base_instance_index = base_instance; - maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType( - 0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - } - - maxwell3d.draw_manager->DrawArray(topology, vertex_first, vertex_count, base_instance, - instance_count); - - if (extended) { - maxwell3d.regs.global_base_instance_index = 0; - maxwell3d.engine_state = Maxwell3D::EngineHint::None; - maxwell3d.replace_table.clear(); - } - } -}; - -/* - * @note: these macros have two versions, a normal and extended version, with the extended version - * also assigning the base vertex/instance. - */ -template -class HLE_DrawIndexedIndirect final : public HLEMacroImpl { -public: - explicit HLE_DrawIndexedIndirect(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - auto topology = static_cast(parameters[0]); - if (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology)) { - Fallback(parameters); - return; - } - - const u32 estimate = static_cast(maxwell3d.EstimateIndexBufferSize()); - const u32 element_base = parameters[4]; - const u32 base_instance = parameters[5]; - maxwell3d.regs.vertex_id_base = element_base; - maxwell3d.regs.global_base_vertex_index = element_base; - maxwell3d.regs.global_base_instance_index = base_instance; - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); - maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - } - auto& params = maxwell3d.draw_manager->GetIndirectParams(); - params.is_byte_count = false; - params.is_indexed = true; - params.include_count = false; - params.count_start_address = 0; - params.indirect_start_address = maxwell3d.GetMacroAddress(1); - params.buffer_size = 5 * sizeof(u32); - params.max_draw_counts = 1; - params.stride = 0; - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; - maxwell3d.draw_manager->DrawIndexedIndirect(topology, 0, estimate); - maxwell3d.regs.vertex_id_base = 0x0; - maxwell3d.regs.global_base_vertex_index = 0x0; - maxwell3d.regs.global_base_instance_index = 0x0; - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::None; - maxwell3d.replace_table.clear(); - } - } - -private: - void Fallback(const std::vector& parameters) { - maxwell3d.RefreshParameters(); - const u32 instance_count = (maxwell3d.GetRegisterValue(0xD1B) & parameters[2]); - const u32 element_base = parameters[4]; - const u32 base_instance = parameters[5]; - maxwell3d.regs.vertex_id_base = element_base; - maxwell3d.regs.global_base_vertex_index = element_base; - maxwell3d.regs.global_base_instance_index = base_instance; - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); - maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - } - - maxwell3d.draw_manager->DrawIndex(Tegra::Maxwell3D::Regs::PrimitiveTopology(parameters[0]), parameters[3], parameters[1], element_base, base_instance, instance_count); - - maxwell3d.regs.vertex_id_base = 0x0; - maxwell3d.regs.global_base_vertex_index = 0x0; - maxwell3d.regs.global_base_instance_index = 0x0; - if (extended) { - maxwell3d.engine_state = Maxwell3D::EngineHint::None; - maxwell3d.replace_table.clear(); - } - } -}; - -class HLE_MultiLayerClear final : public HLEMacroImpl { -public: - explicit HLE_MultiLayerClear(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - ASSERT(parameters.size() == 1); - - const Maxwell3D::Regs::ClearSurface clear_params{parameters[0]}; - const u32 rt_index = clear_params.RT; - const u32 num_layers = maxwell3d.regs.rt[rt_index].depth; - ASSERT(clear_params.layer == 0); - - maxwell3d.regs.clear_surface.raw = clear_params.raw; - maxwell3d.draw_manager->Clear(num_layers); - } -}; - -class HLE_MultiDrawIndexedIndirectCount final : public HLEMacroImpl { -public: - explicit HLE_MultiDrawIndexedIndirectCount(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - const auto topology = Maxwell3D::Regs::PrimitiveTopology(parameters[2]); - if (!IsTopologySafe(topology)) { - Fallback(parameters); - return; - } - - const u32 start_indirect = parameters[0]; - const u32 end_indirect = parameters[1]; - if (start_indirect >= end_indirect) { - // Nothing to do. - return; - } - - const u32 padding = parameters[3]; // padding is in words - - // size of each indirect segment - const u32 indirect_words = 5 + padding; - const u32 stride = indirect_words * sizeof(u32); - const std::size_t draw_count = end_indirect - start_indirect; - const u32 estimate = static_cast(maxwell3d.EstimateIndexBufferSize()); - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; - auto& params = maxwell3d.draw_manager->GetIndirectParams(); - params.is_byte_count = false; - params.is_indexed = true; - params.include_count = true; - params.count_start_address = maxwell3d.GetMacroAddress(4); - params.indirect_start_address = maxwell3d.GetMacroAddress(5); - params.buffer_size = stride * draw_count; - params.max_draw_counts = draw_count; - params.stride = stride; - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + if (extended) { maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType( - 0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); - maxwell3d.SetHLEReplacementAttributeType( - 0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - maxwell3d.SetHLEReplacementAttributeType(0, 0x648, - Maxwell3D::HLEReplacementAttributeType::DrawID); - maxwell3d.draw_manager->DrawIndexedIndirect(topology, 0, estimate); + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseInstance); + } + + maxwell3d.draw_manager->DrawArrayIndirect(topology); + + if (extended) { maxwell3d.engine_state = Maxwell3D::EngineHint::None; maxwell3d.replace_table.clear(); } - -private: - void Fallback(const std::vector& parameters) { - SCOPE_EXIT { - // Clean everything. - maxwell3d.regs.vertex_id_base = 0x0; +} +void HLE_DrawArraysIndirect::Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters) { + SCOPE_EXIT { + if (extended) { maxwell3d.engine_state = Maxwell3D::EngineHint::None; maxwell3d.replace_table.clear(); - }; - maxwell3d.RefreshParameters(); - const u32 start_indirect = parameters[0]; - const u32 end_indirect = parameters[1]; - if (start_indirect >= end_indirect) { - // Nothing to do. - return; - } - const auto topology = static_cast(parameters[2]); - const u32 padding = parameters[3]; - const std::size_t max_draws = parameters[4]; - - const u32 indirect_words = 5 + padding; - const std::size_t first_draw = start_indirect; - const std::size_t effective_draws = end_indirect - start_indirect; - const std::size_t last_draw = start_indirect + (std::min)(effective_draws, max_draws); - - for (std::size_t index = first_draw; index < last_draw; index++) { - const std::size_t base = index * indirect_words + 5; - const u32 base_vertex = parameters[base + 3]; - const u32 base_instance = parameters[base + 4]; - maxwell3d.regs.vertex_id_base = base_vertex; - maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; - maxwell3d.SetHLEReplacementAttributeType( - 0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); - maxwell3d.SetHLEReplacementAttributeType( - 0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); - maxwell3d.CallMethod(0x8e3, 0x648, true); - maxwell3d.CallMethod(0x8e4, static_cast(index), true); - maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; - maxwell3d.draw_manager->DrawIndex(topology, parameters[base + 2], parameters[base], - base_vertex, base_instance, parameters[base + 1]); } + }; + maxwell3d.RefreshParameters(); + const u32 instance_count = (maxwell3d.GetRegisterValue(0xD1B) & parameters[2]); + auto topology = Maxwell3D::Regs::PrimitiveTopology(parameters[0]); + const u32 vertex_first = parameters[3]; + const u32 vertex_count = parameters[1]; + if (!IsTopologySafe(topology) && size_t(maxwell3d.GetMaxCurrentVertices()) < size_t(vertex_first) + size_t(vertex_count)) { + ASSERT(false && "Faulty draw!"); + return; } -}; - -class HLE_DrawIndirectByteCount final : public HLEMacroImpl { -public: - explicit HLE_DrawIndirectByteCount(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - const bool force = maxwell3d.Rasterizer().HasDrawTransformFeedback(); - - auto topology = static_cast(parameters[0] & 0xFFFFU); - if (!force && (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology))) { - Fallback(parameters); - return; - } - auto& params = maxwell3d.draw_manager->GetIndirectParams(); - params.is_byte_count = true; - params.is_indexed = false; - params.include_count = false; - params.count_start_address = 0; - params.indirect_start_address = maxwell3d.GetMacroAddress(2); - params.buffer_size = 4; - params.max_draw_counts = 1; - params.stride = parameters[1]; - maxwell3d.regs.draw.begin = parameters[0]; - maxwell3d.regs.draw_auto_stride = parameters[1]; - maxwell3d.regs.draw_auto_byte_count = parameters[2]; - - maxwell3d.draw_manager->DrawArrayIndirect(topology); + const u32 base_instance = parameters[4]; + if (extended) { + maxwell3d.regs.global_base_instance_index = base_instance; + maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseInstance); } - -private: - void Fallback(const std::vector& parameters) { - maxwell3d.RefreshParameters(); - - maxwell3d.regs.draw.begin = parameters[0]; - maxwell3d.regs.draw_auto_stride = parameters[1]; - maxwell3d.regs.draw_auto_byte_count = parameters[2]; - - maxwell3d.draw_manager->DrawArray( - maxwell3d.regs.draw.topology, 0, - maxwell3d.regs.draw_auto_byte_count / maxwell3d.regs.draw_auto_stride, 0, 1); - } -}; - -class HLE_C713C83D8F63CCF3 final : public HLEMacroImpl { -public: - explicit HLE_C713C83D8F63CCF3(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - const u32 offset = (parameters[0] & 0x3FFFFFFF) << 2; - const u32 address = maxwell3d.regs.shadow_scratch[24]; - auto& const_buffer = maxwell3d.regs.const_buffer; - const_buffer.size = 0x7000; - const_buffer.address_high = (address >> 24) & 0xFF; - const_buffer.address_low = address << 8; - const_buffer.offset = offset; - } -}; - -class HLE_D7333D26E0A93EDE final : public HLEMacroImpl { -public: - explicit HLE_D7333D26E0A93EDE(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - const size_t index = parameters[0]; - const u32 address = maxwell3d.regs.shadow_scratch[42 + index]; - const u32 size = maxwell3d.regs.shadow_scratch[47 + index]; - auto& const_buffer = maxwell3d.regs.const_buffer; - const_buffer.size = size; - const_buffer.address_high = (address >> 24) & 0xFF; - const_buffer.address_low = address << 8; - } -}; - -class HLE_BindShader final : public HLEMacroImpl { -public: - explicit HLE_BindShader(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - auto& regs = maxwell3d.regs; - const u32 index = parameters[0]; - if ((parameters[1] - regs.shadow_scratch[28 + index]) == 0) { - return; - } - - regs.pipelines[index & 0xF].offset = parameters[2]; - maxwell3d.dirty.flags[VideoCommon::Dirty::Shaders] = true; - regs.shadow_scratch[28 + index] = parameters[1]; - regs.shadow_scratch[34 + index] = parameters[2]; - - const u32 address = parameters[4]; - auto& const_buffer = regs.const_buffer; - const_buffer.size = 0x10000; - const_buffer.address_high = (address >> 24) & 0xFF; - const_buffer.address_low = address << 8; - - const size_t bind_group_id = parameters[3] & 0x7F; - auto& bind_group = regs.bind_groups[bind_group_id]; - bind_group.raw_config = 0x11; - maxwell3d.ProcessCBBind(bind_group_id); - } -}; - -class HLE_SetRasterBoundingBox final : public HLEMacroImpl { -public: - explicit HLE_SetRasterBoundingBox(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - const u32 raster_mode = parameters[0]; - auto& regs = maxwell3d.regs; - const u32 raster_enabled = maxwell3d.regs.conservative_raster_enable; - const u32 scratch_data = maxwell3d.regs.shadow_scratch[52]; - regs.raster_bounding_box.raw = raster_mode & 0xFFFFF00F; - regs.raster_bounding_box.pad.Assign(scratch_data & raster_enabled); - } -}; - -template -class HLE_ClearConstBuffer final : public HLEMacroImpl { -public: - explicit HLE_ClearConstBuffer(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - static constexpr std::array zeroes{}; - auto& regs = maxwell3d.regs; - regs.const_buffer.size = u32(base_size); - regs.const_buffer.address_high = parameters[0]; - regs.const_buffer.address_low = parameters[1]; - regs.const_buffer.offset = 0; - maxwell3d.ProcessCBMultiData(zeroes.data(), parameters[2] * 4); - } -}; - -class HLE_ClearMemory final : public HLEMacroImpl { -public: - explicit HLE_ClearMemory(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - - const u32 needed_memory = parameters[2] / sizeof(u32); - if (needed_memory > zero_memory.size()) { - zero_memory.resize(needed_memory, 0); - } - auto& regs = maxwell3d.regs; - regs.upload.line_length_in = parameters[2]; - regs.upload.line_count = 1; - regs.upload.dest.address_high = parameters[0]; - regs.upload.dest.address_low = parameters[1]; - maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(launch_dma)), 0x1011, true); - maxwell3d.CallMultiMethod(size_t(MAXWELL3D_REG_INDEX(inline_data)), zero_memory.data(), needed_memory, needed_memory); - } - -private: - std::vector zero_memory; -}; - -class HLE_TransformFeedbackSetup final : public HLEMacroImpl { -public: - explicit HLE_TransformFeedbackSetup(Maxwell3D& maxwell3d_) : HLEMacroImpl(maxwell3d_) {} - - void Execute(const std::vector& parameters, [[maybe_unused]] u32 method) override { - maxwell3d.RefreshParameters(); - - auto& regs = maxwell3d.regs; - regs.transform_feedback_enabled = 1; - regs.transform_feedback.buffers[0].start_offset = 0; - regs.transform_feedback.buffers[1].start_offset = 0; - regs.transform_feedback.buffers[2].start_offset = 0; - regs.transform_feedback.buffers[3].start_offset = 0; - - regs.upload.line_length_in = 4; - regs.upload.line_count = 1; - regs.upload.dest.address_high = parameters[0]; - regs.upload.dest.address_low = parameters[1]; - maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(launch_dma)), 0x1011, true); - maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(inline_data)), regs.transform_feedback.controls[0].stride, true); - - maxwell3d.Rasterizer().RegisterTransformFeedback(regs.upload.dest.Address()); - } -}; - -} // Anonymous namespace - -HLEMacro::HLEMacro(Maxwell3D& maxwell3d_) : maxwell3d{maxwell3d_} {} - -HLEMacro::~HLEMacro() = default; - -std::unique_ptr HLEMacro::GetHLEProgram(u64 hash) const { - // Compiler will make you a GREAT job at making an ad-hoc hash table :) - switch (hash) { - case 0x0D61FC9FAAC9FCADULL: return std::make_unique>(maxwell3d); - case 0x8A4D173EB99A8603ULL: return std::make_unique>(maxwell3d); - case 0x771BB18C62444DA0ULL: return std::make_unique>(maxwell3d); - case 0x0217920100488FF7ULL: return std::make_unique>(maxwell3d); - case 0x3F5E74B9C9A50164ULL: return std::make_unique(maxwell3d); - case 0xEAD26C3E2109B06BULL: return std::make_unique(maxwell3d); - case 0xC713C83D8F63CCF3ULL: return std::make_unique(maxwell3d); - case 0xD7333D26E0A93EDEULL: return std::make_unique(maxwell3d); - case 0xEB29B2A09AA06D38ULL: return std::make_unique(maxwell3d); - case 0xDB1341DBEB4C8AF7ULL: return std::make_unique(maxwell3d); - case 0x6C97861D891EDf7EULL: return std::make_unique>(maxwell3d); - case 0xD246FDDF3A6173D7ULL: return std::make_unique>(maxwell3d); - case 0xEE4D0004BEC8ECF4ULL: return std::make_unique(maxwell3d); - case 0xFC0CF27F5FFAA661ULL: return std::make_unique(maxwell3d); - case 0xB5F74EDB717278ECULL: return std::make_unique(maxwell3d); - default: - return nullptr; + maxwell3d.draw_manager->DrawArray(topology, vertex_first, vertex_count, base_instance, instance_count); + if (extended) { + maxwell3d.regs.global_base_instance_index = 0; + maxwell3d.engine_state = Maxwell3D::EngineHint::None; + maxwell3d.replace_table.clear(); } } -namespace { -class MacroInterpreterImpl final : public CachedMacro { -public: - explicit MacroInterpreterImpl(Engines::Maxwell3D& maxwell3d_, const std::vector& code_) - : CachedMacro(maxwell3d_) - , code{code_} - {} +void HLE_DrawIndexedIndirect::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + auto topology = static_cast(parameters[0]); + if (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology)) { + Fallback(maxwell3d, parameters); + return; + } - void Execute(const std::vector& params, u32 method) override; + const u32 estimate = u32(maxwell3d.EstimateIndexBufferSize()); + const u32 element_base = parameters[4]; + const u32 base_instance = parameters[5]; + maxwell3d.regs.vertex_id_base = element_base; + maxwell3d.regs.global_base_vertex_index = element_base; + maxwell3d.regs.global_base_instance_index = base_instance; + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + if (extended) { + maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); + maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); + } + auto& params = maxwell3d.draw_manager->GetIndirectParams(); + params.is_byte_count = false; + params.is_indexed = true; + params.include_count = false; + params.count_start_address = 0; + params.indirect_start_address = maxwell3d.GetMacroAddress(1); + params.buffer_size = 5 * sizeof(u32); + params.max_draw_counts = 1; + params.stride = 0; + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + maxwell3d.draw_manager->DrawIndexedIndirect(topology, 0, estimate); + maxwell3d.regs.vertex_id_base = 0x0; + maxwell3d.regs.global_base_vertex_index = 0x0; + maxwell3d.regs.global_base_instance_index = 0x0; + if (extended) { + maxwell3d.engine_state = Maxwell3D::EngineHint::None; + maxwell3d.replace_table.clear(); + } +} +void HLE_DrawIndexedIndirect::Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters) { + maxwell3d.RefreshParameters(); + const u32 instance_count = (maxwell3d.GetRegisterValue(0xD1B) & parameters[2]); + const u32 element_base = parameters[4]; + const u32 base_instance = parameters[5]; + maxwell3d.regs.vertex_id_base = element_base; + maxwell3d.regs.global_base_vertex_index = element_base; + maxwell3d.regs.global_base_instance_index = base_instance; + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + if (extended) { + maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); + maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); + } + maxwell3d.draw_manager->DrawIndex(Tegra::Maxwell3D::Regs::PrimitiveTopology(parameters[0]), parameters[3], parameters[1], element_base, base_instance, instance_count); + maxwell3d.regs.vertex_id_base = 0x0; + maxwell3d.regs.global_base_vertex_index = 0x0; + maxwell3d.regs.global_base_instance_index = 0x0; + if (extended) { + maxwell3d.engine_state = Maxwell3D::EngineHint::None; + maxwell3d.replace_table.clear(); + } +} +void HLE_MultiLayerClear::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + ASSERT(parameters.size() == 1); -private: - /// Resets the execution engine state, zeroing registers, etc. - void Reset(); + const Maxwell3D::Regs::ClearSurface clear_params{parameters[0]}; + const u32 rt_index = clear_params.RT; + const u32 num_layers = maxwell3d.regs.rt[rt_index].depth; + ASSERT(clear_params.layer == 0); - /** - * Executes a single macro instruction located at the current program counter. Returns whether - * the interpreter should keep running. - * - * @param is_delay_slot Whether the current step is being executed due to a delay slot in a - * previous instruction. - */ - bool Step(bool is_delay_slot); + maxwell3d.regs.clear_surface.raw = clear_params.raw; + maxwell3d.draw_manager->Clear(num_layers); +} +void HLE_MultiDrawIndexedIndirectCount::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + const auto topology = Maxwell3D::Regs::PrimitiveTopology(parameters[2]); + if (!IsTopologySafe(topology)) { + Fallback(maxwell3d, parameters); + return; + } - /// Calculates the result of an ALU operation. src_a OP src_b; - u32 GetALUResult(Macro::ALUOperation operation, u32 src_a, u32 src_b); + const u32 start_indirect = parameters[0]; + const u32 end_indirect = parameters[1]; + if (start_indirect >= end_indirect) { + // Nothing to do. + return; + } - /// Performs the result operation on the input result and stores it in the specified register - /// (if necessary). - void ProcessResult(Macro::ResultOperation operation, u32 reg, u32 result); + const u32 padding = parameters[3]; // padding is in words - /// Evaluates the branch condition and returns whether the branch should be taken or not. - bool EvaluateBranchCondition(Macro::BranchCondition cond, u32 value) const; + // size of each indirect segment + const u32 indirect_words = 5 + padding; + const u32 stride = indirect_words * sizeof(u32); + const std::size_t draw_count = end_indirect - start_indirect; + const u32 estimate = static_cast(maxwell3d.EstimateIndexBufferSize()); + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + auto& params = maxwell3d.draw_manager->GetIndirectParams(); + params.is_byte_count = false; + params.is_indexed = true; + params.include_count = true; + params.count_start_address = maxwell3d.GetMacroAddress(4); + params.indirect_start_address = maxwell3d.GetMacroAddress(5); + params.buffer_size = stride * draw_count; + params.max_draw_counts = draw_count; + params.stride = stride; + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); + maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); + maxwell3d.SetHLEReplacementAttributeType(0, 0x648, Maxwell3D::HLEReplacementAttributeType::DrawID); + maxwell3d.draw_manager->DrawIndexedIndirect(topology, 0, estimate); + maxwell3d.engine_state = Maxwell3D::EngineHint::None; + maxwell3d.replace_table.clear(); +} +void HLE_MultiDrawIndexedIndirectCount::Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters) { + SCOPE_EXIT { + // Clean everything. + maxwell3d.regs.vertex_id_base = 0x0; + maxwell3d.engine_state = Maxwell3D::EngineHint::None; + maxwell3d.replace_table.clear(); + }; + maxwell3d.RefreshParameters(); + const u32 start_indirect = parameters[0]; + const u32 end_indirect = parameters[1]; + if (start_indirect >= end_indirect) { + // Nothing to do. + return; + } + const auto topology = static_cast(parameters[2]); + const u32 padding = parameters[3]; + const std::size_t max_draws = parameters[4]; + const u32 indirect_words = 5 + padding; + const std::size_t first_draw = start_indirect; + const std::size_t effective_draws = end_indirect - start_indirect; + const std::size_t last_draw = start_indirect + (std::min)(effective_draws, max_draws); + for (std::size_t index = first_draw; index < last_draw; index++) { + const std::size_t base = index * indirect_words + 5; + const u32 base_vertex = parameters[base + 3]; + const u32 base_instance = parameters[base + 4]; + maxwell3d.regs.vertex_id_base = base_vertex; + maxwell3d.engine_state = Maxwell3D::EngineHint::OnHLEMacro; + maxwell3d.SetHLEReplacementAttributeType(0, 0x640, Maxwell3D::HLEReplacementAttributeType::BaseVertex); + maxwell3d.SetHLEReplacementAttributeType(0, 0x644, Maxwell3D::HLEReplacementAttributeType::BaseInstance); + maxwell3d.CallMethod(0x8e3, 0x648, true); + maxwell3d.CallMethod(0x8e4, static_cast(index), true); + maxwell3d.dirty.flags[VideoCommon::Dirty::IndexBuffer] = true; + maxwell3d.draw_manager->DrawIndex(topology, parameters[base + 2], parameters[base], base_vertex, base_instance, parameters[base + 1]); + } +} +void HLE_DrawIndirectByteCount::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + const bool force = maxwell3d.Rasterizer().HasDrawTransformFeedback(); + auto topology = Maxwell3D::Regs::PrimitiveTopology(parameters[0] & 0xFFFFU); + if (!force && (!maxwell3d.AnyParametersDirty() || !IsTopologySafe(topology))) { + Fallback(maxwell3d, parameters); + return; + } + auto& params = maxwell3d.draw_manager->GetIndirectParams(); + params.is_byte_count = true; + params.is_indexed = false; + params.include_count = false; + params.count_start_address = 0; + params.indirect_start_address = maxwell3d.GetMacroAddress(2); + params.buffer_size = 4; + params.max_draw_counts = 1; + params.stride = parameters[1]; + maxwell3d.regs.draw.begin = parameters[0]; + maxwell3d.regs.draw_auto_stride = parameters[1]; + maxwell3d.regs.draw_auto_byte_count = parameters[2]; + maxwell3d.draw_manager->DrawArrayIndirect(topology); +} +void HLE_DrawIndirectByteCount::Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters) { + maxwell3d.RefreshParameters(); - /// Reads an opcode at the current program counter location. - Macro::Opcode GetOpcode() const; + maxwell3d.regs.draw.begin = parameters[0]; + maxwell3d.regs.draw_auto_stride = parameters[1]; + maxwell3d.regs.draw_auto_byte_count = parameters[2]; - /// Returns the specified register's value. Register 0 is hardcoded to always return 0. - u32 GetRegister(u32 register_id) const; + maxwell3d.draw_manager->DrawArray( + maxwell3d.regs.draw.topology, 0, + maxwell3d.regs.draw_auto_byte_count / maxwell3d.regs.draw_auto_stride, 0, 1); +} +void HLE_C713C83D8F63CCF3::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + const u32 offset = (parameters[0] & 0x3FFFFFFF) << 2; + const u32 address = maxwell3d.regs.shadow_scratch[24]; + auto& const_buffer = maxwell3d.regs.const_buffer; + const_buffer.size = 0x7000; + const_buffer.address_high = (address >> 24) & 0xFF; + const_buffer.address_low = address << 8; + const_buffer.offset = offset; +} +void HLE_D7333D26E0A93EDE::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + const size_t index = parameters[0]; + const u32 address = maxwell3d.regs.shadow_scratch[42 + index]; + const u32 size = maxwell3d.regs.shadow_scratch[47 + index]; + auto& const_buffer = maxwell3d.regs.const_buffer; + const_buffer.size = size; + const_buffer.address_high = (address >> 24) & 0xFF; + const_buffer.address_low = address << 8; +} +void HLE_BindShader::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + auto& regs = maxwell3d.regs; + const u32 index = parameters[0]; + if ((parameters[1] - regs.shadow_scratch[28 + index]) == 0) { + return; + } - /// Sets the register to the input value. - void SetRegister(u32 register_id, u32 value); + regs.pipelines[index & 0xF].offset = parameters[2]; + maxwell3d.dirty.flags[VideoCommon::Dirty::Shaders] = true; + regs.shadow_scratch[28 + index] = parameters[1]; + regs.shadow_scratch[34 + index] = parameters[2]; - /// Sets the method address to use for the next Send instruction. - void SetMethodAddress(u32 address); + const u32 address = parameters[4]; + auto& const_buffer = regs.const_buffer; + const_buffer.size = 0x10000; + const_buffer.address_high = (address >> 24) & 0xFF; + const_buffer.address_low = address << 8; - /// Calls a GPU Engine method with the input parameter. - void Send(u32 value); + const size_t bind_group_id = parameters[3] & 0x7F; + auto& bind_group = regs.bind_groups[bind_group_id]; + bind_group.raw_config = 0x11; + maxwell3d.ProcessCBBind(bind_group_id); +} +void HLE_SetRasterBoundingBox::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + const u32 raster_mode = parameters[0]; + auto& regs = maxwell3d.regs; + const u32 raster_enabled = maxwell3d.regs.conservative_raster_enable; + const u32 scratch_data = maxwell3d.regs.shadow_scratch[52]; + regs.raster_bounding_box.raw = raster_mode & 0xFFFFF00F; + regs.raster_bounding_box.pad.Assign(scratch_data & raster_enabled); +} +void HLE_ClearConstBuffer::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + static constexpr std::array zeroes{}; //must be bigger than either 7000 or 5F00 + maxwell3d.RefreshParameters(); + auto& regs = maxwell3d.regs; + regs.const_buffer.size = u32(base_size); + regs.const_buffer.address_high = parameters[0]; + regs.const_buffer.address_low = parameters[1]; + regs.const_buffer.offset = 0; + maxwell3d.ProcessCBMultiData(zeroes.data(), parameters[2] * 4); +} +void HLE_ClearMemory::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + const u32 needed_memory = parameters[2] / sizeof(u32); + if (needed_memory > zero_memory.size()) { + zero_memory.resize(needed_memory, 0); + } + auto& regs = maxwell3d.regs; + regs.upload.line_length_in = parameters[2]; + regs.upload.line_count = 1; + regs.upload.dest.address_high = parameters[0]; + regs.upload.dest.address_low = parameters[1]; + maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(launch_dma)), 0x1011, true); + maxwell3d.CallMultiMethod(size_t(MAXWELL3D_REG_INDEX(inline_data)), zero_memory.data(), needed_memory, needed_memory); +} +void HLE_TransformFeedbackSetup::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method) { + maxwell3d.RefreshParameters(); + auto& regs = maxwell3d.regs; + regs.transform_feedback_enabled = 1; + regs.transform_feedback.buffers[0].start_offset = 0; + regs.transform_feedback.buffers[1].start_offset = 0; + regs.transform_feedback.buffers[2].start_offset = 0; + regs.transform_feedback.buffers[3].start_offset = 0; + regs.upload.line_length_in = 4; + regs.upload.line_count = 1; + regs.upload.dest.address_high = parameters[0]; + regs.upload.dest.address_low = parameters[1]; + maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(launch_dma)), 0x1011, true); + maxwell3d.CallMethod(size_t(MAXWELL3D_REG_INDEX(inline_data)), regs.transform_feedback.controls[0].stride, true); + maxwell3d.Rasterizer().RegisterTransformFeedback(regs.upload.dest.Address()); +} - /// Reads a GPU register located at the method address. - u32 Read(u32 method) const; +#define HLE_MACRO_LIST \ + HLE_MACRO_ELEM(0x0D61FC9FAAC9FCADULL, HLE_DrawArraysIndirect, (false)) \ + HLE_MACRO_ELEM(0x8A4D173EB99A8603ULL, HLE_DrawArraysIndirect, (true)) \ + HLE_MACRO_ELEM(0x771BB18C62444DA0ULL, HLE_DrawIndexedIndirect, (false)) \ + HLE_MACRO_ELEM(0x0217920100488FF7ULL, HLE_DrawIndexedIndirect, (true)) \ + HLE_MACRO_ELEM(0x3F5E74B9C9A50164ULL, HLE_MultiDrawIndexedIndirectCount, ()) \ + HLE_MACRO_ELEM(0xEAD26C3E2109B06BULL, HLE_MultiLayerClear, ()) \ + HLE_MACRO_ELEM(0xC713C83D8F63CCF3ULL, HLE_C713C83D8F63CCF3, ()) \ + HLE_MACRO_ELEM(0xD7333D26E0A93EDEULL, HLE_D7333D26E0A93EDE, ()) \ + HLE_MACRO_ELEM(0xEB29B2A09AA06D38ULL, HLE_BindShader, ()) \ + HLE_MACRO_ELEM(0xDB1341DBEB4C8AF7ULL, HLE_SetRasterBoundingBox, ()) \ + HLE_MACRO_ELEM(0x6C97861D891EDf7EULL, HLE_ClearConstBuffer, (0x5F00)) \ + HLE_MACRO_ELEM(0xD246FDDF3A6173D7ULL, HLE_ClearConstBuffer, (0x7000)) \ + HLE_MACRO_ELEM(0xEE4D0004BEC8ECF4ULL, HLE_ClearMemory, ()) \ + HLE_MACRO_ELEM(0xFC0CF27F5FFAA661ULL, HLE_TransformFeedbackSetup, ()) \ + HLE_MACRO_ELEM(0xB5F74EDB717278ECULL, HLE_DrawIndirectByteCount, ()) \ - /// Returns the next parameter in the parameter queue. - u32 FetchParameter(); +// Allocates and returns a cached macro if the hash matches a known function. +[[nodiscard]] inline AnyCachedMacro GetHLEProgram(u64 hash) noexcept { + // Compiler will make you a GREAT job at making an ad-hoc hash table :) + switch (hash) { +#define HLE_MACRO_ELEM(HASH, TY, VAL) case HASH: return TY VAL; + HLE_MACRO_LIST +#undef HLE_MACRO_ELEM + default: return std::monostate{}; + } +} +[[nodiscard]] inline bool CanBeHLEProgram(u64 hash) noexcept { + switch (hash) { +#define HLE_MACRO_ELEM(HASH, TY, VAL) case HASH: return true; + HLE_MACRO_LIST +#undef HLE_MACRO_ELEM + default: return false; + } +} - /// Current program counter - u32 pc{}; - /// Program counter to execute at after the delay slot is executed. - std::optional delayed_pc; - - /// General purpose macro registers. - std::array registers = {}; - - /// Method address to use for the next Send instruction. - Macro::MethodAddress method_address = {}; - - /// Input parameters of the current macro. - std::unique_ptr parameters; - std::size_t num_parameters = 0; - std::size_t parameters_capacity = 0; - /// Index of the next parameter that will be fetched by the 'parm' instruction. - u32 next_parameter_index = 0; - - bool carry_flag = false; - const std::vector& code; -}; - -void MacroInterpreterImpl::Execute(const std::vector& params, u32 method) { +void MacroInterpreterImpl::Execute(Engines::Maxwell3D& maxwell3d, std::span params, u32 method) { Reset(); registers[1] = params[0]; - num_parameters = params.size(); - - if (num_parameters > parameters_capacity) { - parameters_capacity = num_parameters; - parameters = std::make_unique(num_parameters); - } - std::memcpy(parameters.get(), params.data(), num_parameters * sizeof(u32)); + parameters.resize(params.size()); + std::memcpy(parameters.data(), params.data(), params.size() * sizeof(u32)); // Execute the code until we hit an exit condition. bool keep_executing = true; while (keep_executing) { - keep_executing = Step(false); + keep_executing = Step(maxwell3d, false); } // Assert the the macro used all the input parameters - ASSERT(next_parameter_index == num_parameters); + ASSERT(next_parameter_index == parameters.size()); } +/// Resets the execution engine state, zeroing registers, etc. void MacroInterpreterImpl::Reset() { registers = {}; pc = 0; delayed_pc = {}; method_address.raw = 0; - num_parameters = 0; + // Vector must hold its last indices otherwise wonky shit will happen // The next parameter index starts at 1, because $r1 already has the value of the first // parameter. next_parameter_index = 1; carry_flag = false; } -bool MacroInterpreterImpl::Step(bool is_delay_slot) { +/// @brief Executes a single macro instruction located at the current program counter. Returns whether +/// the interpreter should keep running. +/// @param is_delay_slot Whether the current step is being executed due to a delay slot in a previous instruction. +bool MacroInterpreterImpl::Step(Engines::Maxwell3D& maxwell3d, bool is_delay_slot) { u32 base_address = pc; Macro::Opcode opcode = GetOpcode(); @@ -682,14 +493,12 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { switch (opcode.operation) { case Macro::Operation::ALU: { - u32 result = GetALUResult(opcode.alu_operation, GetRegister(opcode.src_a), - GetRegister(opcode.src_b)); - ProcessResult(opcode.result_operation, opcode.dst, result); + u32 result = GetALUResult(opcode.alu_operation, GetRegister(opcode.src_a), GetRegister(opcode.src_b)); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, result); break; } case Macro::Operation::AddImmediate: { - ProcessResult(opcode.result_operation, opcode.dst, - GetRegister(opcode.src_a) + opcode.immediate); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, GetRegister(opcode.src_a) + opcode.immediate); break; } case Macro::Operation::ExtractInsert: { @@ -699,7 +508,7 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { src = (src >> opcode.bf_src_bit) & opcode.GetBitfieldMask(); dst &= ~(opcode.GetBitfieldMask() << opcode.bf_dst_bit); dst |= src << opcode.bf_dst_bit; - ProcessResult(opcode.result_operation, opcode.dst, dst); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, dst); break; } case Macro::Operation::ExtractShiftLeftImmediate: { @@ -708,7 +517,7 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { u32 result = ((src >> dst) & opcode.GetBitfieldMask()) << opcode.bf_dst_bit; - ProcessResult(opcode.result_operation, opcode.dst, result); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, result); break; } case Macro::Operation::ExtractShiftLeftRegister: { @@ -717,12 +526,12 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { u32 result = ((src >> opcode.bf_src_bit) & opcode.GetBitfieldMask()) << dst; - ProcessResult(opcode.result_operation, opcode.dst, result); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, result); break; } case Macro::Operation::Read: { - u32 result = Read(GetRegister(opcode.src_a) + opcode.immediate); - ProcessResult(opcode.result_operation, opcode.dst, result); + u32 result = Read(maxwell3d, GetRegister(opcode.src_a) + opcode.immediate); + ProcessResult(maxwell3d, opcode.result_operation, opcode.dst, result); break; } case Macro::Operation::Branch: { @@ -738,7 +547,7 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { delayed_pc = base_address + opcode.GetBranchTarget(); // Execute one more instruction due to the delay slot. - return Step(true); + return Step(maxwell3d, true); } break; } @@ -751,13 +560,13 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) { // cause an exit if it's executed inside a delay slot. if (opcode.is_exit && !is_delay_slot) { // Exit has a delay slot, execute the next instruction - Step(true); + Step(maxwell3d, true); return false; } - return true; } +/// Calculates the result of an ALU operation. src_a OP src_b; u32 MacroInterpreterImpl::GetALUResult(Macro::ALUOperation operation, u32 src_a, u32 src_b) { switch (operation) { case Macro::ALUOperation::Add: { @@ -797,7 +606,8 @@ u32 MacroInterpreterImpl::GetALUResult(Macro::ALUOperation operation, u32 src_a, } } -void MacroInterpreterImpl::ProcessResult(Macro::ResultOperation operation, u32 reg, u32 result) { +/// Performs the result operation on the input result and stores it in the specified register (if necessary). +void MacroInterpreterImpl::ProcessResult(Engines::Maxwell3D& maxwell3d, Macro::ResultOperation operation, u32 reg, u32 result) { switch (operation) { case Macro::ResultOperation::IgnoreAndFetch: // Fetch parameter and ignore result. @@ -815,12 +625,12 @@ void MacroInterpreterImpl::ProcessResult(Macro::ResultOperation operation, u32 r case Macro::ResultOperation::FetchAndSend: // Fetch parameter and send result. SetRegister(reg, FetchParameter()); - Send(result); + Send(maxwell3d, result); break; case Macro::ResultOperation::MoveAndSend: // Move and send result. SetRegister(reg, result); - Send(result); + Send(maxwell3d, result); break; case Macro::ResultOperation::FetchAndSetMethod: // Fetch parameter and use result as Method Address. @@ -831,13 +641,13 @@ void MacroInterpreterImpl::ProcessResult(Macro::ResultOperation operation, u32 r // Move result and use as Method Address, then fetch and send parameter. SetRegister(reg, result); SetMethodAddress(result); - Send(FetchParameter()); + Send(maxwell3d, FetchParameter()); break; case Macro::ResultOperation::MoveAndSetMethodSend: // Move result and use as Method Address, then send bits 12:17 of result. SetRegister(reg, result); SetMethodAddress(result); - Send((result >> 12) & 0b111111); + Send(maxwell3d, (result >> 12) & 0b111111); break; default: UNIMPLEMENTED_MSG("Unimplemented result operation {}", operation); @@ -845,6 +655,7 @@ void MacroInterpreterImpl::ProcessResult(Macro::ResultOperation operation, u32 r } } +/// Evaluates the branch condition and returns whether the branch should be taken or not. bool MacroInterpreterImpl::EvaluateBranchCondition(Macro::BranchCondition cond, u32 value) const { switch (cond) { case Macro::BranchCondition::Zero: @@ -855,46 +666,44 @@ bool MacroInterpreterImpl::EvaluateBranchCondition(Macro::BranchCondition cond, UNREACHABLE(); } +/// Reads an opcode at the current program counter location. Macro::Opcode MacroInterpreterImpl::GetOpcode() const { ASSERT((pc % sizeof(u32)) == 0); ASSERT(pc < code.size() * sizeof(u32)); return {code[pc / sizeof(u32)]}; } +/// Returns the specified register's value. Register 0 is hardcoded to always return 0. u32 MacroInterpreterImpl::GetRegister(u32 register_id) const { - return registers.at(register_id); + return registers[register_id]; } +/// Sets the register to the input value. void MacroInterpreterImpl::SetRegister(u32 register_id, u32 value) { // Register 0 is hardwired as the zero register. // Ensure no writes to it actually occur. - if (register_id == 0) { + if (register_id == 0) return; - } - - registers.at(register_id) = value; + registers[register_id] = value; } -void MacroInterpreterImpl::SetMethodAddress(u32 address) { - method_address.raw = address; -} - -void MacroInterpreterImpl::Send(u32 value) { +/// Calls a GPU Engine method with the input parameter. +void MacroInterpreterImpl::Send(Engines::Maxwell3D& maxwell3d, u32 value) { maxwell3d.CallMethod(method_address.address, value, true); // Increment the method address by the method increment. - method_address.address.Assign(method_address.address.Value() + - method_address.increment.Value()); + method_address.address.Assign(method_address.address.Value() + method_address.increment.Value()); } -u32 MacroInterpreterImpl::Read(u32 method) const { +/// Reads a GPU register located at the method address. +u32 MacroInterpreterImpl::Read(Engines::Maxwell3D& maxwell3d, u32 method) const { return maxwell3d.GetRegisterValue(method); } +/// Returns the next parameter in the parameter queue. u32 MacroInterpreterImpl::FetchParameter() { - ASSERT(next_parameter_index < num_parameters); + ASSERT(next_parameter_index < parameters.size()); return parameters[next_parameter_index++]; } -} // Anonymous namespace #ifdef ARCHITECTURE_x86_64 namespace { @@ -930,17 +739,15 @@ static const auto default_cg_mode = Xbyak::DontSetProtectRWE; static const auto default_cg_mode = nullptr; //Allow RWE #endif -class MacroJITx64Impl final : public Xbyak::CodeGenerator, public CachedMacro { -public: - explicit MacroJITx64Impl(Engines::Maxwell3D& maxwell3d_, const std::vector& code_) +struct MacroJITx64Impl final : public Xbyak::CodeGenerator, public DynamicCachedMacro { + explicit MacroJITx64Impl(std::span code_) : Xbyak::CodeGenerator(MAX_CODE_SIZE, default_cg_mode) - , CachedMacro(maxwell3d_) , code{code_} { Compile(); } - void Execute(const std::vector& parameters, u32 method) override; + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, u32 method) override; void Compile_ALU(Macro::Opcode opcode); void Compile_AddImmediate(Macro::Opcode opcode); @@ -950,18 +757,13 @@ public: void Compile_Read(Macro::Opcode opcode); void Compile_Branch(Macro::Opcode opcode); -private: void Optimizer_ScanFlags(); - void Compile(); bool Compile_NextInstruction(); - Xbyak::Reg32 Compile_FetchParameter(); Xbyak::Reg32 Compile_GetRegister(u32 index, Xbyak::Reg32 dst); - void Compile_ProcessResult(Macro::ResultOperation operation, u32 reg); void Compile_Send(Xbyak::Reg32 value); - Macro::Opcode GetOpCode() const; struct JITState { @@ -981,21 +783,17 @@ private: bool enable_asserts{}; }; OptimizerState optimizer{}; - std::optional next_opcode{}; ProgramType program{nullptr}; - std::array labels; std::array delay_skip; Xbyak::Label end_of_code{}; - bool is_delay_slot{}; u32 pc{}; - - const std::vector& code; + std::span code; }; -void MacroJITx64Impl::Execute(const std::vector& parameters, u32 method) { +void MacroJITx64Impl::Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, u32 method) { ASSERT_OR_EXECUTE(program != nullptr, { return; }); JITState state{}; state.maxwell3d = &maxwell3d; @@ -1231,7 +1029,7 @@ void MacroJITx64Impl::Compile_Read(Macro::Opcode opcode) { Compile_ProcessResult(opcode.result_operation, opcode.dst); } -void Send(Engines::Maxwell3D* maxwell3d, Macro::MethodAddress method_address, u32 value) { +static void MacroJIT_SendThunk(Engines::Maxwell3D* maxwell3d, Macro::MethodAddress method_address, u32 value) { maxwell3d->CallMethod(method_address.address, value, true); } @@ -1240,7 +1038,7 @@ void MacroJITx64Impl::Compile_Send(Xbyak::Reg32 value) { mov(Common::X64::ABI_PARAM1, qword[STATE]); mov(Common::X64::ABI_PARAM2.cvt32(), METHOD_ADDRESS); mov(Common::X64::ABI_PARAM3.cvt32(), value); - Common::X64::CallFarFunction(*this, &Send); + Common::X64::CallFarFunction(*this, &MacroJIT_SendThunk); Common::X64::ABI_PopRegistersAndAdjustStack(*this, PersistentCallerSavedRegs(), 0); Xbyak::Label dont_process{}; @@ -1452,10 +1250,8 @@ bool MacroJITx64Impl::Compile_NextInstruction() { return true; } -static void WarnInvalidParameter(uintptr_t parameter, uintptr_t max_parameter) { - LOG_CRITICAL(HW_GPU, - "Macro JIT: invalid parameter access 0x{:x} (0x{:x} is the last parameter)", - parameter, max_parameter - sizeof(u32)); +static void MacroJIT_ErrorThunk(uintptr_t parameter, uintptr_t max_parameter) { + LOG_CRITICAL(HW_GPU, "Macro JIT: invalid parameter access 0x{:x} (0x{:x} is the last parameter)", parameter, max_parameter - sizeof(u32)); } Xbyak::Reg32 MacroJITx64Impl::Compile_FetchParameter() { @@ -1465,7 +1261,7 @@ Xbyak::Reg32 MacroJITx64Impl::Compile_FetchParameter() { Common::X64::ABI_PushRegistersAndAdjustStack(*this, PersistentCallerSavedRegs(), 0); mov(Common::X64::ABI_PARAM1, PARAMETERS); mov(Common::X64::ABI_PARAM2, MAX_PARAMETER); - Common::X64::CallFarFunction(*this, &WarnInvalidParameter); + Common::X64::CallFarFunction(*this, &MacroJIT_ErrorThunk); Common::X64::ABI_PopRegistersAndAdjustStack(*this, PersistentCallerSavedRegs(), 0); L(parameter_ok); mov(eax, dword[PARAMETERS]); @@ -1574,33 +1370,42 @@ static void Dump(u64 hash, std::span code, bool decompiled = false) { macro_file.write(reinterpret_cast(code.data()), code.size_bytes()); } -MacroEngine::MacroEngine(Engines::Maxwell3D& maxwell3d_, bool is_interpreted_) - : hle_macros{std::make_optional(maxwell3d_)} - , maxwell3d{maxwell3d_} - , is_interpreted{is_interpreted_} -{} - -MacroEngine::~MacroEngine() = default; - -void MacroEngine::AddCode(u32 method, u32 data) { - uploaded_macro_code[method].push_back(data); -} - -void MacroEngine::ClearCode(u32 method) { - macro_cache.erase(method); - uploaded_macro_code.erase(method); -} - -void MacroEngine::Execute(u32 method, const std::vector& parameters) { - auto compiled_macro = macro_cache.find(method); - if (compiled_macro != macro_cache.end()) { - const auto& cache_info = compiled_macro->second; - if (cache_info.has_hle_program) { - cache_info.hle_program->Execute(parameters, method); - } else { - maxwell3d.RefreshParameters(); - cache_info.lle_program->Execute(parameters, method); - } +void MacroEngine::Execute(Engines::Maxwell3D& maxwell3d, u32 method, std::span parameters) { + auto const execute_variant = [&maxwell3d, ¶meters, method](AnyCachedMacro& acm) { + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if(&acm)) + a->Execute(maxwell3d, parameters, method); + if (auto a = std::get_if>(&acm)) + a->get()->Execute(maxwell3d, parameters, method); + }; + if (auto const it = macro_cache.find(method); it != macro_cache.end()) { + auto& ci = it->second; + if (!CanBeHLEProgram(ci.hash) || Settings::values.disable_macro_hle) + maxwell3d.RefreshParameters(); //LLE must reload parameters + execute_variant(ci.program); } else { // Macro not compiled, check if it's uploaded and if so, compile it std::optional mid_method; @@ -1617,51 +1422,37 @@ void MacroEngine::Execute(u32 method, const std::vector& parameters) { return; } } - auto& cache_info = macro_cache[method]; - - if (!mid_method.has_value()) { - cache_info.lle_program = Compile(macro_code->second); - cache_info.hash = Common::HashValue(macro_code->second); - } else { + auto& ci = macro_cache[method]; + if (mid_method) { const auto& macro_cached = uploaded_macro_code[mid_method.value()]; const auto rebased_method = method - mid_method.value(); auto& code = uploaded_macro_code[method]; code.resize(macro_cached.size() - rebased_method); std::memcpy(code.data(), macro_cached.data() + rebased_method, code.size() * sizeof(u32)); - cache_info.hash = Common::HashValue(code); - cache_info.lle_program = Compile(code); - } - - auto hle_program = hle_macros->GetHLEProgram(cache_info.hash); - if (!hle_program || Settings::values.disable_macro_hle) { - maxwell3d.RefreshParameters(); - cache_info.lle_program->Execute(parameters, method); + ci.hash = Common::HashValue(code); + ci.program = Compile(maxwell3d, code); } else { - cache_info.has_hle_program = true; - cache_info.hle_program = std::move(hle_program); - cache_info.hle_program->Execute(parameters, method); + ci.program = Compile(maxwell3d, macro_code->second); + ci.hash = Common::HashValue(macro_code->second); } - + if (CanBeHLEProgram(ci.hash) && !Settings::values.disable_macro_hle) { + ci.program = GetHLEProgram(ci.hash); + } else { + maxwell3d.RefreshParameters(); + } + execute_variant(ci.program); if (Settings::values.dump_macros) { - Dump(cache_info.hash, macro_code->second, cache_info.has_hle_program); + Dump(ci.hash, macro_code->second, !std::holds_alternative(ci.program)); } } } -std::unique_ptr MacroEngine::Compile(const std::vector& code) { +AnyCachedMacro MacroEngine::Compile(Engines::Maxwell3D& maxwell3d, std::span code) { #ifdef ARCHITECTURE_x86_64 if (!is_interpreted) - return std::make_unique(maxwell3d, code); -#endif - return std::make_unique(maxwell3d, code); -} - -std::optional GetMacroEngine(Engines::Maxwell3D& maxwell3d) { -#ifdef ARCHITECTURE_x86_64 - return std::make_optional(maxwell3d, bool(Settings::values.disable_macro_jit)); -#else - return std::make_optional(maxwell3d, true); + return std::make_unique(code); #endif + return MacroInterpreterImpl(code); } } // namespace Tegra diff --git a/src/video_core/macro.h b/src/video_core/macro.h index 9bdb4219ce..a9a8f2de04 100644 --- a/src/video_core/macro.h +++ b/src/video_core/macro.h @@ -7,8 +7,10 @@ #pragma once #include -#include +#include +#include #include +#include #include "common/bit_field.h" #include "common/common_types.h" @@ -98,62 +100,142 @@ union MethodAddress { } // namespace Macro -class CachedMacro { -public: - CachedMacro(Engines::Maxwell3D& maxwell3d_) - : maxwell3d{maxwell3d_} - {} - virtual ~CachedMacro() = default; +struct HLEMacro { +}; +/// @note: these macros have two versions, a normal and extended version, with the extended version +/// also assigning the base vertex/instance. +struct HLE_DrawArraysIndirect final { + HLE_DrawArraysIndirect(bool extended_) noexcept : extended{extended_} {} + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + void Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters); + bool extended; +}; +/// @note: these macros have two versions, a normal and extended version, with the extended version +/// also assigning the base vertex/instance. +struct HLE_DrawIndexedIndirect final { + explicit HLE_DrawIndexedIndirect(bool extended_) noexcept : extended{extended_} {} + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + void Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters); + bool extended; +}; +struct HLE_MultiLayerClear final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct HLE_MultiDrawIndexedIndirectCount final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + void Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters); +}; +struct HLE_DrawIndirectByteCount final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + void Fallback(Engines::Maxwell3D& maxwell3d, std::span parameters); +}; +struct HLE_C713C83D8F63CCF3 final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct HLE_D7333D26E0A93EDE final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct HLE_BindShader final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct HLE_SetRasterBoundingBox final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct HLE_ClearConstBuffer final { + HLE_ClearConstBuffer(size_t base_size_) noexcept : base_size{base_size_} {} + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + size_t base_size; +}; +struct HLE_ClearMemory final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); + std::vector zero_memory; +}; +struct HLE_TransformFeedbackSetup final { + void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, [[maybe_unused]] u32 method); +}; +struct MacroInterpreterImpl final { + MacroInterpreterImpl() {} + MacroInterpreterImpl(std::span code_) : code{code_} {} + void Execute(Engines::Maxwell3D& maxwell3d, std::span params, u32 method); + void Reset(); + bool Step(Engines::Maxwell3D& maxwell3d, bool is_delay_slot); + u32 GetALUResult(Macro::ALUOperation operation, u32 src_a, u32 src_b); + void ProcessResult(Engines::Maxwell3D& maxwell3d, Macro::ResultOperation operation, u32 reg, u32 result); + bool EvaluateBranchCondition(Macro::BranchCondition cond, u32 value) const; + Macro::Opcode GetOpcode() const; + u32 GetRegister(u32 register_id) const; + void SetRegister(u32 register_id, u32 value); + /// Sets the method address to use for the next Send instruction. + [[nodiscard]] inline void SetMethodAddress(u32 address) noexcept { + method_address.raw = address; + } + void Send(Engines::Maxwell3D& maxwell3d, u32 value); + u32 Read(Engines::Maxwell3D& maxwell3d, u32 method) const; + u32 FetchParameter(); + /// General purpose macro registers. + std::array registers = {}; + /// Input parameters of the current macro. + std::vector parameters; + std::span code; + /// Program counter to execute at after the delay slot is executed. + std::optional delayed_pc; + /// Method address to use for the next Send instruction. + Macro::MethodAddress method_address = {}; + /// Current program counter + u32 pc{}; + /// Index of the next parameter that will be fetched by the 'parm' instruction. + u32 next_parameter_index = 0; + bool carry_flag = false; +}; +struct DynamicCachedMacro { + virtual ~DynamicCachedMacro() = default; /// Executes the macro code with the specified input parameters. /// @param parameters The parameters of the macro /// @param method The method to execute - virtual void Execute(const std::vector& parameters, u32 method) = 0; - Engines::Maxwell3D& maxwell3d; + virtual void Execute(Engines::Maxwell3D& maxwell3d, std::span parameters, u32 method) = 0; }; -class HLEMacro { -public: - explicit HLEMacro(Engines::Maxwell3D& maxwell3d_); - ~HLEMacro(); - // Allocates and returns a cached macro if the hash matches a known function. - // Returns nullptr otherwise. - [[nodiscard]] std::unique_ptr GetHLEProgram(u64 hash) const; -private: - Engines::Maxwell3D& maxwell3d; -}; - -class MacroEngine { -public: - explicit MacroEngine(Engines::Maxwell3D& maxwell3d, bool is_interpreted); - ~MacroEngine(); +using AnyCachedMacro = std::variant< + std::monostate, + HLEMacro, + HLE_DrawArraysIndirect, + HLE_DrawIndexedIndirect, + HLE_MultiDrawIndexedIndirectCount, + HLE_MultiLayerClear, + HLE_C713C83D8F63CCF3, + HLE_D7333D26E0A93EDE, + HLE_BindShader, + HLE_SetRasterBoundingBox, + HLE_ClearConstBuffer, + HLE_ClearMemory, + HLE_TransformFeedbackSetup, + HLE_DrawIndirectByteCount, + MacroInterpreterImpl, + // Used for JIT x86 macro + std::unique_ptr +>; +struct MacroEngine { + MacroEngine(bool is_interpreted_) noexcept : is_interpreted{is_interpreted_} {} // Store the uploaded macro code to compile them when they're called. - void AddCode(u32 method, u32 data); - + inline void AddCode(u32 method, u32 data) noexcept { + uploaded_macro_code[method].push_back(data); + } // Clear the code associated with a method. - void ClearCode(u32 method); - + inline void ClearCode(u32 method) noexcept { + macro_cache.erase(method); + uploaded_macro_code.erase(method); + } // Compiles the macro if its not in the cache, and executes the compiled macro - void Execute(u32 method, const std::vector& parameters); - -protected: - std::unique_ptr Compile(const std::vector& code); - -private: + void Execute(Engines::Maxwell3D& maxwell3d, u32 method, std::span parameters); + AnyCachedMacro Compile(Engines::Maxwell3D& maxwell3d, std::span code); struct CacheInfo { - std::unique_ptr lle_program{}; - std::unique_ptr hle_program{}; + AnyCachedMacro program; u64 hash{}; - bool has_hle_program{}; }; - ankerl::unordered_dense::map macro_cache; ankerl::unordered_dense::map> uploaded_macro_code; - std::optional hle_macros; - Engines::Maxwell3D& maxwell3d; bool is_interpreted; }; -std::optional GetMacroEngine(Engines::Maxwell3D& maxwell3d); - } // namespace Tegra From 2ed1328c93c4739c069e7a284cb82b0a72762dac Mon Sep 17 00:00:00 2001 From: lizzie Date: Fri, 6 Mar 2026 15:05:05 +0100 Subject: [PATCH 032/145] [vk] use static_vector instead of small_vector for TFB and other bindings (#3641) MK8D is a big offender, taking up lots of time memcpy'ing and memmov'ing small_vector<> AND to add salt to the wound it doesn't even do heap allocations (no game does I think) - so basically useless waste of compute time in hot path for NO reason :^) Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3641 Reviewed-by: CamilleLaVey Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- .../buffer_cache/buffer_cache_base.h | 13 +++-- .../renderer_vulkan/vk_buffer_cache.cpp | 50 +++++++++---------- 2 files changed, 33 insertions(+), 30 deletions(-) diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h index 0596329392..08524bd854 100644 --- a/src/video_core/buffer_cache/buffer_cache_base.h +++ b/src/video_core/buffer_cache/buffer_cache_base.h @@ -14,9 +14,12 @@ #include #include #include -#include #include +#include +#include +#include + #include "common/common_types.h" #include "common/div_ceil.h" #include "common/literals.h" @@ -94,10 +97,10 @@ static constexpr Binding NULL_BINDING{ template struct HostBindings { - boost::container::small_vector buffers; - boost::container::small_vector offsets; - boost::container::small_vector sizes; - boost::container::small_vector strides; + boost::container::static_vector buffers; + boost::container::static_vector offsets; + boost::container::static_vector sizes; + boost::container::static_vector strides; u32 min_index{NUM_VERTEX_BUFFERS}; u32 max_index{0}; }; diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp index f4345262fb..c842cce709 100644 --- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp +++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp @@ -10,6 +10,7 @@ #include #include +#include "video_core/buffer_cache/buffer_cache_base.h" #include "video_core/renderer_vulkan/vk_buffer_cache.h" #include "video_core/renderer_vulkan/maxwell_to_vk.h" @@ -583,18 +584,18 @@ void BufferCacheRuntime::BindVertexBuffer(u32 index, VkBuffer buffer, u32 offset } void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings& bindings) { - boost::container::small_vector buffer_handles; - for (u32 index = 0; index < bindings.buffers.size(); ++index) { - auto handle = bindings.buffers[index]->Handle(); + boost::container::static_vector buffer_handles(bindings.buffers.size()); + for (u32 i = 0; i < bindings.buffers.size(); ++i) { + auto handle = bindings.buffers[i]->Handle(); if (handle == VK_NULL_HANDLE) { - bindings.offsets[index] = 0; - bindings.sizes[index] = VK_WHOLE_SIZE; + bindings.offsets[i] = 0; + bindings.sizes[i] = VK_WHOLE_SIZE; if (!device.HasNullDescriptor()) { ReserveNullBuffer(); handle = *null_buffer; } } - buffer_handles.push_back(handle); + buffer_handles[i] = handle; } const u32 device_max = device.GetMaxVertexInputBindings(); const u32 min_binding = (std::min)(bindings.min_index, device_max); @@ -604,19 +605,12 @@ void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings& bi return; } if (device.IsExtExtendedDynamicStateSupported()) { - scheduler.Record([bindings_ = std::move(bindings), - buffer_handles_ = std::move(buffer_handles), - binding_count](vk::CommandBuffer cmdbuf) { - cmdbuf.BindVertexBuffers2EXT(bindings_.min_index, binding_count, buffer_handles_.data(), - bindings_.offsets.data(), bindings_.sizes.data(), - bindings_.strides.data()); + scheduler.Record([bindings_ = std::move(bindings), buffer_handles_ = std::move(buffer_handles), binding_count](vk::CommandBuffer cmdbuf) { + cmdbuf.BindVertexBuffers2EXT(bindings_.min_index, binding_count, buffer_handles_.data(), bindings_.offsets.data(), bindings_.sizes.data(), bindings_.strides.data()); }); } else { - scheduler.Record([bindings_ = std::move(bindings), - buffer_handles_ = std::move(buffer_handles), - binding_count](vk::CommandBuffer cmdbuf) { - cmdbuf.BindVertexBuffers(bindings_.min_index, binding_count, buffer_handles_.data(), - bindings_.offsets.data()); + scheduler.Record([bindings_ = std::move(bindings), buffer_handles_ = std::move(buffer_handles), binding_count](vk::CommandBuffer cmdbuf) { + cmdbuf.BindVertexBuffers(bindings_.min_index, binding_count, buffer_handles_.data(), bindings_.offsets.data()); }); } } @@ -647,15 +641,21 @@ void BufferCacheRuntime::BindTransformFeedbackBuffers(VideoCommon::HostBindings< // Already logged in the rasterizer return; } - boost::container::small_vector buffer_handles; - for (u32 index = 0; index < bindings.buffers.size(); ++index) { - buffer_handles.push_back(bindings.buffers[index]->Handle()); + boost::container::static_vector buffer_handles(bindings.buffers.size()); + for (u32 i = 0; i < bindings.buffers.size(); ++i) { + auto handle = bindings.buffers[i]->Handle(); + if (handle == VK_NULL_HANDLE) { + bindings.offsets[i] = 0; + bindings.sizes[i] = VK_WHOLE_SIZE; + if (!device.HasNullDescriptor()) { + ReserveNullBuffer(); + handle = *null_buffer; + } + } + buffer_handles[i] = handle; } - scheduler.Record([bindings_ = std::move(bindings), - buffer_handles_ = std::move(buffer_handles)](vk::CommandBuffer cmdbuf) { - cmdbuf.BindTransformFeedbackBuffersEXT(0, static_cast(buffer_handles_.size()), - buffer_handles_.data(), bindings_.offsets.data(), - bindings_.sizes.data()); + scheduler.Record([bindings_ = std::move(bindings), buffer_handles_ = std::move(buffer_handles)](vk::CommandBuffer cmdbuf) { + cmdbuf.BindTransformFeedbackBuffersEXT(0, u32(buffer_handles_.size()), buffer_handles_.data(), bindings_.offsets.data(), bindings_.sizes.data()); }); } From b75e81af5e11cb09eae405d51c40489401794912 Mon Sep 17 00:00:00 2001 From: lizzie Date: Fri, 6 Mar 2026 15:05:39 +0100 Subject: [PATCH 033/145] [video_core/engines] implement stub NV01 timer, inline other channel engines (#3640) Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3640 Reviewed-by: CamilleLaVey Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- src/video_core/control/channel_state.cpp | 15 ++++--- src/video_core/control/channel_state.h | 44 +++++++++---------- src/video_core/engines/engine_interface.h | 3 +- src/video_core/engines/maxwell_3d.h | 2 +- src/video_core/engines/nv01_timer.h | 52 +++++++++++++++++++++++ src/video_core/engines/puller.cpp | 42 +++++++++--------- src/video_core/engines/puller.h | 4 ++ 7 files changed, 109 insertions(+), 53 deletions(-) create mode 100644 src/video_core/engines/nv01_timer.h diff --git a/src/video_core/control/channel_state.cpp b/src/video_core/control/channel_state.cpp index 2539997d53..d07c7e2a83 100644 --- a/src/video_core/control/channel_state.cpp +++ b/src/video_core/control/channel_state.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -19,12 +22,12 @@ ChannelState::ChannelState(s32 bind_id_) : bind_id{bind_id_}, initialized{} {} void ChannelState::Init(Core::System& system, GPU& gpu, u64 program_id_) { ASSERT(memory_manager); program_id = program_id_; - dma_pusher = std::make_unique(system, gpu, *memory_manager, *this); - maxwell_3d = std::make_unique(system, *memory_manager); - fermi_2d = std::make_unique(*memory_manager); - kepler_compute = std::make_unique(system, *memory_manager); - maxwell_dma = std::make_unique(system, *memory_manager); - kepler_memory = std::make_unique(system, *memory_manager); + dma_pusher.emplace(system, gpu, *memory_manager, *this); + maxwell_3d.emplace(system, *memory_manager); + fermi_2d.emplace(*memory_manager); + kepler_compute.emplace(system, *memory_manager); + maxwell_dma.emplace(system, *memory_manager); + kepler_memory.emplace(system, *memory_manager); initialized = true; } diff --git a/src/video_core/control/channel_state.h b/src/video_core/control/channel_state.h index b385f4939f..2984d2e09e 100644 --- a/src/video_core/control/channel_state.h +++ b/src/video_core/control/channel_state.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -6,6 +9,12 @@ #include #include "common/common_types.h" +#include "video_core/engines/fermi_2d.h" +#include "video_core/engines/kepler_memory.h" +#include "video_core/engines/kepler_compute.h" +#include "video_core/engines/maxwell_3d.h" +#include "video_core/engines/maxwell_dma.h" +#include "video_core/dma_pusher.h" namespace Core { class System; @@ -18,49 +27,34 @@ class RasterizerInterface; namespace Tegra { class GPU; - -namespace Engines { -class Puller; -class Fermi2D; -class Maxwell3D; -class MaxwellDMA; -class KeplerCompute; -class KeplerMemory; -} // namespace Engines - class MemoryManager; -class DmaPusher; namespace Control { struct ChannelState { explicit ChannelState(s32 bind_id); - ChannelState(const ChannelState& state) = delete; - ChannelState& operator=(const ChannelState&) = delete; - ChannelState(ChannelState&& other) noexcept = default; - ChannelState& operator=(ChannelState&& other) noexcept = default; void Init(Core::System& system, GPU& gpu, u64 program_id); void BindRasterizer(VideoCore::RasterizerInterface* rasterizer); - s32 bind_id = -1; - u64 program_id = 0; /// 3D engine - std::unique_ptr maxwell_3d; + std::optional maxwell_3d; /// 2D engine - std::unique_ptr fermi_2d; + std::optional fermi_2d; /// Compute engine - std::unique_ptr kepler_compute; + std::optional kepler_compute; /// DMA engine - std::unique_ptr maxwell_dma; + std::optional maxwell_dma; /// Inline memory engine - std::unique_ptr kepler_memory; - + std::optional kepler_memory; + /// NV01 Timer + std::optional nv01_timer; + std::optional dma_pusher; std::shared_ptr memory_manager; - std::unique_ptr dma_pusher; - + s32 bind_id = -1; + u64 program_id = 0; bool initialized{}; }; diff --git a/src/video_core/engines/engine_interface.h b/src/video_core/engines/engine_interface.h index e271ecab59..bf3bd66aca 100644 --- a/src/video_core/engines/engine_interface.h +++ b/src/video_core/engines/engine_interface.h @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project @@ -15,6 +15,7 @@ namespace Tegra::Engines { enum class EngineTypes : u32 { + Nv01Timer, KeplerCompute, Maxwell3D, Fermi2D, diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h index 52546e4279..b73082b7ef 100644 --- a/src/video_core/engines/maxwell_3d.h +++ b/src/video_core/engines/maxwell_3d.h @@ -2258,7 +2258,7 @@ public: /// Returns whether the vertex array specified by index is supposed to be /// accessed per instance or not. bool IsInstancingEnabled(std::size_t index) const { - return is_instanced[index]; + return bool(is_instanced[index]); //FUCK YOU MSVC } }; diff --git a/src/video_core/engines/nv01_timer.h b/src/video_core/engines/nv01_timer.h new file mode 100644 index 0000000000..a8e60f9f53 --- /dev/null +++ b/src/video_core/engines/nv01_timer.h @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include "common/bit_field.h" +#include "common/common_funcs.h" +#include "common/common_types.h" +#include "common/logging/log.h" +#include "video_core/engines/engine_interface.h" +#include "video_core/engines/engine_upload.h" + +namespace Core { +class System; +} + +namespace Tegra { +class MemoryManager; +} + +namespace Tegra::Engines { +class Nv01Timer final : public EngineInterface { +public: + explicit Nv01Timer(Core::System& system_, MemoryManager& memory_manager) + : system{system_} + {} + ~Nv01Timer() override; + + /// Write the value to the register identified by method. + void CallMethod(u32 method, u32 method_argument, bool is_last_call) override { + LOG_DEBUG(HW_GPU, "method={}, argument={}, is_last_call={}", method, method_argument, is_last_call); + } + + /// Write multiple values to the register identified by method. + void CallMultiMethod(u32 method, const u32* base_start, u32 amount, u32 methods_pending) override { + LOG_DEBUG(HW_GPU, "method={}, base_start={}, amount={}, pending={}", method, fmt::ptr(base_start), amount, methods_pending); + } + + struct Regs { + // No fucking idea + INSERT_PADDING_BYTES_NOINIT(0x48); + } regs{}; +private: + void ConsumeSinkImpl() override {} + Core::System& system; +}; +} diff --git a/src/video_core/engines/puller.cpp b/src/video_core/engines/puller.cpp index 8dd34c04ab..b5b4e5d7fa 100644 --- a/src/video_core/engines/puller.cpp +++ b/src/video_core/engines/puller.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -34,24 +37,22 @@ void Puller::ProcessBindMethod(const MethodCall& method_call) { bound_engines[method_call.subchannel] = engine_id; switch (engine_id) { case EngineID::FERMI_TWOD_A: - dma_pusher.BindSubchannel(channel_state.fermi_2d.get(), method_call.subchannel, - EngineTypes::Fermi2D); + dma_pusher.BindSubchannel(&*channel_state.fermi_2d, method_call.subchannel, EngineTypes::Fermi2D); break; case EngineID::MAXWELL_B: - dma_pusher.BindSubchannel(channel_state.maxwell_3d.get(), method_call.subchannel, - EngineTypes::Maxwell3D); + dma_pusher.BindSubchannel(&*channel_state.maxwell_3d, method_call.subchannel, EngineTypes::Maxwell3D); break; case EngineID::KEPLER_COMPUTE_B: - dma_pusher.BindSubchannel(channel_state.kepler_compute.get(), method_call.subchannel, - EngineTypes::KeplerCompute); + dma_pusher.BindSubchannel(&*channel_state.kepler_compute, method_call.subchannel, EngineTypes::KeplerCompute); break; case EngineID::MAXWELL_DMA_COPY_A: - dma_pusher.BindSubchannel(channel_state.maxwell_dma.get(), method_call.subchannel, - EngineTypes::MaxwellDMA); + dma_pusher.BindSubchannel(&*channel_state.maxwell_dma, method_call.subchannel, EngineTypes::MaxwellDMA); break; case EngineID::KEPLER_INLINE_TO_MEMORY_B: - dma_pusher.BindSubchannel(channel_state.kepler_memory.get(), method_call.subchannel, - EngineTypes::KeplerMemory); + dma_pusher.BindSubchannel(&*channel_state.kepler_memory, method_call.subchannel, EngineTypes::KeplerMemory); + break; + case EngineID::NV01_TIMER: + dma_pusher.BindSubchannel(&*channel_state.nv01_timer, method_call.subchannel, EngineTypes::Nv01Timer); break; default: UNIMPLEMENTED_MSG("Unimplemented engine {:04X}", engine_id); @@ -209,24 +210,22 @@ void Puller::CallEngineMethod(const MethodCall& method_call) { switch (engine) { case EngineID::FERMI_TWOD_A: - channel_state.fermi_2d->CallMethod(method_call.method, method_call.argument, - method_call.IsLastCall()); + channel_state.fermi_2d->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); break; case EngineID::MAXWELL_B: - channel_state.maxwell_3d->CallMethod(method_call.method, method_call.argument, - method_call.IsLastCall()); + channel_state.maxwell_3d->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); break; case EngineID::KEPLER_COMPUTE_B: - channel_state.kepler_compute->CallMethod(method_call.method, method_call.argument, - method_call.IsLastCall()); + channel_state.kepler_compute->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); break; case EngineID::MAXWELL_DMA_COPY_A: - channel_state.maxwell_dma->CallMethod(method_call.method, method_call.argument, - method_call.IsLastCall()); + channel_state.maxwell_dma->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); break; case EngineID::KEPLER_INLINE_TO_MEMORY_B: - channel_state.kepler_memory->CallMethod(method_call.method, method_call.argument, - method_call.IsLastCall()); + channel_state.kepler_memory->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); + break; + case EngineID::NV01_TIMER: + channel_state.nv01_timer->CallMethod(method_call.method, method_call.argument, method_call.IsLastCall()); break; default: UNIMPLEMENTED_MSG("Unimplemented engine"); @@ -255,6 +254,9 @@ void Puller::CallEngineMultiMethod(u32 method, u32 subchannel, const u32* base_s case EngineID::KEPLER_INLINE_TO_MEMORY_B: channel_state.kepler_memory->CallMultiMethod(method, base_start, amount, methods_pending); break; + case EngineID::NV01_TIMER: + channel_state.nv01_timer->CallMultiMethod(method, base_start, amount, methods_pending); + break; default: UNIMPLEMENTED_MSG("Unimplemented engine"); break; diff --git a/src/video_core/engines/puller.h b/src/video_core/engines/puller.h index d4175ee945..fe5102e3ed 100644 --- a/src/video_core/engines/puller.h +++ b/src/video_core/engines/puller.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + // SPDX-FileCopyrightText: 2022 yuzu Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later @@ -20,6 +23,7 @@ class MemoryManager; class DmaPusher; enum class EngineID { + NV01_TIMER = 0x0004, FERMI_TWOD_A = 0x902D, // 2D Engine MAXWELL_B = 0xB197, // 3D Engine KEPLER_COMPUTE_B = 0xB1C0, From e4122dae1d56a8b358c46e450b3d50ca10ffcc21 Mon Sep 17 00:00:00 2001 From: crueter Date: Fri, 6 Mar 2026 16:38:21 +0100 Subject: [PATCH 034/145] [desktop] addons: open mod folder in rc menu (#3662) also fixed the multiselection being absolutely horrendous Signed-off-by: crueter Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3662 --- .../configure_per_game_addons.cpp | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/yuzu/configuration/configure_per_game_addons.cpp b/src/yuzu/configuration/configure_per_game_addons.cpp index bdff73a040..1d2d358672 100644 --- a/src/yuzu/configuration/configure_per_game_addons.cpp +++ b/src/yuzu/configuration/configure_per_game_addons.cpp @@ -10,13 +10,14 @@ #include +#include #include #include #include +#include #include #include #include -#include #include "common/common_types.h" #include "common/fs/fs.h" @@ -42,7 +43,7 @@ ConfigurePerGameAddons::ConfigurePerGameAddons(Core::System& system_, QWidget* p item_model = new QStandardItemModel(tree_view); tree_view->setModel(item_model); tree_view->setAlternatingRowColors(true); - tree_view->setSelectionMode(QHeaderView::MultiSelection); + tree_view->setSelectionMode(QHeaderView::ExtendedSelection); tree_view->setSelectionBehavior(QHeaderView::SelectRows); tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel); tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); @@ -248,8 +249,11 @@ void ConfigurePerGameAddons::AddonDeleteRequested(QList selected) { void ConfigurePerGameAddons::showContextMenu(const QPoint& pos) { const QModelIndex index = tree_view->indexAt(pos); - auto selected = tree_view->selectionModel()->selectedIndexes(); - if (index.isValid() && selected.empty()) selected = {index}; + auto selected = tree_view->selectionModel()->selectedRows(); + if (index.isValid() && selected.empty()) { + QModelIndex idx = item_model->index(index.row(), 0); + if (idx.isValid()) selected << idx; + } if (selected.empty()) return; @@ -260,6 +264,15 @@ void ConfigurePerGameAddons::showContextMenu(const QPoint& pos) { AddonDeleteRequested(selected); }); + if (selected.length() == 1) { + auto loc = selected.at(0).data(PATCH_LOCATION).toString(); + if (QFileInfo::exists(loc)) { + QAction* open = menu.addAction(tr("&Open in File Manager")); + connect(open, &QAction::triggered, this, + [selected, loc]() { QDesktopServices::openUrl(QUrl::fromLocalFile(loc)); }); + } + } + menu.exec(tree_view->viewport()->mapToGlobal(pos)); } From c062931c9bef18afd5f0cd74329e8c3e32b4b598 Mon Sep 17 00:00:00 2001 From: lizzie Date: Fri, 6 Mar 2026 16:38:39 +0100 Subject: [PATCH 035/145] [qt] add translation table entry for debug_knobs,serial_battery and serial_unit (#3682) trivial qt change Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3682 Reviewed-by: DraVee Co-authored-by: lizzie Co-committed-by: lizzie --- src/qt_common/config/shared_translation.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/qt_common/config/shared_translation.cpp b/src/qt_common/config/shared_translation.cpp index f49c43ee2a..d1ed32134c 100644 --- a/src/qt_common/config/shared_translation.cpp +++ b/src/qt_common/config/shared_translation.cpp @@ -425,6 +425,9 @@ std::unique_ptr InitializeTranslations(QObject* parent) "their resolution, details and supported controllers and depending on this setting.\n" "Setting to Handheld can help improve performance for low end systems.")); INSERT(Settings, current_user, QString(), QString()); + INSERT(Settings, serial_unit, tr("Unit Serial"), QString()); + INSERT(Settings, serial_battery, tr("Battery Serial"), QString()); + INSERT(Settings, debug_knobs, tr("Debug knobs"), QString()); // Controls From ddac8c8eb500918bd8c89e0c330587c591206c2c Mon Sep 17 00:00:00 2001 From: xbzk Date: Fri, 6 Mar 2026 19:52:17 +0100 Subject: [PATCH 036/145] [vk] fix crash introduced in 9a07bd0570 (#3685) Fix for current crash on master. Just reverted only the necessary stuff so that PresentManager can hold a reference to khr and resist death upon application hold/restore. @Lizzie shall judge. Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3685 Co-authored-by: xbzk Co-committed-by: xbzk --- src/video_core/renderer_vulkan/renderer_vulkan.cpp | 2 +- src/video_core/renderer_vulkan/vk_present_manager.cpp | 6 +++--- src/video_core/renderer_vulkan/vk_present_manager.h | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.cpp b/src/video_core/renderer_vulkan/renderer_vulkan.cpp index cb1b1a5362..1725bc8ccc 100644 --- a/src/video_core/renderer_vulkan/renderer_vulkan.cpp +++ b/src/video_core/renderer_vulkan/renderer_vulkan.cpp @@ -137,7 +137,7 @@ try memory_allocator, scheduler, swapchain, - *surface) + surface) , blit_swapchain(device_memory, device, memory_allocator, diff --git a/src/video_core/renderer_vulkan/vk_present_manager.cpp b/src/video_core/renderer_vulkan/vk_present_manager.cpp index aa019a4160..80853362ad 100644 --- a/src/video_core/renderer_vulkan/vk_present_manager.cpp +++ b/src/video_core/renderer_vulkan/vk_present_manager.cpp @@ -101,7 +101,7 @@ PresentManager::PresentManager(const vk::Instance& instance_, MemoryAllocator& memory_allocator_, Scheduler& scheduler_, Swapchain& swapchain_, - VkSurfaceKHR_T* surface_) + vk::SurfaceKHR& surface_) : instance{instance_} , render_window{render_window_} , device{device_} @@ -291,7 +291,7 @@ void PresentManager::PresentThread(std::stop_token token) { } void PresentManager::RecreateSwapchain(Frame* frame) { - swapchain.Create(surface, frame->width, frame->height); // Pass raw pointer + swapchain.Create(*surface, frame->width, frame->height); // Pass raw pointer SetImageCount(); } @@ -310,7 +310,7 @@ void PresentManager::CopyToSwapchain(Frame* frame) { // Recreate surface and swapchain if needed. if (requires_recreation) { #ifdef ANDROID - surface = *CreateSurface(instance, render_window.GetWindowInfo()).address(); + surface = CreateSurface(instance, render_window.GetWindowInfo()); #endif RecreateSwapchain(frame); } diff --git a/src/video_core/renderer_vulkan/vk_present_manager.h b/src/video_core/renderer_vulkan/vk_present_manager.h index 3d5cc32102..c51f8ed77f 100644 --- a/src/video_core/renderer_vulkan/vk_present_manager.h +++ b/src/video_core/renderer_vulkan/vk_present_manager.h @@ -44,7 +44,7 @@ public: MemoryAllocator& memory_allocator, Scheduler& scheduler, Swapchain& swapchain, - VkSurfaceKHR_T* surface); + vk::SurfaceKHR& surface); ~PresentManager(); /// Returns the last used presentation frame @@ -78,7 +78,7 @@ private: MemoryAllocator& memory_allocator; Scheduler& scheduler; Swapchain& swapchain; - VkSurfaceKHR_T* surface; + vk::SurfaceKHR& surface; vk::CommandPool cmdpool; std::vector frames; boost::container::deque present_queue; From 11ad71b1e7db5206f074481d642020d1c30dafb1 Mon Sep 17 00:00:00 2001 From: lizzie Date: Sat, 7 Mar 2026 18:16:05 +0100 Subject: [PATCH 037/145] [docs] Obtanium, installing mods, external ES-DE config, section about CFW and settings (#3678) Signed-off-by: lizzie Reviewed-on: https://git.eden-emu.dev/eden-emu/eden/pulls/3678 Reviewed-by: DraVee Reviewed-by: CamilleLaVey Co-authored-by: lizzie Co-committed-by: lizzie --- README.md | 8 +- docs/README.md | 3 +- docs/user/AddGamesToSRM.md | 100 ---------- docs/user/CFW.md | 11 ++ docs/user/Graphics.md | 4 +- docs/user/Mods.md | 206 +++++++++++++++++++++ docs/user/README.md | 19 +- docs/user/Settings.md | 54 ++++++ docs/user/{AddEdenToSRM.md => SteamROM.md} | 129 +++++++++++-- docs/user/ThirdParty.md | 59 ++++++ 10 files changed, 473 insertions(+), 120 deletions(-) delete mode 100644 docs/user/AddGamesToSRM.md create mode 100644 docs/user/CFW.md create mode 100644 docs/user/Mods.md create mode 100644 docs/user/Settings.md rename docs/user/{AddEdenToSRM.md => SteamROM.md} (50%) diff --git a/README.md b/README.md index 3ae31151f7..44a2b4c28b 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,10 @@ See the [sign-up instructions](docs/SIGNUP.md) for information on registration. Alternatively, if you wish to add translations, go to the [Eden project on Transifex](https://app.transifex.com/edenemu/eden-emulator) and review [the translations README](./dist/languages). +## Documentation + +We have a user manual! See our [User Handbook](./docs/user/README.md). + ## Building See the [General Build Guide](docs/Build.md) @@ -69,7 +73,9 @@ For information on provided development tooling, see the [Tools directory](./too ## Download -You can download the latest releases from [here](https://github.com/eden-emulator/Releases/releases). +You can download the latest releases from [here](https://git.eden-emu.dev/eden-emu/eden/releases). + +Save us some bandwidth! We have [mirrors available](./docs/user/ThirdParty.md#mirrors) as well. ## Support diff --git a/docs/README.md b/docs/README.md index 01727ae4dc..4ea532be8e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,7 @@ # Eden Build Documentation +Are you just a casual user? Take a look at our [User Handbook](./user) then! + This contains documentation created by developers. This contains build instructions, guidelines, instructions/layouts for [cool stuff we made](./CPMUtil), and more. - **[General Build Instructions](Build.md)** @@ -11,7 +13,6 @@ This contains documentation created by developers. This contains build instructi - **[CPM - CMake Package Manager](./CPMUtil)** - **[Platform-Specific Caveats](Caveats.md)** - **[The NVIDIA SM86 (Maxwell) GPU](./NvidiaGpu.md)** -- **[User Handbook](./user)** - **[Dynarmic](./dynarmic)** - **[Cross compilation](./CrossCompile.md)** - **[Driver Bugs](./DriverBugs.md)** diff --git a/docs/user/AddGamesToSRM.md b/docs/user/AddGamesToSRM.md deleted file mode 100644 index 433999c9b6..0000000000 --- a/docs/user/AddGamesToSRM.md +++ /dev/null @@ -1,100 +0,0 @@ -# Importing Games into Steam with Steam Rom Manager - -Use this when you want to import your games inside Eden into Steam to launch with artwork from Steam Game Mode without needing to launch Eden first. - -**Click [Here](https://evilperson1337.notion.site/Importing-Games-into-Steam-with-Steam-Rom-Manager-2b757c2edaf680d7a491c92b138f1fcc) for a version of this guide with images & visual elements.** - ---- - -### Pre-Requisites - -- Steam Deck Set up and Configured -- Eden set up and Configured -- Internet Access - ---- - -## Steps - -1. Press the **STEAM** button and then go to *Power → Switch to Desktop* to enter the Desktop mode. - -1. Install ***Steam ROM Manager***, there are 2 ways you can accomplish this, either manually or through [*EmuDeck*](https://www.emudeck.com/#downloads). - - --- - - ### Manual Installation - - 1. Open the *Discover Store* and search for *Steam ROM Manager.* - 2. Select the **Install** button to install the program. - - --- - - ### Installing Through *EmuDeck* - - - - 1. Open **EmuDeck**, then navigate to *Manage Emulators.* - 2. Scroll down to the bottom of the page to the *Manage your Tools & Frontends* section. Click **Steam ROM Manager**. - - 3. Click the **Install** button on the right hand side to install it. - - --- - -2. Open the Start Menu and Launch ***Steam ROM Manager*** - -1. The program will now launch and show you a window with parsers. - - - -2. Switch off all Parsers by hitting the *Toggle Parsers* switch. -3. Scroll down the list on the left-hand side and look for a parser called *Nintendo Switch - Eden* and switch it on. This parser may not exist depending on how you installed *Steam ROM Manager* (EmuDeck creates it for you). Follow these steps to create it if it is missing. - - --- - ### Creating the Eden Parser - - 1. Select Create Parser and in the *Community Presets* option look for **Nintendo Switch - Yuzu**. - 2. Change the **Parser title** from *Nintendo Switch - Yuzu* to *Nintendo Switch - Eden.* - 3. Hit the **Browse** option under the *ROMs directory* section. Select the directory containing your Switch ROMs. - 4. Under *Steam collections*, you can add a Steam category name. This just organizes the games under a common category in your Steam Library, this is optional but recommended. - 5. Scroll down slightly to the **Executable Configuration → Executable**, select **Browse** and select the Eden AppImage. - 6. Leave everything else the same and hit **Save** to save the parser. - --- - -4. Click the Eden parser to view the options on the right, select **Test** at the bottom of the screen to ensure that *Steam ROM Manager* detects your games correctly. -1. *Steam ROM Manager* will start to scan the specified ROMs directory and match them to games. Look over the results to ensure they are accurate. If you do not see any entries - check your parsers ROMs directory field. -1. When you are happy with the results, click the **Add Games** → **Parse** to start the actual Parsing. -1. The program will now identify the games and pull artwork from [*SteamGridDB*](https://www.steamgriddb.com/). -2. Review the game matches and ensure everything is there. - - --- - - ### Correcting a Mismatch - - If the game is not identified correctly, you may need to tell *Steam ROM Manager* what the game is manually. - - 1. Hover over the game card and click the magnifying glass icon. - 2. Search for the game on the *Search SteamGridDB* section and scroll through the results, selecting the one you want. - 3. Ensure the *Name* and *Game ID* update in the **Per-App Exceptions** and press **Save and close**. The game should now update. - - --- - - ### Excluding Matches - - You may want to tell Steam ROM Manager to ignore some files (updates/DLC/etc.) that it finds in the directory. This is how you do so. - - 1. Hit the **Exclude Games** button in the bottom right. - 2. Deselect the game you want to exclude, the poster artwork should go dim and the **Number Excluded** number should increment up. Repeat with any other exclusions you want to add. - 3. Hit **Save Excludes** when you are happy with your selections. - --- -3. When you are happy with the results, select **Save to Steam** to save the results. -1. The program will now start writing the entries into the Steam Library. You should get pop up notifications of the progress, but you can monitor the progress by selecting the **Log** on the left-hand side if needed. -2. Restart Steam to have the changes take effect. Check your library to ensure that your games are there, in a category if you defined one in the parser. -3. Try to launch a game and ensure everything is working. You are now good to go. \ No newline at end of file diff --git a/docs/user/CFW.md b/docs/user/CFW.md new file mode 100644 index 0000000000..ea224d3d36 --- /dev/null +++ b/docs/user/CFW.md @@ -0,0 +1,11 @@ +# User Handbook - Custom Firmware (CFW) + +At the moment of writing, we do not support CFW such as Atmosphere, due to: + +- Lacking the required LLE emulation capabilities to properly emulate the full firmware. +- Lack of implementation on some of the key internals. +- Nobody has bothered to do it (PRs always welcome!) + +We do however, maintain HLE compatibility with the former mentioned CFW, applications that require Atmosphere to run will run fine in the emulator without any adjustments. + +If they don't run - then that's a bug! diff --git a/docs/user/Graphics.md b/docs/user/Graphics.md index e1e13a777d..ad359b9049 100644 --- a/docs/user/Graphics.md +++ b/docs/user/Graphics.md @@ -1,5 +1,7 @@ # User Handbook - Graphics +Graphical enhancements and visual quality improvments. This doesn't cover texture mods. + ## Visual Enhancements ### Anti-aliasing @@ -89,7 +91,7 @@ The OpenGL backend would invoke behaviour that would result in swarst/LLVMpipe w ### HaikuOS compatibility -HaikuOS bundles a Mesa library that doesn't support full core OpenGL 4.6 (required by the emulator). This leads to HaikuOS being one of the few computer platforms where Vulkan is the only available option for users. If OpenGL is desired, Mesa has to be built manually from source. For debugging purpouses `lavapipe` is recommended over the GPU driver; there is in-kernel support for NVIDIA cards through. +HaikuOS bundles a Mesa library that doesn't support full core OpenGL 4.6 (required by the emulator). This leads to HaikuOS being one of the few computer platforms where Vulkan is the only available option for users. If OpenGL is desired, Mesa has to be built manually from source. For debugging purposes `lavapipe` is recommended over the GPU driver; there is in-kernel support for NVIDIA cards through. ### Fixes for Windows 10 and above having "Device loss" diff --git a/docs/user/Mods.md b/docs/user/Mods.md new file mode 100644 index 0000000000..11361d628c --- /dev/null +++ b/docs/user/Mods.md @@ -0,0 +1,206 @@ +# User Handbook - Installing Mods + +## General Notes + +**Note:** When installing a mod, always read the mod's installation instructions. + +This is especially important if a mod uses a framework such as **ARCropolis**, **Skyline**, or **Atmosphere plugins**. In those cases, follow the framework's instructions instead of using Eden's normal mod folder. + +For example, **Super Smash Bros. Ultimate** uses such a framework. See the related section below for details. + +--- + +# Installing Mods for Most Games + +1. Right click a game in the game list. +2. Click **"Open Mod Data Location"**. +3. Extract the mod into that folder. + +Each mod should be placed inside **its own subfolder**. + +--- + +# Enabling or Disabling Mods + +1. Right click the game in the game list. +2. Click **Configure Game**. +3. In the **Add-Ons** tab, enable or disable mods, updates, and DLC by ticking or unticking their boxes. + +--- + +# Important Note About SD Card Paths + +Some mods are designed for real Nintendo Switch consoles and refer to the **SD card root**. + +The emulated SD card is located at: + +``` +%AppData%\eden\sdmc +``` + +Example: + +``` +Switch instruction: sd:/ultimate/mods +Eden equivalent: sdmc/ultimate/mods +``` + +--- + +# Framework-Based Mods (Super Smash Bros. Ultimate) + +Some games require external mod frameworks instead of the built-in mod loader. + +The most common example is **Super Smash Bros. Ultimate**. + +These mods are installed directly to the **emulated SD card**, not the normal Eden mod folder. + +--- + +# Installing the ARCropolis Modding Framework + +**Note:** Some mod packs bundle ARCropolis with their installer (for example, Smash Ult-S). + +--- + +## 1. Download ARCropolis + +Download the latest release: + +https://github.com/Raytwo/ARCropolis/releases/ + +--- + +## 2. Install ARCropolis + +Extract the **`atmosphere`** folder into: + +``` +%AppData%\eden\sdmc +``` + +This is the **emulated SD card directory**. + +Verify installation by checking that the following file exists: + +``` +sdmc\atmosphere\contents\01006A800016E000\romfs\skyline\plugins\libarcropolis.nro +``` + +--- + +## 3. Download Skyline + +Download the latest Skyline release: + +https://github.com/skyline-dev/skyline/releases + +Skyline used to be bundled with ARCropolis but is now distributed separately to avoid compatibility issues caused by outdated bundled versions. + +--- + +## 4. Install Skyline + +Extract the **`exefs`** folder into: + +``` +sdmc\atmosphere\contents\01006A800016E000 +``` + +The `exefs` folder should be **next to the `romfs` folder**. + +Verify installation by checking that the following file exists: + +``` +%AppData%\eden\sdmc\atmosphere\contents\01006A800016E000\exefs\subsdk9 +``` + +--- + +## 5. Launch the Game Once + +Start the game and make sure you see the **ARCropolis version text on the title screen**. + +This will also create the folders required for installing mods. + +--- + +## 6. Install Smash Ultimate Mods + +Install mods inside: + +``` +sdmc\ultimate\mods +``` + +Each mod must be placed inside **its own subfolder**. + +Example: + +``` +sdmc\ultimate\mods\ExampleMod +``` + +--- + +# Troubleshooting + +## ARCropolis text does not appear on startup + +Check the following: + +- `libarcropolis.nro` exists in: + +``` +sdmc\atmosphere\contents\01006A800016E000\romfs\skyline\plugins +``` + +- `subsdk9` exists in: + +``` +sdmc\atmosphere\contents\01006A800016E000\exefs +``` + +- Files were extracted to: + +``` +%AppData%\eden\sdmc +``` + +--- + +## Mods are not loading + +Make sure mods are installed inside: + +``` +sdmc\ultimate\mods +``` + +Each mod must have its **own subfolder**. + +Correct example: + +``` +sdmc\ultimate\mods\ExampleMod +``` + +Incorrect example: + +``` +sdmc\ultimate\mods\ExampleMod\ExampleMod +``` + +--- + +## Installing mods in the wrong folder + +ARCropolis mods **do not go in Eden's normal mod folder**. + +Do **not** install Smash mods here: + +``` +user\load\01006A800016E000 +``` + +That folder is only used for traditional **RomFS mods**, not ARCropolis. diff --git a/docs/user/README.md b/docs/user/README.md index 5fd3a17e51..9804f4d62f 100644 --- a/docs/user/README.md +++ b/docs/user/README.md @@ -4,10 +4,14 @@ The "FAQ". This handbook is primarily aimed at the end-user - baking useful knowledge for enhancing their emulation experience. +A copy of this handbook is [available online](https://git.eden-emu.dev/eden-emu/eden/src/branch/master/docs/user/README.md). + ## Basics - **[The Basics](Basics.md)** - **[Quickstart](./QuickStart.md)** +- **[Settings](./Settings.md)** +- **[Installing Mods](./Mods.md)** - **[Run On macOS](./RunOnMacOS.md)** - **[Audio](Audio.md)** - **[Graphics](Graphics.md)** @@ -17,22 +21,29 @@ This handbook is primarily aimed at the end-user - baking useful knowledge for e - **[Using Amiibo](./UsingAmiibo.md)** - **[Using Cheats](./UsingCheats.md)** - **[Importing Saves](./ImportingSaves.md)** -- **[Add Eden to Steam ROM Manager](./AddEdenToSRM.md)** -- **[Add Games to Steam ROM Manager](./AddGamesToSRM.md)** - **[Installing Atmosphere Mods](./InstallingAtmosphereMods.md)** - **[Installing Updates & DLCs](./InstallingUpdatesDLC.md)** - **[Controller Profiles](./ControllerProfiles.md)** - **[Alter Date & Time](./AlterDateTime.md)** +## 3rd-party Integration + +- **[Configuring Steam ROM Manager](./SteamROM.md)** +- **[Server hosting](ServerHosting.md)** +- **[Syncthing Guide](./SyncthingGuide.md)** +- **[Third Party](./ThirdParty.md)** + - **[Obtainium](./ThirdParty.md#configuring-obtainium)** + - **[ES-DE](./ThirdParty.md#configuring-es-de)** + - **[Mirrors](./ThirdParty.md#mirrors)** + ## Advanced +- **[Custom Firmware](./CFW.md)** - **[How To Access Logs](./HowToAccessLogs.md)** - **[Gyro Controls](./GyroControls.md)** - **[Platforms and Architectures](Architectures.md)** -- **[Server hosting](ServerHosting.md)** - **[Command Line](CommandLine.md)** - **[Native Application Development](Native.md)** - **[Adding Boolean Settings Toggles](AddingBooleanToggles.md)** - **[Adding Debug Knobs](./AddingDebugKnobs.md)** -- **[Syncthing Guide](./SyncthingGuide.md)** - **[Testing](Testing.md)** diff --git a/docs/user/Settings.md b/docs/user/Settings.md new file mode 100644 index 0000000000..35fcd0c9ef --- /dev/null +++ b/docs/user/Settings.md @@ -0,0 +1,54 @@ +# User Handbook - Settings + +As the emulator continues to grow, so does the number of settings that come and go. + +Most of the development adds new settings that enhance performance/compatibility, only to be removed later in newer versions due to newfound discoveries or because they were "a hacky workaround". + +As such, this guide will NOT mention those kind of settings, we'd rather mention settings which have a long shelf time (i.e won't get removed in future releases) and are likely to be unchanged. + +Some of the options are self explainatory, and they do exactly what they say they do (i.e "Pause when not in focus"); such options will be also skipped due to triviality. + +## Foreword + +Before touching the settings, please see the game boots with stock options. We try our best to ensure users can boot any game using the default settings. If they don't work, then you may try fiddling with options - but please, first use stock options. + +## General + +- `General/Force X11 as Graphics Backend`: Wayland on *NIX has prominent issues that are unlikely to be resolved; the kind that are "not our fault, it's Wayland issue", this "temporary" hack forces X11 as the backend, regardless of the desktop manager's default. +- `General/Enable Gamemode`: This only does anything when you have Feral Interactive's Gamemode library installed somewhere, if you do, this will help boost FPS by telling the OS to explicitly prioritize *this* application for "gaming" - only for *NIX systems. +- `Hotkeys`: Deceptively to remove a hotkey you must right click and a menu will appear to remove that specific hotkey. +- `UI/Language`: Changes language *of the interface* NOT the emulated program! +- `Debug/Enable Auto Stub`: May help to "fix" some games by just lying and saying that everything they do returns "success" instead of outright crashing for any function/service that is NOT implemented. +- `Debug/Show log in console`: Does as said, note that the program may need to be reopened (Windows) for changes to take effect. +- `Debug/Flush log output`: Classically, every write to the log is "buffered", that is, changes aren't written to the disk UNTIL the program has decided it is time to write, until then it keeps data in a buffer which resides on RAM. If the program crashes, the OS will automatically discard said buffer (any RAM associated with a dead process is automatically discarded/reused for some other purpose); this means critical data may not be logged to the disk on time, which may lead to missing log lines. Use this if you're wanting to remove that factor when debugging, sometimes a hard crash may "eat" some of the log lines IF this option isn't enabled. +- `Debug/Disable Macro HLE:` The emulator has HLE emulation of macro programs for Maxwell, this means that some details are purpousefully skipped; this option forces all macro programs to be ran without skipping anything. + +## System + +- `System/RNG Seed`: Set to 0 (and uncheck) to disable ASLR systemwide (this makes mods like CTGP to stop working); by default it enables ASLR to replicate console behaviour. +- `Network/Enable Airplane Mode`: Enable this if a game is crashing before loading AND the logs mention anything related to "web" or "internet" services. + +## CPU + +- `CPU/Virtual table bouncing`: Some games have the tendency to crash on loading due to an indirect bad jump (Pokemon ZA being the worst offender); this option lies to the game and tells it to just pretend it never executed a given function. This is fine for most casual users, but developers of switch applications **must** disable this. This temporary "hack" should hopefully be gone in 6-7 months from now on. +- `Fastmem`, aka. `CPU/Enable Host MMU`: Enables "fastmem"; a detailed description of fastmem can be found [here](../dynarmic/Design.md#fast-memory-fastmem). +- `CPU/Unsafe FMA`: Enables deliberate innacurate FMA behaviour which may affect how FMA returns any given operation - this may introduce tiny floating point errors which can cascade in sensitive code (i.e FFmpeg). +- `CPU/Faster FRSQRTE and FRECPE`: Introduces accuracy errors on square root and reciprocals in exchange for less checks - this introduces inaccuracies with some cases but it's mostly safe. +- `CPU/Faster ASIMD Instructions`: Skips rounding mode checks for ARM ASIMD instructions - this means some code dpeending on these rounding modes may misbehave. +- `CPU/Disable address space checks`: Before each memory access, the emulator checks the address is in range, if not it faults; this option makes it so the emulator skips the check entirely (which may be expensive for a myriad of reasons). However at the same time this allows the guest program to "break out" of the emulation context by writing to arbitrary addresses. +- `CPU/Ignore global monitor`: This relies on a quirk present on x86 to avoid the ARM global monitor emulation, this may increase performance in mutex-heavy contexts (i.e games waiting for next frames or such); but also can cause deadlocks and fun to debug issues. + +It is important to note the majority of precision-reducing instructions do not benefit cases where they are not used, which means the performance gains will vary per game. + +# Graphics + +See also [an extended breakdown of some options](./Graphics.md). + +- `Extras/Extended Dynamic State` and `Extras/Vertex Input Dynamic State`: These Vulkan extensions essentially allow you to reuse the same pipeline but just change the state between calls (so called "dynamic state"); the "extended" levels signifies how much state can be placed on this "dynamic" range, for example the amount of depth culling to use can be placed on the dynamic state, avoiding costly reloads and flushes. While this by itself is a fine option, SOME vendors (notably PowerVR and Mali) have problems with anything related to EDS3. EDS3 contains EDS2, and EDS2 contains EDS1. Essentially this means more extended data the driver has to keep track of, at the benefit of avoiding costly flushes. +- `Advanced/Use persistent cache`: This saves compiled shaders onto the disk, independent of any driver's own disk saved shaders (yes, some drivers, notably NVIDIA, save a secondary shader cache onto disk) - disable this only if you're debugging or working on the GPU backend. This option is meant to massively help to reduce shader stutters (after playing for one session that compiles them). +- `Advanced/Use Vulkan pipeline cache`: This is NOT the same as `Use persistent cache`; it's a separate flag that tells the Vulkan backend to create pipeline caches, which are a detail that can be used to massively improve performance and remove pipeline creation overhead. This is a Vulkan feature. + +## Controls + +Most of the controls should work out of the box. If not, please use a joystick calibrator to ensure it's not an issue with your own controller, for example: +- https://github.com/dkosmari/calibrate-joystick diff --git a/docs/user/AddEdenToSRM.md b/docs/user/SteamROM.md similarity index 50% rename from docs/user/AddEdenToSRM.md rename to docs/user/SteamROM.md index 4658bcf7e0..a782b51969 100644 --- a/docs/user/AddEdenToSRM.md +++ b/docs/user/SteamROM.md @@ -1,4 +1,6 @@ -# Importing Eden into Steam with Steam Rom Manager +# User Handbook - Configuring Steam ROM Manager + +## Importing Eden into Steam with Steam Rom Manager Use this when you want to import the Eden AppImage into your Steam Library along with artwork using *Steam ROM Manager.* @@ -6,7 +8,7 @@ Use this when you want to import the Eden AppImage into your Steam Library along --- -### Pre-Requisites +#### Pre-Requisites - Eden set up and configured - Internet Connection @@ -14,9 +16,9 @@ Use this when you want to import the Eden AppImage into your Steam Library along --- -## Steps +### Steps -### Initial Setup +#### Initial Setup 1. Press the **STEAM** button and then go to *Power → Switch to Desktop* to enter the Desktop mode. @@ -24,14 +26,14 @@ Use this when you want to import the Eden AppImage into your Steam Library along --- - ### Manual Installation + #### Manual Installation 1. Open the *Discover Store* and search for *Steam ROM Manager.* 2. Select the **Install** button to install the program. --- - ### Installing Through *EmuDeck* + #### Installing Through *EmuDeck*