From 74ae2c650dd6d59f4dbd999636e7c74b478a29d8 Mon Sep 17 00:00:00 2001 From: FakeMichau <49685661+FakeMichau@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:36:45 +0100 Subject: [PATCH] Let asi plugins register custom providers FFX VK for custom upscaling and custom FG Interops for custom upscalers --- OptiScaler.ini | 20 +- OptiScaler/Config.cpp | 66 +-- OptiScaler/Config.h | 7 +- OptiScaler/State.h | 2 + OptiScaler/dllmain.cpp | 6 +- OptiScaler/framegen/ffx/FSRFG_Dx12.cpp | 27 +- OptiScaler/framegen/ffx/FSRFG_Dx12.h | 3 + OptiScaler/framegen/ffx/FSRFG_Vk.cpp | 15 +- OptiScaler/framegen/ffx/FSRFG_Vk.h | 3 + OptiScaler/framegen/nvngx/Nvngx_Custom.cpp | 5 +- OptiScaler/framegen/nvngx/Nvngx_Custom.h | 3 +- OptiScaler/framegen/nvngx/Nvngx_FFX.cpp | 6 +- OptiScaler/hooks/FG_Hooks.cpp | 2 +- OptiScaler/hooks/Vulkan_Hooks.cpp | 2 +- OptiScaler/menu/menu_common.cpp | 149 +++---- OptiScaler/misc/CustomProviders.h | 380 ++++++++++++------ OptiScaler/plugins/PluginApi.cpp | 13 + OptiScaler/proxies/FfxApi_Proxy.h | 123 ++++-- OptiScaler/proxies/Nvngx_Proxy.h | 109 +++-- OptiScaler/proxies/Nvngx_RRDllProxy.cpp | 7 +- OptiScaler/upscalers/FeatureProvider_Dx11.cpp | 12 +- OptiScaler/upscalers/FeatureProvider_Dx12.cpp | 8 +- OptiScaler/upscalers/FeatureProvider_Vk.cpp | 16 +- .../upscalers/dlss/DLSSFeature_Dx11On12.cpp | 5 +- .../upscalers/dlss/DLSSFeature_Dx11On12.h | 4 +- .../upscalers/dlss/DLSSFeature_Dx12.cpp | 4 +- OptiScaler/upscalers/dlss/DLSSFeature_Vk.cpp | 80 +++- OptiScaler/upscalers/dlss/DLSSFeature_Vk.h | 10 +- .../upscalers/ffx/FFXFeature_Dx11On12.cpp | 5 +- .../upscalers/ffx/FFXFeature_Dx11On12.h | 4 +- .../upscalers/ffx/FFXFeature_VkOn12.cpp | 5 +- OptiScaler/upscalers/ffx/FFXFeature_VkOn12.h | 4 +- OptiScaler/upscalers/nvngx/Nvngx_RR.cpp | 4 +- OptiScaler/upscalers/nvngx/Nvngx_RR.h | 5 +- plugin_sdk/README.md | 28 +- plugin_sdk/optiscaler_plugin.h | 30 +- plugin_sdk/sample/SamplePlugin.cpp | 69 ++++ 37 files changed, 846 insertions(+), 395 deletions(-) diff --git a/OptiScaler.ini b/OptiScaler.ini index 880bc287..e8a75409 100644 --- a/OptiScaler.ini +++ b/OptiScaler.ini @@ -3,25 +3,24 @@ ; ------------------------------------------------------- ; Select Upscaler for Dx11 games ; fsr22 (native DX11), fsr31 (native DX11), xess (native DX11, Arc only), xess_12 (dx11on12), fsr21_12 (dx11on12), fsr22_12 (dx11on12), ffx_12 (FSR 2.3; 3.1; 4.x), dlss - Default (auto) is fsr22 +; or the name of a custom upscaler with 'ffx' or 'dlss', run through dx11on12 Dx11Upscaler=auto ; Select Upscaler for Dx12 games ; xess, fsr21, fsr22, ffx (FSR 2.3; 3.1; 4.x), dlss -; or the name of a folder in the 'custom' folder +; or the name of a custom upscaler: a folder in the 'custom' folder or one registered by an ASI plugin ; Default (auto) is DLSS when capable gpu, FSR4 when capable gpu, XeSS otherwise Dx12Upscaler=auto ; Select Upscaler for Vulkan games ; fsr21 (native VK), fsr22 (native VK), ffx (native FSR 2.3; 3.1), xess (native VK), fsr21_12 (VKon12), ffx_12 (FSR 2.3; 3.1; 4.x), dlss - Default (auto) is fsr22 -; or the name of a folder in the 'custom' folder +; or the name of a custom upscaler with 'ffx_vk', 'ffx' (VKon12) or 'dlss', the first one it has is used VulkanUpscaler=auto ; DLSSD for the game's ray reconstruction (DX12 and Vulkan, DLSS inputs only) -; dlssd or the name of a folder in the 'custom' folder with a dlssd folder (an nvngx_dlssd replacement) -; or a regular upscaler: xess, fsr21, fsr22, ffx, dlss (needs RRAllowRegularUpscalers) - these don't denoise, -; ray traced effects stay noisy -; Ray reconstruction is reported as available with a DLSSD capable gpu, with a custom one that runs, -; or with a regular upscaler picked here +; dlssd, a custom one (a 'custom' subfolder with a dlssd folder, or one added by an ASI plugin) +; or a regular upscaler: xess, fsr21, fsr22, ffx, dlss (needs RRAllowRegularUpscalers, no denoising) +; The game's ray reconstruction option shows up when any of these can run ; Default (auto) is NVIDIA's DLSSD when the gpu can run it, the first custom one otherwise RRUpscaler=auto @@ -66,7 +65,7 @@ FGOutput=auto ; Arturs - requires dlss-enabler-headless.dll, FSR 3 MFG ; FFX - requires amd_fidelityfx_dx12.dll OR amd_fidelityfx_loader_dx12.dll + amd_fidelityfx_framegeneration_dx12.dll, FSRFG 3 or 4 ; Combo - requires the same as FFX AND Arturs, uses FFX for middle frames and Enabler for the rest. Allow for combining FSR 4 FG and Enabler in 4x and 6x modes -; Or the name of a folder in the 'custom' folder that has a 'dlssg' folder with an nvngx_dlssg replacement dll +; Or the name of a custom FG with 'dlssg', an nvngx_dlssg replacement ; None, Nukems, Arturs, FFX, Combo - Default (auto) is Nukems FGNvngxReplacement=auto @@ -192,6 +191,11 @@ UseMutexForSwapchain=auto ; true or false - Default (auto) is false DisableFlipMetering=auto +; FFX frame generation and swapchain used by FSR FG +; The name of a custom FG with 'ffx_fg' (DX11/12) or 'ffx_fg_vk' (Vulkan), a folder in the 'custom' folder +; or one registered by an ASI plugin - Default (auto) is the regular FFX one +Provider=auto + ; Frame Pace Tuning ; ------------------------------------------------------- ; Enables custom Frame Pace Tuning parameters diff --git a/OptiScaler/Config.cpp b/OptiScaler/Config.cpp index 921acb6c..4432d7a8 100644 --- a/OptiScaler/Config.cpp +++ b/OptiScaler/Config.cpp @@ -62,27 +62,25 @@ bool Config::Reload(std::filesystem::path iniPath) // Upscalers { - // transform converts only when optional has a value - Dx11Upscaler.set_from_config(readString("Upscalers", "Dx11Upscaler", true).transform(CodeToUpscaler)); - auto dx12Upscaler = readString("Upscalers", "Dx12Upscaler", true).transform(CodeToUpscalerFfx); + // Any value other than an upscaler is the name of a custom upscaler, the upscaler it runs as is set by + // CustomProviders::ResolveUpscaler once the Opti folder is known + auto readUpscaler = [&](const char* key, auto codeToUpscaler, auto& upscaler, auto& custom) + { + // transform converts only when optional has a value + auto value = readString("Upscalers", key, true).transform(codeToUpscaler); - // Any other value is the folder name of a custom upscaler, its kind is set by - // CustomProviders::ResolveDx12Upscaler once the Opti folder is known - if (dx12Upscaler == Upscaler::Reset) - CustomUpscaler.set_from_config(std::string(ini.GetValue("Upscalers", "Dx12Upscaler"))); - else - Dx12Upscaler.set_from_config(dx12Upscaler); + if (value == Upscaler::Reset) + custom.set_from_config(std::string(ini.GetValue("Upscalers", key))); + else + upscaler.set_from_config(value); + }; - // Same for Vulkan, checked by CustomProviders::ResolveVulkanUpscaler - auto vulkanUpscaler = readString("Upscalers", "VulkanUpscaler", true).transform(CodeToUpscalerFfx); + readUpscaler("Dx11Upscaler", CodeToUpscaler, Dx11Upscaler, CustomUpscalerDx11); + readUpscaler("Dx12Upscaler", CodeToUpscalerFfx, Dx12Upscaler, CustomUpscaler); + readUpscaler("VulkanUpscaler", CodeToUpscalerFfx, VulkanUpscaler, CustomUpscalerVk); - if (vulkanUpscaler == Upscaler::Reset) - CustomUpscalerVk.set_from_config(std::string(ini.GetValue("Upscalers", "VulkanUpscaler"))); - else - VulkanUpscaler.set_from_config(vulkanUpscaler); - - // A regular upscaler or a folder name for ray reconstruction, dlssd is the same as auto, folders are - // checked by CustomProviders::ResolveRRUpscaler + // A regular upscaler or a custom name for ray reconstruction, dlssd is the same as auto, custom names + // are checked by CustomProviders::ResolveAll if (auto rrUpscaler = readString("Upscalers", "RRUpscaler", true); rrUpscaler.value_or("dlssd") != "dlssd") { if (auto upscaler = CodeToUpscalerFfx(rrUpscaler.value()); IsRRRegularUpscaler(upscaler)) @@ -178,6 +176,7 @@ bool Config::Reload(std::filesystem::path iniPath) FGFPTAllowWaitForSingleObjectOnFence.set_from_config(readBool("FSRFG", "FPTWaitForSingleObjectOnFence")); FSRFGEnableWatermark.set_from_config(readBool("FSRFG", "EnableWatermark")); FSRFGDisableFlipMetering.set_from_config(readBool("FSRFG", "DisableFlipMetering")); + FSRFGProvider.set_from_config(readString("FSRFG", "Provider")); } // OptiFG @@ -1338,27 +1337,29 @@ bool Config::SaveIni() // Upscalers { - auto SaveUpscaler = [&](const char* key, auto& upscalerSetting) + // A custom name is saved in place of the upscaler it runs as + auto SaveUpscaler = [&](const char* key, auto& upscalerSetting, auto& customSetting) { - std::string value = upscalerSetting.value_for_config() + auto upscaler = upscalerSetting.value_for_config(); + auto custom = customSetting.value_or(""); + + if (!custom.empty() && (upscaler == Upscaler::FFX || upscaler == Upscaler::FFX_on12 || + upscaler == Upscaler::DLSS || upscaler == Upscaler::DLSS_on12)) + { + ini.SetValue("Upscalers", key, custom.c_str()); + return; + } + + std::string value = upscaler .transform(UpscalerToCode) // Turn enum into string .value_or("auto"); ini.SetValue("Upscalers", key, value.c_str()); }; - SaveUpscaler("Dx11Upscaler", Instance()->Dx11Upscaler); - if (auto custom = Instance()->CustomUpscaler.value_or(""); - !custom.empty() && (Instance()->Dx12Upscaler.value_for_config() == Upscaler::FFX || - Instance()->Dx12Upscaler.value_for_config() == Upscaler::DLSS)) - ini.SetValue("Upscalers", "Dx12Upscaler", custom.c_str()); - else - SaveUpscaler("Dx12Upscaler", Instance()->Dx12Upscaler); - if (auto custom = Instance()->CustomUpscalerVk.value_or(""); - !custom.empty() && Instance()->VulkanUpscaler.value_for_config() == Upscaler::FFX) - ini.SetValue("Upscalers", "VulkanUpscaler", custom.c_str()); - else - SaveUpscaler("VulkanUpscaler", Instance()->VulkanUpscaler); + SaveUpscaler("Dx11Upscaler", Instance()->Dx11Upscaler, Instance()->CustomUpscalerDx11); + SaveUpscaler("Dx12Upscaler", Instance()->Dx12Upscaler, Instance()->CustomUpscaler); + SaveUpscaler("VulkanUpscaler", Instance()->VulkanUpscaler, Instance()->CustomUpscalerVk); if (auto regular = Instance()->RRRegularUpscaler.value_for_config(); regular.has_value()) ini.SetValue("Upscalers", "RRUpscaler", UpscalerToCode(regular.value()).c_str()); @@ -1462,6 +1463,7 @@ bool Config::SaveIni() GetBoolValue(Instance()->FSRFGEnableWatermark.value_for_config()).c_str()); ini.SetValue("FSRFG", "DisableFlipMetering", GetBoolValue(Instance()->FSRFGDisableFlipMetering.value_for_config()).c_str()); + ini.SetValue("FSRFG", "Provider", Instance()->FSRFGProvider.value_for_config().value_or("auto").c_str()); } // XeFG output diff --git a/OptiScaler/Config.h b/OptiScaler/Config.h index 1a9dc8c8..61c4c738 100644 --- a/OptiScaler/Config.h +++ b/OptiScaler/Config.h @@ -545,9 +545,10 @@ class Config // FSR CustomOptional FsrDebugView { false }; CustomOptional FfxUpscalerIndex { 0 }; - // Folder name in custom used by FFX or DLSS, stored in Dx12Upscaler, empty for the regular upscalers + // Custom upscaler name (misc/CustomProviders.h) of each API, stored in the API's upscaler setting in place of + // the upscaler it runs as, empty for the regular upscalers + CustomOptional CustomUpscalerDx11; CustomOptional CustomUpscaler; - // Folder name in custom used by Vulkan FFX, stored in VulkanUpscaler, empty for the regular upscalers CustomOptional CustomUpscalerVk; // Folder in custom with a dlssd for the game's ray reconstruction, RRUpscaler in the ini, empty for auto CustomOptional CustomRRUpscaler; @@ -721,6 +722,8 @@ class Config CustomOptional FSRFGSkipConfigForHudless { false }; CustomOptional FSRFGSkipDispatchForHudless { false }; CustomOptional FSRFGEnableWatermark { false }; + // Custom FFX FG name (misc/CustomProviders.h) used by FSR FG, empty for the regular one + CustomOptional FSRFGProvider; // XeFG CustomOptional FGXeFGIgnoreInitChecks { false }; diff --git a/OptiScaler/State.h b/OptiScaler/State.h index ce693a28..9e86d393 100644 --- a/OptiScaler/State.h +++ b/OptiScaler/State.h @@ -214,6 +214,8 @@ class State FGNvngxReplacement activeFgNvngx = FGNvngxReplacement::None; std::string fgNvngxCustom; std::string activeFgNvngxCustom; + // Config::FSRFGProvider FSR FG was started with, applied after a restart + std::string activeFsrFgProvider; // Streamline FG inputs Sl_Inputs slFGInputs = {}; diff --git a/OptiScaler/dllmain.cpp b/OptiScaler/dllmain.cpp index 8290d1bc..96679925 100644 --- a/OptiScaler/dllmain.cpp +++ b/OptiScaler/dllmain.cpp @@ -1764,10 +1764,7 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserv spdlog::info(""); spdlog::info("LogLevel: {}", Config::Instance()->LogLevel.value_or_default()); - CustomProviders::ResolveDx12Upscaler(); - CustomProviders::ResolveVulkanUpscaler(); - CustomProviders::ResolveFGNvngx(); - CustomProviders::ResolveRRUpscaler(); + CustomProviders::ResolveAll(); spdlog::info(""); if (Util::GetRealWindowsVersion(winVer)) @@ -1798,6 +1795,7 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserv State::Instance().activeFgOutput = Config::Instance()->FGOutput.value_or_default(); State::Instance().activeFgNvngx = Config::Instance()->FGNvngxReplacement.value_or_default(); State::Instance().activeFgNvngxCustom = State::Instance().fgNvngxCustom; + State::Instance().activeFsrFgProvider = Config::Instance()->FSRFGProvider.value_or(""); // Ensure valid FG configuration if (State::Instance().activeFgOutput == FGOutput::NoFG && State::Instance().activeFgInput != FGInput::NoFG && diff --git a/OptiScaler/framegen/ffx/FSRFG_Dx12.cpp b/OptiScaler/framegen/ffx/FSRFG_Dx12.cpp index b47916da..b2bbfcbc 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Dx12.cpp +++ b/OptiScaler/framegen/ffx/FSRFG_Dx12.cpp @@ -304,7 +304,8 @@ void FSRFG_Dx12::ConfigureFramePaceTuning() feature_version FSRFG_Dx12::Version() { - if (_fgContext == nullptr && _version.major == 0) + // A custom FG's version is known once its context is made + if (_fgContext == nullptr && _version.major == 0 && _custom == nullptr) { if (!FfxApiProxy::IsFGReady()) FfxApiProxy::InitFfxDx12(); @@ -1148,7 +1149,11 @@ bool FSRFG_Dx12::CreateSwapchainInternal(IDXGIFactory* factory, ID3D12CommandQue createSwapChainDesc.header.pNext = &versionDesc.header; - auto result = FfxApiProxy::D3D12_CreateContext(&_swapChainContext, &createSwapChainDesc.header, nullptr); + // A custom FG makes its own swapchain + auto result = _custom != nullptr + ? FfxApiProxy::D3D12_CreateContext(&_custom->module, &_swapChainContext, + &createSwapChainDesc.header, nullptr) + : FfxApiProxy::D3D12_CreateContext(&_swapChainContext, &createSwapChainDesc.header, nullptr); if (result == FFX_API_RETURN_OK) { @@ -1192,7 +1197,11 @@ bool FSRFG_Dx12::CreateSwapchain1Internal(IDXGIFactory* factory, ID3D12CommandQu createSwapChainDesc.header.pNext = &versionDesc.header; - auto result = FfxApiProxy::D3D12_CreateContext(&_swapChainContext, &createSwapChainDesc.header, nullptr); + // A custom FG makes its own swapchain + auto result = _custom != nullptr + ? FfxApiProxy::D3D12_CreateContext(&_custom->module, &_swapChainContext, + &createSwapChainDesc.header, nullptr) + : FfxApiProxy::D3D12_CreateContext(&_swapChainContext, &createSwapChainDesc.header, nullptr); if (result == FFX_API_RETURN_OK) { @@ -1298,7 +1307,8 @@ void FSRFG_Dx12::CreateContext(ID3D12Device* device, FG_Constants& fgConstants) return; } - FfxApiProxy::D3D12_QueryFgVersions(device, State::Instance().ffxFGVersionIds, State::Instance().ffxFGVersionNames); + FfxApiProxy::D3D12_QueryFgVersions(device, State::Instance().ffxFGVersionIds, State::Instance().ffxFGVersionNames, + _custom != nullptr ? &_custom->module : nullptr); if (State::Instance().ffxFGVersionIds.empty()) { @@ -1416,7 +1426,10 @@ void FSRFG_Dx12::CreateContext(ID3D12Device* device, FG_Constants& fgConstants) ScopedSkipSpoofingGlobal skipSpoofingGlobal {}; ScopedSkipHeapCapture skipHeapCapture {}; - ffxReturnCode_t retCode = FfxApiProxy::D3D12_CreateContext(&_fgContext, &createFg.header, nullptr); + ffxReturnCode_t retCode = + _custom != nullptr + ? FfxApiProxy::D3D12_CreateContext(&_custom->module, &_fgContext, &createFg.header, nullptr) + : FfxApiProxy::D3D12_CreateContext(&_fgContext, &createFg.header, nullptr); LOG_INFO("D3D12_CreateContext result: {:X}", retCode); _isActive = (retCode == FFX_API_RETURN_OK); @@ -1523,11 +1536,11 @@ void FSRFG_Dx12::EvaluateState(ID3D12Device* device, FG_Constants& fgConstants) _constants = fgConstants; - if (!FfxApiProxy::IsFGReady()) + if (!FfxApiProxy::IsFsrFgReady()) FfxApiProxy::InitFfxDx12(); // If needed hooks are missing or XeFG proxy is not inited or FG swapchain is not created - if (!FfxApiProxy::IsFGReady() || State::Instance().currentFGSwapchain == nullptr) + if (!FfxApiProxy::IsFsrFgReady() || State::Instance().currentFGSwapchain == nullptr) return; if (State::Instance().isShuttingDown) diff --git a/OptiScaler/framegen/ffx/FSRFG_Dx12.h b/OptiScaler/framegen/ffx/FSRFG_Dx12.h index c53d2c0a..53895fdd 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Dx12.h +++ b/OptiScaler/framegen/ffx/FSRFG_Dx12.h @@ -18,6 +18,9 @@ class FSRFG_Dx12 : public virtual IFGFeature_Dx12 FfxApiSurfaceFormat _usingHudlessFormat = FFX_API_SURFACE_FORMAT_UNKNOWN; feature_version _version { 0, 0, 0 }; + // Custom FG and swapchain provider, nullptr for the regular FFX one + CustomFfxModule* _custom = FfxApiProxy::ActiveCustomFgDx12(); + bool _linkedHudlesDesc = false; uint32_t _maxRenderWidth = 0; diff --git a/OptiScaler/framegen/ffx/FSRFG_Vk.cpp b/OptiScaler/framegen/ffx/FSRFG_Vk.cpp index b13c398c..ff133fba 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Vk.cpp +++ b/OptiScaler/framegen/ffx/FSRFG_Vk.cpp @@ -244,9 +244,9 @@ bool FSRFG_Vk::CreateSwapchain(VkDevice device, const VkSwapchainCreateInfoKHR* _driverFgRejected = false; // ML FG only works with the swapchain of the same module, the version can't be switched without recreating it - _ffxSwapchain = FfxApiProxy::VkFfxModule_FG(); + _ffxSwapchain = _custom != nullptr ? &_custom->module : FfxApiProxy::VkFfxModule_FG(); - if (IsDriverVersionSelected()) + if (_custom == nullptr && IsDriverVersionSelected()) { if (FSR4DriverProviderVk::IsFgSupported(device, _physicalDevice, &VulkanHooks::GetDeviceProcAddr)) { @@ -290,7 +290,9 @@ bool FSRFG_Vk::CreateSwapchain(VkDevice device, const VkSwapchainCreateInfoKHR* if (!UsesDriver()) { - BypassOverlayHooks(_ffxSwapchain->dll); + // A plugin's FG has no dll of its own to patch + if (_ffxSwapchain->dll != nullptr) + BypassOverlayHooks(_ffxSwapchain->dll); // Logs why the swapchain can't be created, SDK 2.x takes it without a context if (_ffxSwapchain->vkBackendV2) @@ -501,7 +503,9 @@ void FSRFG_Vk::CreateContext() _swapchainOutdated = true; } - _ffx = driver ? FSR4DriverProviderVk::FgModule() : FfxApiProxy::VkFfxModule_FG(); + _ffx = driver ? FSR4DriverProviderVk::FgModule() + : _custom != nullptr ? &_custom->module + : FfxApiProxy::VkFfxModule_FG(); ffxCreateBackendVKDesc backendDesc {}; backendDesc.header.type = FfxApiProxy::VkBackendType(_ffx); @@ -646,7 +650,8 @@ void FSRFG_Vk::ConfigureFramePaceTuning() void FSRFG_Vk::QueryVersions() { auto& state = State::Instance(); - FfxApiProxy::VULKAN_QueryFgVersions(nullptr, state.ffxFGVersionIds, state.ffxFGVersionNames); + FfxApiProxy::VULKAN_QueryFgVersions(nullptr, state.ffxFGVersionIds, state.ffxFGVersionNames, + _custom != nullptr ? &_custom->module : nullptr); auto config = Config::Instance(); diff --git a/OptiScaler/framegen/ffx/FSRFG_Vk.h b/OptiScaler/framegen/ffx/FSRFG_Vk.h index bffc7fe5..209c299c 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Vk.h +++ b/OptiScaler/framegen/ffx/FSRFG_Vk.h @@ -24,6 +24,9 @@ class FSRFG_Vk : public virtual IFGFeature_Vk FfxModule* _ffxSwapchain = nullptr; FfxModule* _ffx = nullptr; + // Custom FG and swapchain provider, nullptr for the SDK and driver ones + CustomFfxModule* _custom = FfxApiProxy::ActiveCustomFgVk(); + // Selected FG version needs the swapchain from the other provider, the game recreates it on out of date bool _swapchainOutdated = false; diff --git a/OptiScaler/framegen/nvngx/Nvngx_Custom.cpp b/OptiScaler/framegen/nvngx/Nvngx_Custom.cpp index e53b8491..c70922c5 100644 --- a/OptiScaler/framegen/nvngx/Nvngx_Custom.cpp +++ b/OptiScaler/framegen/nvngx/Nvngx_Custom.cpp @@ -5,11 +5,12 @@ void Nvngx_Custom::LoadLibraries() { - ngx.dll = CustomProviders::LoadDll(_name, CustomProviders::DlssgDllPath(_name)); + auto exports = CustomProviders::Load(_name, CustomProviders::Kind::Dlssg); - if (ngx.dll == nullptr) + if (!exports) return; + ngx.SetSource(exports); ngx.LoadExports(); // Max fake frames are reported like DLSSG does, which only reports them once inited diff --git a/OptiScaler/framegen/nvngx/Nvngx_Custom.h b/OptiScaler/framegen/nvngx/Nvngx_Custom.h index c83ccde4..ac2d7b13 100644 --- a/OptiScaler/framegen/nvngx/Nvngx_Custom.h +++ b/OptiScaler/framegen/nvngx/Nvngx_Custom.h @@ -1,7 +1,8 @@ #pragma once #include -// nvngx_dlssg replacement from custom//dlssg, it's loaded by Opti so it can't check for nvngx.dll as the caller +// nvngx_dlssg replacement from custom//dlssg or a plugin, it's loaded by Opti so it can't check for nvngx.dll as +// the caller class Nvngx_Custom : public Nvngx_DllProxy { std::string _name; diff --git a/OptiScaler/framegen/nvngx/Nvngx_FFX.cpp b/OptiScaler/framegen/nvngx/Nvngx_FFX.cpp index de71d935..6320f53e 100644 --- a/OptiScaler/framegen/nvngx/Nvngx_FFX.cpp +++ b/OptiScaler/framegen/nvngx/Nvngx_FFX.cpp @@ -317,7 +317,8 @@ static constexpr Nvngx_FFX_Api ApiDx12 { FfxApiProxy::D3D12_Configure, FfxApiProxy::D3D12_Query, FfxApiProxy::D3D12_Dispatch, - FfxApiProxy::D3D12_QueryFgVersions, + [](void* device, std::vector& ids, std::vector& names) + { return FfxApiProxy::D3D12_QueryFgVersions(device, ids, names); }, GetResourceDx12, CopyTextureDx12, }; @@ -328,7 +329,8 @@ static constexpr Nvngx_FFX_Api ApiVk { FfxApiProxy::VULKAN_Configure, FfxApiProxy::VULKAN_Query, FfxApiProxy::VULKAN_Dispatch, - FfxApiProxy::VULKAN_QueryFgVersions, + [](void* device, std::vector& ids, std::vector& names) + { return FfxApiProxy::VULKAN_QueryFgVersions(device, ids, names); }, GetResourceVk, CopyTextureVk, }; diff --git a/OptiScaler/hooks/FG_Hooks.cpp b/OptiScaler/hooks/FG_Hooks.cpp index ae3e18bb..e44264a4 100644 --- a/OptiScaler/hooks/FG_Hooks.cpp +++ b/OptiScaler/hooks/FG_Hooks.cpp @@ -128,7 +128,7 @@ static bool CheckForFGStatus() if (State::Instance().activeFgOutput == FGOutput::FSRFG) { FfxApiProxy::InitFfxDx12(); - if (!FfxApiProxy::IsFGReady()) + if (!FfxApiProxy::IsFsrFgReady()) { ImGui::InsertNotification( { ImGuiToastType::Error, 20000, "Can't init FSR FG\nAre you missing the required DLLs?" }); diff --git a/OptiScaler/hooks/Vulkan_Hooks.cpp b/OptiScaler/hooks/Vulkan_Hooks.cpp index f0cc307e..5c998859 100644 --- a/OptiScaler/hooks/Vulkan_Hooks.cpp +++ b/OptiScaler/hooks/Vulkan_Hooks.cpp @@ -379,7 +379,7 @@ static IFGFeature_Vk* CreateFGFeature() bool sdkLoaded = FfxApiProxy::IsFGReadyVk(); bool driverLoaded = FSR4DriverProviderVk::InitFg(); - if (sdkLoaded || driverLoaded) + if (sdkLoaded || driverLoaded || FfxApiProxy::ActiveCustomFgVk() != nullptr) state.currentVkFG = new FSRFG_Vk(); else LOG_ERROR("Can't load FFX Vulkan frame generation, FSR FG won't be available"); diff --git a/OptiScaler/menu/menu_common.cpp b/OptiScaler/menu/menu_common.cpp index 53f4c41f..a40f10e3 100644 --- a/OptiScaler/menu/menu_common.cpp +++ b/OptiScaler/menu/menu_common.cpp @@ -992,40 +992,6 @@ void MenuCommon::GetCurrentBackendInfo(const API api, Upscaler& upscaler, std::s *name = UpscalerDisplayName(upscaler, api); } -// Custom upscaler setting of the API, nullptr when it has none -static CustomOptional* CustomUpscalerSetting(API api) -{ - if (api == API::DX12) - return &Config::Instance()->CustomUpscaler; - - if (api == API::Vulkan) - return &Config::Instance()->CustomUpscalerVk; - - return nullptr; -} - -// Custom upscaler picked for native DX12 FFX or DLSS, or native Vulkan FFX, empty for the regular ones -static std::string SelectedCustom(Upscaler upscaler, API api) -{ - if (api == API::DX12) - { - auto custom = Config::Instance()->CustomUpscaler.value_or(""); - - return (upscaler == Upscaler::FFX && CustomProviders::IsFfx(custom)) || - (upscaler == Upscaler::DLSS && CustomProviders::IsDlss(custom)) - ? custom - : ""; - } - - if (api == API::Vulkan) - { - auto custom = Config::Instance()->CustomUpscalerVk.value_or(""); - return upscaler == Upscaler::FFX && CustomProviders::IsFfxVk(custom) ? custom : ""; - } - - return ""; -} - // Backend that recreates the current feature, ray reconstruction keeps its DLSSD and the upscalers their own static Upscaler SameBackend(Upscaler currentBackend) { @@ -1037,13 +1003,14 @@ static Upscaler SameBackend(Upscaler currentBackend) return currentBackend; } -// Loaded custom FFX upscaler picked for the API, nullptr for the regular ones -static CustomFfxModule* SelectedCustomFfx(const std::string& name, API api) +// Loaded custom FFX upscaler, nullptr for the regular ones. Only native Vulkan FFX runs the Vulkan dll. +static CustomFfxModule* SelectedCustomFfx(const std::string& name, Upscaler upscaler, API api) { if (name.empty()) return nullptr; - return api == API::Vulkan ? FfxApiProxy::FindCustomUpscalerVk(name) : FfxApiProxy::FindCustomUpscalerDx12(name); + return api == API::Vulkan && upscaler == Upscaler::FFX ? FfxApiProxy::FindCustomUpscalerVk(name) + : FfxApiProxy::FindCustomUpscalerDx12(name); } // List of upscalers reported by FFX for a given backend, nullptr if the backend doesn't use FFX @@ -1150,11 +1117,11 @@ void MenuCommon::RenderUpscalerCombo(const API api, Upscaler currentUpscaler, co return ShortUpscalerName(upscaler, api, index); }; - const auto currentCustom = SelectedCustom(currentUpscaler, api); + const auto currentCustom = CustomProviders::Selected(api, currentUpscaler); // Interop is only shown here, the list uses a tag for it auto selectedName = upscalerName(targetBackend, ffxIndex); - if (auto custom = SelectedCustom(targetBackend, api); !custom.empty()) + if (auto custom = CustomProviders::Selected(api, targetBackend); !custom.empty()) selectedName = custom; else if (IsOn12(targetBackend)) selectedName += " (Dx12)"; @@ -1207,18 +1174,24 @@ void MenuCommon::RenderUpscalerCombo(const API api, Upscaler currentUpscaler, co // Custom ones are sorted after the regular ones, their names don't need versions // DLSS ones don't need a DLSS capable GPU - if (api == API::DX12) - { - for (auto& name : CustomProviders::Scan().ffx) - entries.push_back({ Upscaler::FFX, config->FfxUpscalerIndexFor(name).value_or_default(), {}, name }); + std::vector customNames; - for (auto& name : CustomProviders::Scan().dlss) - entries.push_back({ Upscaler::DLSS, -1, {}, name }); - } - else if (api == API::Vulkan) + for (auto kind : { CustomProviders::Kind::Ffx, CustomProviders::Kind::FfxVk, CustomProviders::Kind::Dlss }) { - for (auto& name : CustomProviders::Scan().ffxVk) - entries.push_back({ Upscaler::FFX, config->FfxUpscalerIndexFor(name).value_or_default(), {}, name }); + for (auto& name : CustomProviders::List(kind)) + { + if (!CustomProviders::Contains(customNames, name)) + customNames.push_back(name); + } + } + + for (auto& name : customNames) + { + for (auto upscaler : CustomProviders::Upscalers(name, api)) + { + const bool ffx = upscaler == Upscaler::FFX || upscaler == Upscaler::FFX_on12; + entries.push_back({ upscaler, ffx ? config->FfxUpscalerIndexFor(name).value_or_default() : -1, {}, name }); + } } // Upscaler of the GPU vendor goes first, FSRs are sorted by version, newest first @@ -1262,14 +1235,14 @@ void MenuCommon::RenderUpscalerCombo(const API api, Upscaler currentUpscaler, co // Regular and custom entries share an upscaler type, which the backend change check compares, // so a switch between them is marked here - if (auto customSetting = CustomUpscalerSetting(api); - !selected && (entry.upscaler == Upscaler::FFX || entry.upscaler == Upscaler::DLSS) && - customSetting != nullptr && entry.custom != customSetting->value_or("")) + if (auto& customSetting = CustomProviders::NameSetting(api); + !selected && entry.custom != customSetting.value_or("") && + (!entry.custom.empty() || CustomProviders::Runs(customSetting.value_or(""), api, entry.upscaler))) { if (entry.custom.empty()) - customSetting->reset(); + customSetting.reset(); else - *customSetting = entry.custom; + customSetting = entry.custom; MARK_ALL_BACKENDS_CHANGED(); } @@ -1278,14 +1251,12 @@ void MenuCommon::RenderUpscalerCombo(const API api, Upscaler currentUpscaler, co // Dimmed tags aligned to the right const char* tag = nullptr; - if (entry.ffxIndex >= 0 && IsOn12(entry.upscaler)) - tag = "FFX Dx12"; - else if (entry.ffxIndex >= 0) - tag = "FFX"; + if (entry.ffxIndex >= 0) + tag = IsOn12(entry.upscaler) ? "FFX Dx12" : "FFX"; + else if (!entry.custom.empty()) + tag = IsOn12(entry.upscaler) ? "DLSS Dx12" : "DLSS"; else if (IsOn12(entry.upscaler)) tag = "Dx12"; - else if (!entry.custom.empty()) - tag = "DLSS"; if (tag != nullptr) { @@ -1334,7 +1305,7 @@ static void RenderRRUpscalerCombo(API api, IFeature* feature, const char* label if (Nvngx_RR::NativeAvailable()) entries.push_back({}); - for (auto& name : CustomProviders::Scan().dlssd) + for (auto& name : CustomProviders::List(CustomProviders::Kind::Dlssd)) { if (Nvngx_RR::Listable(name, api)) entries.push_back(name); @@ -3984,8 +3955,8 @@ void MenuCommon::RenderActiveUpscalerSettings(RenderMenuContext& ctx) // FFX ----------------- if (!usesDlssd && (currentBackend == Upscaler::FFX || currentBackend == Upscaler::FFX_on12)) { - const auto customName = SelectedCustom(currentBackend, state.api); - const auto customUpscaler = SelectedCustomFfx(customName, state.api); + const auto customName = CustomProviders::Selected(state.api, currentBackend); + const auto customUpscaler = SelectedCustomFfx(customName, currentBackend, state.api); auto& upscalerIndex = config->FfxUpscalerIndexFor(customName); // A custom upscaler only has a list once it got loaded @@ -4627,11 +4598,11 @@ void MenuCommon::RenderFrameGenerationSelection(RenderMenuContext& ctx) auto constexpr optiFgIndex = (uint32_t) FGInput::Upscaler; // FSR FG's Vulkan dll is loaded with the device if (state.swapchainApi != API::Vulkan && !inputOptions[optiFgIndex].disabled && - state.activeFgOutput == FGOutput::FSRFG && !FfxApiProxy::IsFGReady() && !ffxInitTried) + state.activeFgOutput == FGOutput::FSRFG && !FfxApiProxy::IsFsrFgReady() && !ffxInitTried) { ffxInitTried = true; FfxApiProxy::InitFfxDx12(); - inputOptions[optiFgIndex].set_disabled(!FfxApiProxy::IsFGReady(), "amd_fidelityfx_dx12.dll is missing"); + inputOptions[optiFgIndex].set_disabled(!FfxApiProxy::IsFsrFgReady(), "amd_fidelityfx_dx12.dll is missing"); } else if (!inputOptions[optiFgIndex].disabled && state.activeFgOutput == FGOutput::XeFG && !xefgInitTried && XeFGProxy::Module() == nullptr) @@ -4678,7 +4649,8 @@ void MenuCommon::RenderFrameGenerationSelection(RenderMenuContext& ctx) auto constexpr dlssgOutputIndex = (uint32_t) FGOutput::DLSSG; const bool maySupportDlssg = primaryGpu.vendorId == VendorId::Nvidia; const bool hasDlssgReplacement = state.nukemsFgFileAvailable || state.artursFgFileAvailable || - FfxApiProxy::IsFGReady(false) || !CustomProviders::Scan().dlssg.empty(); + FfxApiProxy::IsFGReady(false) || + !CustomProviders::List(CustomProviders::Kind::Dlssg).empty(); if (!maySupportDlssg && hasDlssgReplacement) { @@ -4748,7 +4720,7 @@ void MenuCommon::RenderFrameGenerationSelection(RenderMenuContext& ctx) // clang-format on // Custom ones go after the rest, each one is a value from FGNvngxReplacement::Custom on - const auto& customFgs = CustomProviders::Scan().dlssg; + const auto customFgs = CustomProviders::List(CustomProviders::Kind::Dlssg); auto constexpr fgNvngxCustomIndex = (uint32_t) FGNvngxReplacement::Custom; for (uint32_t i = 0; i < customFgs.size(); i++) @@ -4871,6 +4843,34 @@ void MenuCommon::RenderFrameGenerationSelection(RenderMenuContext& ctx) ShowTooltip("What backend to use instead of the real DLSSG"); } + // Custom FFX FGs of the swapchain API, DX11 runs the DX12 one + const auto customFsrFgs = CustomProviders::List( + state.swapchainApi == API::Vulkan ? CustomProviders::Kind::FfxFgVk : CustomProviders::Kind::FfxFg); + + if (config->FGOutput == FGOutput::FSRFG && !customFsrFgs.empty()) + { + ImGui::TableNextColumn(); + + auto provider = config->FSRFGProvider.value_or(""); + + if (ImGui::BeginCombo("FSR FG Provider", provider.empty() ? "Default" : provider.c_str())) + { + if (ImGui::Selectable("Default", provider.empty())) + config->FSRFGProvider.reset(); + + for (auto& name : customFsrFgs) + { + if (ImGui::Selectable(name.c_str(), _stricmp(provider.c_str(), name.c_str()) == 0)) + config->FSRFGProvider = name; + } + + ImGui::EndCombo(); + } + + ShowTooltip("FFX frame generation and swapchain used by FSR FG\n" + "Custom ones are from custom\\\\ffx_fg(_vk) or plugins"); + } + ImGui::EndTable(); } @@ -4904,8 +4904,10 @@ void MenuCommon::RenderFrameGenerationSelection(RenderMenuContext& ctx) if (config->FGInput.value_or_default() == FGInput::XeFG && configFgOutput == FGOutput::XeFG) configFgOutput = FGOutput::NoFG; - state.fgSettingsChanged = state.activeFgOutput != configFgOutput || - state.activeFgInput != config->FGInput.value_or_default() || nvngxFgChanged; + state.fgSettingsChanged = + state.activeFgOutput != configFgOutput || state.activeFgInput != config->FGInput.value_or_default() || + nvngxFgChanged || + _stricmp(state.activeFsrFgProvider.c_str(), config->FSRFGProvider.value_or("").c_str()) != 0; if (state.fgSettingsChanged) { @@ -5278,8 +5280,9 @@ void MenuCommon::RenderFrameGenerationRuntimeSettings(RenderMenuContext& ctx) if (ScopedCard::Shows("fg_fsrfg") && state.activeFgOutput == FGOutput::FSRFG && state.activeFgInput != FGInput::NoFG && state.FGSwapchainExists()) { - if (state.activeFgInput != FGInput::Upscaler || (currentFeature != nullptr && !currentFeature->IsFrozen()) && - (state.currentVkFG != nullptr || FfxApiProxy::IsFGReady())) + if (state.activeFgInput != FGInput::Upscaler || + (currentFeature != nullptr && !currentFeature->IsFrozen()) && + (state.currentVkFG != nullptr || FfxApiProxy::IsFsrFgReady())) { ScopedCard card { "FSR FG Settings" }; @@ -6063,7 +6066,7 @@ void MenuCommon::RenderFrameGenerationRuntimeSettings(RenderMenuContext& ctx) ScopedCard card { "OptiFG Settings" }; if (currentFeature != nullptr && !currentFeature->IsFrozen() && - ((state.activeFgOutput == FGOutput::FSRFG && FfxApiProxy::IsFGReady()) || + ((state.activeFgOutput == FGOutput::FSRFG && FfxApiProxy::IsFsrFgReady()) || (state.activeFgOutput == FGOutput::XeFG && XeFGProxy::Module() != nullptr) || (state.activeFgOutput == FGOutput::DLSSG && StreamlineProxy::Module() != nullptr) || state.activeFgOutput == FGOutput::Reprojection)) @@ -6373,7 +6376,7 @@ void MenuCommon::RenderFrameGenerationRuntimeSettings(RenderMenuContext& ctx) { ImGui::Text("Upscaler is not active"); // Probably never will be visible } - else if (state.activeFgOutput == FGOutput::FSRFG && !FfxApiProxy::IsFGReady()) + else if (state.activeFgOutput == FGOutput::FSRFG && !FfxApiProxy::IsFsrFgReady()) { ImGui::TextColored(toneMapColor({ 1.0f, 0.0f, 0.0f, 1.0f }), "amd_fidelityfx_dx12.dll is missing!"); // Probably never will be visible diff --git a/OptiScaler/misc/CustomProviders.h b/OptiScaler/misc/CustomProviders.h index 7874a182..aaaed6b9 100644 --- a/OptiScaler/misc/CustomProviders.h +++ b/OptiScaler/misc/CustomProviders.h @@ -8,18 +8,57 @@ #include -// Dlls in custom// of the Opti folder, each kind a folder has is an entry in the upscaler or FG list: -// custom//ffx DX12 FFX upscaler -// custom//ffx_vk Vulkan FFX upscaler -// custom//dlss NGX runtime that runs DLSS -// custom//dlssg nvngx_dlssg replacement, an FG Nvngx entry -// custom//dlssd nvngx_dlssd replacement, a ray reconstruction (RRUpscaler) entry -// The dll can have any name. When the folder has more dlls, like ones the dll loads itself, the standard name -// is used (amd_fidelityfx_upscaler_dx12.dll, amd_fidelityfx_upscaler_vk.dll then amd_fidelityfx_vk.dll, nvngx.dll, -// nvngx_dlssg.dll, nvngx_dlssd.dll), else the first one. A Vulkan dll with another name is taken as -// amd_fidelityfx_upscaler_vk.dll. +// Custom providers are dlls in custom// of the Opti folder, or ones an ASI plugin registered with +// RegisterProvider. Each kind a name has is an entry in the upscaler or FG lists: +// custom//ffx DX12 FFX upscaler, on DX11 and Vulkan through DX12 interop +// custom//ffx_vk Vulkan FFX upscaler +// custom//ffx_fg DX12 FFX frame generation and its swapchain, an FSR FG provider +// custom//ffx_fg_vk Vulkan FFX frame generation and its swapchain, an FSR FG provider +// custom//dlss NGX runtime that runs DLSS on DX12 and Vulkan, on DX11 through DX12 interop +// custom//dlssg nvngx_dlssg replacement, an FG Nvngx entry +// custom//dlssd nvngx_dlssd replacement, a ray reconstruction (RRUpscaler) entry +// The dll can have any name. When the folder has more dlls, like ones the dll loads itself, the standard name of the +// kind is used (amd_fidelityfx_upscaler_dx12.dll, nvngx.dll...), else the first one. A Vulkan FFX dll other than +// amd_fidelityfx_vk.dll takes the V2 backend type of FFX SDK 2.x. namespace CustomProviders { +// Same values as OptiProviderKind +enum class Kind : uint32_t +{ + Ffx, + FfxVk, + FfxFg, + FfxFgVk, + Dlss, + Dlssg, + Dlssd, + Count +}; + +static_assert((uint32_t) Kind::Dlssd == OptiProvider_Dlssd); + +struct KindInfo +{ + const wchar_t* folder; + // Fixed size, an initializer_list in an inline function's static differs between translation units + const wchar_t* standardNames[2]; +}; + +inline const KindInfo& Info(Kind kind) +{ + static const KindInfo infos[] = { + { L"ffx", { L"amd_fidelityfx_upscaler_dx12.dll" } }, + { L"ffx_vk", { L"amd_fidelityfx_upscaler_vk.dll", L"amd_fidelityfx_vk.dll" } }, + { L"ffx_fg", { L"amd_fidelityfx_framegeneration_dx12.dll", L"amd_fidelityfx_dx12.dll" } }, + { L"ffx_fg_vk", { L"amd_fidelityfx_framegeneration_vk.dll", L"amd_fidelityfx_vk.dll" } }, + { L"dlss", { L"nvngx.dll" } }, + { L"dlssg", { L"nvngx_dlssg.dll" } }, + { L"dlssd", { L"nvngx_dlssd.dll" } }, + }; + + return infos[(size_t) kind]; +} + inline std::filesystem::path Root() { return std::filesystem::path(Config::Instance()->MainDllPath.value()) / L"custom"; @@ -28,15 +67,14 @@ inline std::filesystem::path Root() inline std::filesystem::path Folder(const std::string& name) { return Root() / string_to_wstring(name); } // The dll in custom//, empty when there's none -inline std::filesystem::path DllPath(const std::string& name, const wchar_t* kind, - std::initializer_list standardNames) +inline std::filesystem::path DllPath(const std::string& name, Kind kind) { - auto folder = Folder(name) / kind; + auto folder = Folder(name) / Info(kind).folder; std::error_code error; - for (auto standardName : standardNames) + for (auto standardName : Info(kind).standardNames) { - if (std::filesystem::exists(folder / standardName, error)) + if (standardName != nullptr && std::filesystem::exists(folder / standardName, error)) return folder / standardName; } @@ -49,43 +87,105 @@ inline std::filesystem::path DllPath(const std::string& name, const wchar_t* kin return {}; } -inline std::filesystem::path FfxDllPath(const std::string& name) +// Where the exports of a custom provider come from, a dll from its folder or a plugin's resolver +struct Exports { - return DllPath(name, L"ffx", { L"amd_fidelityfx_upscaler_dx12.dll" }); + HMODULE dll = nullptr; + std::filesystem::path path; // Empty for a plugin + OptiGetProcFn getProc = nullptr; + void* userData = nullptr; + + void* operator()(const char* exportName) const + { + if (getProc != nullptr) + return getProc(userData, exportName); + + return (void*) KernelBaseProxy::GetProcAddress_()(dll, exportName); + } + + explicit operator bool() const { return dll != nullptr || getProc != nullptr; } + + // The legacy FFX SDK 1.x dll takes FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK, the rest the V2 backend type + bool IsLegacyFfxVk() const { return _wcsicmp(path.filename().c_str(), L"amd_fidelityfx_vk.dll") == 0; } +}; + +struct PluginProvider +{ + std::string name; + Kind kind; + OptiGetProcFn getProc; + void* userData; +}; + +inline std::mutex pluginMutex; +inline std::vector pluginProviders; + +// Folder names aren't case sensitive +inline bool Contains(const std::vector& names, const std::string& name) +{ + return std::ranges::any_of(names, [&name](const std::string& n) { return _stricmp(n.c_str(), name.c_str()) == 0; }); } -inline std::filesystem::path FfxVkDllPath(const std::string& name) +// Names with that kind, the folders are scanned once and the plugin ones are added as they register +inline std::vector List(Kind kind) { - return DllPath(name, L"ffx_vk", { L"amd_fidelityfx_upscaler_vk.dll", L"amd_fidelityfx_vk.dll" }); + static const auto folders = [] + { + std::array, (size_t) Kind::Count> found; + std::error_code error; + + for (auto& entry : std::filesystem::directory_iterator(Root(), error)) + { + auto name = wstring_to_string(entry.path().filename().wstring()); + + for (size_t k = 0; k < found.size(); k++) + { + if (!DllPath(name, (Kind) k).empty()) + found[k].push_back(name); + } + } + + return found; + }(); + + auto names = folders[(size_t) kind]; + + std::scoped_lock lock(pluginMutex); + + for (auto& provider : pluginProviders) + { + if (provider.kind == kind && !Contains(names, provider.name)) + names.push_back(provider.name); + } + + return names; } -// The legacy FFX SDK 1.x dll takes FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK, the rest the V2 backend type -inline bool IsLegacyFfxVkDll(const std::filesystem::path& path) -{ - return _wcsicmp(path.filename().c_str(), L"amd_fidelityfx_vk.dll") == 0; -} +inline bool Has(const std::string& name, Kind kind) { return !name.empty() && Contains(List(kind), name); } -inline std::filesystem::path NgxDllPath(const std::string& name) { return DllPath(name, L"dlss", { L"nvngx.dll" }); } - -inline std::filesystem::path DlssgDllPath(const std::string& name) +// Exports of the name's kind, a plugin's first, then the folder's dll. Empty when there are none. +inline Exports Load(const std::string& name, Kind kind) { - return DllPath(name, L"dlssg", { L"nvngx_dlssg.dll" }); -} + { + std::scoped_lock lock(pluginMutex); -inline std::filesystem::path DlssdDllPath(const std::string& name) -{ - return DllPath(name, L"dlssd", { L"nvngx_dlssd.dll" }); -} + for (auto& provider : pluginProviders) + { + if (provider.kind == kind && _stricmp(provider.name.c_str(), name.c_str()) == 0) + { + LOG_INFO("Using custom {} from a plugin", name); + return { .getProc = provider.getProc, .userData = provider.userData }; + } + } + } -// nullptr when the path is empty or the dll can't be loaded -inline HMODULE LoadDll(const std::string& name, const std::filesystem::path& path) -{ + auto path = DllPath(name, kind); auto dll = path.empty() ? nullptr : NtdllProxy::LoadLibraryExW_Ldr(path.c_str(), NULL, NULL); if (dll == nullptr) { LOG_ERROR("Can't load custom {} from {}", name, wstring_to_string(Folder(name).wstring())); - return nullptr; + return {}; } LOG_INFO("Loaded custom {} from {}", name, wstring_to_string(path.wstring())); @@ -94,136 +194,158 @@ inline HMODULE LoadDll(const std::string& name, const std::filesystem::path& pat PluginApi::InitPlugin(dll, (PFN_OptiPluginInit) KernelBaseProxy::GetProcAddress_()(dll, OPTI_PLUGIN_INIT_NAME), name); - return dll; + return { .dll = dll, .path = path }; } -struct Names -{ - std::vector ffx; - std::vector ffxVk; - std::vector dlss; - std::vector dlssg; - std::vector dlssd; -}; - -// Scanned once -inline const Names& Scan() -{ - static const auto names = [] - { - Names found; - std::error_code error; - - for (auto& entry : std::filesystem::directory_iterator(Root(), error)) - { - auto name = wstring_to_string(entry.path().filename().wstring()); - - if (!FfxDllPath(name).empty()) - found.ffx.push_back(name); - - if (!FfxVkDllPath(name).empty()) - found.ffxVk.push_back(name); - - if (!NgxDllPath(name).empty()) - found.dlss.push_back(name); - - if (!DlssgDllPath(name).empty()) - found.dlssg.push_back(name); - - if (!DlssdDllPath(name).empty()) - found.dlssd.push_back(name); - } - - return found; - }(); - - return names; -} - -// Folder names aren't case sensitive -inline bool Contains(const std::vector& names, const std::string& name) -{ - return std::ranges::any_of(names, [&name](const std::string& n) { return _stricmp(n.c_str(), name.c_str()) == 0; }); -} - -inline bool IsFfx(const std::string& name) { return Contains(Scan().ffx, name); } -inline bool IsFfxVk(const std::string& name) { return Contains(Scan().ffxVk, name); } -inline bool IsDlss(const std::string& name) { return Contains(Scan().dlss, name); } -inline bool IsDlssg(const std::string& name) { return Contains(Scan().dlssg, name); } -inline bool IsDlssd(const std::string& name) { return Contains(Scan().dlssd, name); } - -// Dx12Upscaler from the ini as a custom folder's kind, a folder with both is used as FFX -inline void ResolveDx12Upscaler() +inline CustomOptional& NameSetting(API api) { auto cfg = Config::Instance(); - auto name = cfg->CustomUpscaler.value_or(""); + return api == API::DX11 ? cfg->CustomUpscalerDx11 + : api == API::Vulkan ? cfg->CustomUpscalerVk + : cfg->CustomUpscaler; +} - if (name.empty()) - return; +inline CustomOptional& UpscalerSetting(API api) +{ + auto cfg = Config::Instance(); + return api == API::DX11 ? cfg->Dx11Upscaler : api == API::Vulkan ? cfg->VulkanUpscaler : cfg->Dx12Upscaler; +} - if (IsFfx(name)) +// Upscalers a custom name runs as on the API, the native one first +inline std::vector Upscalers(const std::string& name, API api) +{ + std::vector upscalers; + + auto add = [&](Upscaler upscaler, Kind kind) { - cfg->Dx12Upscaler.set_from_config(Upscaler::FFX); + if (Has(name, kind)) + upscalers.push_back(upscaler); + }; + + if (api == API::DX11) + { + add(Upscaler::FFX_on12, Kind::Ffx); + add(Upscaler::DLSS_on12, Kind::Dlss); } - else if (IsDlss(name)) + else if (api == API::Vulkan) { - cfg->Dx12Upscaler.set_from_config(Upscaler::DLSS); + add(Upscaler::FFX, Kind::FfxVk); + add(Upscaler::FFX_on12, Kind::Ffx); + add(Upscaler::DLSS, Kind::Dlss); } else { - LOG_WARN("Dx12Upscaler={} isn't an upscaler or a folder in {}", name, wstring_to_string(Root().wstring())); - cfg->CustomUpscaler.reset(); + add(Upscaler::FFX, Kind::Ffx); + add(Upscaler::DLSS, Kind::Dlss); } + + return upscalers; } -// VulkanUpscaler from the ini as a custom folder, only FFX ones run on Vulkan -inline void ResolveVulkanUpscaler() +inline bool Runs(const std::string& name, API api, Upscaler upscaler) { - auto cfg = Config::Instance(); - auto name = cfg->CustomUpscalerVk.value_or(""); + return std::ranges::contains(Upscalers(name, api), upscaler); +} + +// Custom name picked for the API when it runs as that upscaler, empty for the regular ones +inline std::string Selected(API api, Upscaler upscaler) +{ + auto name = NameSetting(api).value_or(""); + return Runs(name, api, upscaler) ? name : ""; +} + +// Custom name from the API's upscaler setting in the ini as the upscaler it runs as. +// It's kept while a plugin can still register it. +inline void ResolveUpscaler(API api) +{ + auto& setting = NameSetting(api); + auto name = setting.value_or(""); if (name.empty()) return; - if (IsFfxVk(name)) + if (auto upscalers = Upscalers(name, api); !upscalers.empty()) { - cfg->VulkanUpscaler.set_from_config(Upscaler::FFX); + UpscalerSetting(api).set_from_config(upscalers[0]); } - else + else if (!Config::Instance()->LoadAsiPlugins.value_or_default()) { - LOG_WARN("VulkanUpscaler={} isn't an upscaler or a folder with ffx_vk in {}", name, + LOG_WARN("{} isn't an upscaler or a custom upscaler for API {} in {}", name, (int) api, wstring_to_string(Root().wstring())); - cfg->CustomUpscalerVk.reset(); + setting.reset(); } } -// FGNvngxReplacement from the ini as a custom folder with dlssg -inline void ResolveFGNvngx() +// Custom name of FGNvngxReplacement, FSRFGProvider or RRUpscaler from the ini, kept while a plugin can register it +inline void ResolveName(std::string& name, std::initializer_list kinds, const char* key) { - auto& name = State::Instance().fgNvngxCustom; + if (name.empty() || std::ranges::any_of(kinds, [&name](Kind kind) { return Has(name, kind); }) || + Config::Instance()->LoadAsiPlugins.value_or_default()) + { + return; + } + + LOG_WARN("{}={} isn't a replacement or a custom provider in {}", key, name, wstring_to_string(Root().wstring())); + name.clear(); +} - if (name.empty()) - return; +inline void ResolveAll() +{ + for (auto api : { API::DX11, API::DX12, API::Vulkan }) + ResolveUpscaler(api); + + auto& state = State::Instance(); + ResolveName(state.fgNvngxCustom, { Kind::Dlssg }, "FGNvngxReplacement"); - if (!IsDlssg(name)) + if (state.fgNvngxCustom.empty() && + Config::Instance()->FGNvngxReplacement.value_or_default() == FGNvngxReplacement::Custom) { - LOG_WARN("FGNvngxReplacement={} isn't a replacement or a folder with dlssg in {}", name, - wstring_to_string(Root().wstring())); - name.clear(); Config::Instance()->FGNvngxReplacement.reset(); } + + auto fsrFg = Config::Instance()->FSRFGProvider.value_or(""); + ResolveName(fsrFg, { Kind::FfxFg, Kind::FfxFgVk }, "FSRFGProvider"); + + if (fsrFg.empty()) + Config::Instance()->FSRFGProvider.reset(); + + auto rr = Config::Instance()->CustomRRUpscaler.value_or(""); + ResolveName(rr, { Kind::Dlssd }, "RRUpscaler"); + + if (rr.empty()) + Config::Instance()->CustomRRUpscaler.reset(); } -// RRUpscaler from the ini as a custom folder with dlssd -inline void ResolveRRUpscaler() +// From the plugin API, a plugin's name replaces a folder with the same name +inline bool Register(const std::string& name, Kind kind, OptiGetProcFn getProc, void* userData) { - auto cfg = Config::Instance(); - auto name = cfg->CustomRRUpscaler.value_or(""); + if (name.empty() || kind >= Kind::Count || getProc == nullptr) + return false; - if (!name.empty() && !IsDlssd(name)) { - LOG_WARN("RRUpscaler={} isn't a folder with dlssd in {}", name, wstring_to_string(Root().wstring())); - cfg->CustomRRUpscaler.reset(); + std::scoped_lock lock(pluginMutex); + + auto same = [&](const PluginProvider& p) + { return p.kind == kind && _stricmp(p.name.c_str(), name.c_str()) == 0; }; + + if (std::ranges::any_of(pluginProviders, same)) + { + LOG_WARN("Custom {} ({}) is already registered", name, wstring_to_string(Info(kind).folder)); + return false; + } + + pluginProviders.push_back({ name, kind, getProc, userData }); } + + LOG_INFO("Registered custom {} ({})", name, wstring_to_string(Info(kind).folder)); + + // The ini can name it before it's registered + for (auto api : { API::DX11, API::DX12, API::Vulkan }) + { + if (_stricmp(NameSetting(api).value_or("").c_str(), name.c_str()) == 0) + ResolveUpscaler(api); + } + + return true; } } // namespace CustomProviders diff --git a/OptiScaler/plugins/PluginApi.cpp b/OptiScaler/plugins/PluginApi.cpp index 3c4ee87f..5e4e4f17 100644 --- a/OptiScaler/plugins/PluginApi.cpp +++ b/OptiScaler/plugins/PluginApi.cpp @@ -4,6 +4,7 @@ #include "Config.h" #include "menu/menu_common.h" +#include "misc/CustomProviders.h" #include @@ -466,6 +467,16 @@ bool Api_ReInitUpscalers(OptiPlugin* plugin) return true; } +bool Api_RegisterProvider(OptiPlugin* plugin, const char* name, OptiProviderKind kind, OptiGetProcFn getProc, + void* userData) +{ + if (plugin == nullptr || name == nullptr) + return false; + + LOG_INFO("[{}] Registering provider {}", plugin->name, name); + return CustomProviders::Register(name, (CustomProviders::Kind) kind, getProc, userData); +} + const OptiPluginApi _api = { .size = sizeof(OptiPluginApi), .version = OPTI_PLUGIN_API_VERSION, @@ -508,6 +519,8 @@ const OptiPluginApi _api = { .Log = Api_Log, .ReInitUpscalers = Api_ReInitUpscalers, + + .RegisterProvider = Api_RegisterProvider, }; } // namespace diff --git a/OptiScaler/proxies/FfxApi_Proxy.h b/OptiScaler/proxies/FfxApi_Proxy.h index b4a8c5f2..91dd04f2 100644 --- a/OptiScaler/proxies/FfxApi_Proxy.h +++ b/OptiScaler/proxies/FfxApi_Proxy.h @@ -55,7 +55,7 @@ enum class FFXStructType Unknown, }; -// Upscaler dll from custom//ffx or ffx_vk, only used by Opti and never hooked for inputs +// Upscaler or FG from custom// or a plugin, only used by Opti and never hooked for inputs struct CustomFfxModule { std::string name; @@ -96,6 +96,8 @@ class FfxApiProxy // std::map so the pointers handed out stay valid inline static std::map custom_dx12; inline static std::map custom_vk; + inline static std::map custom_fg_dx12; + inline static std::map custom_fg_vk; inline static std::recursive_mutex customMutex; inline static ankerl::unordered_dense::map customContexts; @@ -117,7 +119,8 @@ class FfxApiProxy std::scoped_lock lock(customMutex); auto matches = [module](const auto& custom) { return custom.second.module.dll == module; }; - return std::ranges::any_of(custom_dx12, matches) || std::ranges::any_of(custom_vk, matches); + return std::ranges::any_of(custom_dx12, matches) || std::ranges::any_of(custom_vk, matches) || + std::ranges::any_of(custom_fg_dx12, matches) || std::ranges::any_of(custom_fg_vk, matches); } // Util::LoadProxyLibrary that never returns a custom upscaler dll, those can't be hooked for inputs @@ -176,8 +179,8 @@ class FfxApiProxy } std::scoped_lock lock(customMutex); - return std::ranges::any_of(custom_vk, - [module](const auto& custom) { return custom.second.module.dll == module; }); + auto matches = [module](const auto& custom) { return custom.second.module.dll == module; }; + return std::ranges::any_of(custom_vk, matches) || std::ranges::any_of(custom_fg_vk, matches); } static bool IsCustomUpscalerModule(HMODULE module) @@ -216,6 +219,25 @@ class FfxApiProxy return result; } + // Custom FFX FG picked for FSR FG output (State::activeFsrFgProvider), nullptr for the regular one + static CustomFfxModule* ActiveCustomFgDx12() + { + auto& name = State::Instance().activeFsrFgProvider; + return CustomProviders::Has(name, CustomProviders::Kind::FfxFg) ? LoadCustomFgDx12(name) : nullptr; + } + + static CustomFfxModule* ActiveCustomFgVk() + { + auto& name = State::Instance().activeFsrFgProvider; + return CustomProviders::Has(name, CustomProviders::Kind::FfxFgVk) ? LoadCustomFgVk(name) : nullptr; + } + + // FSR FG output can run on DX12, with the active custom FG or the regular FFX dlls + static bool IsFsrFgReady(bool sendNotification = true) + { + return ActiveCustomFgDx12() != nullptr || IsFGReady(sendNotification); + } + static bool IsSRReady(bool sendNotification = true) { bool result = (main_dx12.dll && !main_dx12.isLoader) || upscaling_dx12.dll != nullptr; @@ -1020,24 +1042,28 @@ class FfxApiProxy // Loading is only tried once per name, nullptr if it failed static CustomFfxModule* LoadCustomUpscalerDx12(const std::string& name) { - return LoadCustomUpscaler(custom_dx12, name, CustomProviders::FfxDllPath(name)); + return LoadCustom(custom_dx12, name, CustomProviders::Kind::Ffx); } static CustomFfxModule* LoadCustomUpscalerVk(const std::string& name) { - return LoadCustomUpscaler(custom_vk, name, CustomProviders::FfxVkDllPath(name)); + return LoadCustom(custom_vk, name, CustomProviders::Kind::FfxVk); + } + + static CustomFfxModule* LoadCustomFgDx12(const std::string& name) + { + return LoadCustom(custom_fg_dx12, name, CustomProviders::Kind::FfxFg); + } + + static CustomFfxModule* LoadCustomFgVk(const std::string& name) + { + return LoadCustom(custom_fg_vk, name, CustomProviders::Kind::FfxFgVk); } // Already loaded custom upscaler, doesn't try loading it - static CustomFfxModule* FindCustomUpscalerDx12(const std::string& name) - { - return FindCustomUpscaler(custom_dx12, name); - } + static CustomFfxModule* FindCustomUpscalerDx12(const std::string& name) { return FindCustom(custom_dx12, name); } - static CustomFfxModule* FindCustomUpscalerVk(const std::string& name) - { - return FindCustomUpscaler(custom_vk, name); - } + static CustomFfxModule* FindCustomUpscalerVk(const std::string& name) { return FindCustom(custom_vk, name); } // Context made by the given module, later calls with it go to the same module static ffxReturnCode_t D3D12_CreateContext(FfxModule* module, ffxContext* context, ffxCreateContextDescHeader* desc, @@ -1564,10 +1590,14 @@ class FfxApiProxy return D3D12_QuerySdk(context, desc); } - // Versions of the FFX SDK frame generation, the driver's ML FG is given to the SDK through AmdExtFfxApi + // Versions of the FFX SDK frame generation, the driver's ML FG is given to the SDK through AmdExtFfxApi. + // A custom module is asked for its own instead. static ffxReturnCode_t D3D12_QueryFgVersions(void* device, std::vector& ids, - std::vector& names) + std::vector& names, FfxModule* custom = nullptr) { + auto query = [custom](ffxQueryDescHeader* header) + { return custom != nullptr ? custom->Query(nullptr, header) : D3D12_Query(nullptr, header); }; + ffxQueryDescGetVersions versionQuery {}; versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION; @@ -1578,7 +1608,7 @@ class FfxApiProxy ids.clear(); names.clear(); - auto result = D3D12_Query(nullptr, &versionQuery.header); + auto result = query(&versionQuery.header); if (result == FFX_API_RETURN_OK && versionCount > 0) { @@ -1587,7 +1617,7 @@ class FfxApiProxy versionQuery.versionIds = ids.data(); versionQuery.versionNames = names.data(); - result = D3D12_Query(nullptr, &versionQuery.header); + result = query(&versionQuery.header); ids.resize(result == FFX_API_RETURN_OK ? versionCount : 0); names.resize(ids.size()); @@ -2203,10 +2233,14 @@ class FfxApiProxy return FFX_API_RETURN_OK; } - // Versions of the FFX SDK frame generation followed by the frame generation of the driver + // Versions of the FFX SDK frame generation followed by the frame generation of the driver. + // A custom module is asked for its own instead. static ffxReturnCode_t VULKAN_QueryFgVersions(void* device, std::vector& ids, - std::vector& names) + std::vector& names, FfxModule* custom = nullptr) { + auto query = [custom](ffxQueryDescHeader* header) + { return custom != nullptr ? custom->Query(nullptr, header) : VULKAN_QuerySdk(nullptr, header); }; + ffxQueryDescGetVersions versionQuery {}; versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION; @@ -2218,7 +2252,7 @@ class FfxApiProxy names.clear(); // Driver provided ML FG works without the FFX SDK - auto result = VULKAN_QuerySdk(nullptr, &versionQuery.header); + auto result = query(&versionQuery.header); if (result == FFX_API_RETURN_OK && versionCount > 0) { @@ -2227,13 +2261,14 @@ class FfxApiProxy versionQuery.versionIds = ids.data(); versionQuery.versionNames = names.data(); - result = VULKAN_QuerySdk(nullptr, &versionQuery.header); + result = query(&versionQuery.header); ids.resize(result == FFX_API_RETURN_OK ? versionCount : 0); names.resize(ids.size()); } - FSR4DriverProviderVk::AddFgToVersionList(ids, names); + if (custom == nullptr) + FSR4DriverProviderVk::AddFgToVersionList(ids, names); return ids.empty() ? result : FFX_API_RETURN_OK; } @@ -2481,8 +2516,8 @@ class FfxApiProxy (LPCWSTR) legacy_vk.dll, &pinned); } - static CustomFfxModule* LoadCustomUpscaler(std::map& customs, const std::string& name, - const std::filesystem::path& path) + static CustomFfxModule* LoadCustom(std::map& customs, const std::string& name, + CustomProviders::Kind kind) { std::scoped_lock lock(customMutex); @@ -2492,22 +2527,29 @@ class FfxApiProxy if (inserted) { it->second.name = name; - module.dll = CustomProviders::LoadDll(name, path); + auto exports = CustomProviders::Load(name, kind); - if (module.dll == nullptr) + if (!exports) return nullptr; - module.filePath = path.wstring(); - module.vkBackendV2 = !CustomProviders::IsLegacyFfxVkDll(path); - FSR4Presets::Hook(module.dll); - FSR4Models::Hook(module.dll); - GetMethods(module); + module.dll = exports.dll; + module.filePath = exports.path.wstring(); + module.vkBackendV2 = !exports.IsLegacyFfxVk(); + + // FSR4 presets and models are patched in the dll, a plugin has neither + if (module.dll != nullptr) + { + FSR4Presets::Hook(module.dll); + FSR4Models::Hook(module.dll); + } + + GetMethods(module, exports); } return module.CreateContext != nullptr && module.Query != nullptr ? &it->second : nullptr; } - static CustomFfxModule* FindCustomUpscaler(std::map& customs, const std::string& name) + static CustomFfxModule* FindCustom(std::map& customs, const std::string& name) { std::scoped_lock lock(customMutex); @@ -2515,14 +2557,15 @@ class FfxApiProxy return it != customs.end() && it->second.module.CreateContext != nullptr ? &it->second : nullptr; } - static void GetMethods(FfxModule& module) + static void GetMethods(FfxModule& module) { GetMethods(module, { .dll = module.dll }); } + + static void GetMethods(FfxModule& module, const CustomProviders::Exports& exports) { - module.Configure = (PfnFfxConfigure) KernelBaseProxy::GetProcAddress_()(module.dll, "ffxConfigure"); - module.CreateContext = (PfnFfxCreateContext) KernelBaseProxy::GetProcAddress_()(module.dll, "ffxCreateContext"); - module.DestroyContext = - (PfnFfxDestroyContext) KernelBaseProxy::GetProcAddress_()(module.dll, "ffxDestroyContext"); - module.Dispatch = (PfnFfxDispatch) KernelBaseProxy::GetProcAddress_()(module.dll, "ffxDispatch"); - module.Query = (PfnFfxQuery) KernelBaseProxy::GetProcAddress_()(module.dll, "ffxQuery"); + module.Configure = (PfnFfxConfigure) exports("ffxConfigure"); + module.CreateContext = (PfnFfxCreateContext) exports("ffxCreateContext"); + module.DestroyContext = (PfnFfxDestroyContext) exports("ffxDestroyContext"); + module.Dispatch = (PfnFfxDispatch) exports("ffxDispatch"); + module.Query = (PfnFfxQuery) exports("ffxQuery"); } static feature_version QueryVersionVk(FfxModule& module, uint64_t createDescType, const char* label) diff --git a/OptiScaler/proxies/Nvngx_Proxy.h b/OptiScaler/proxies/Nvngx_Proxy.h index b92ff68a..6e4a7b95 100644 --- a/OptiScaler/proxies/Nvngx_Proxy.h +++ b/OptiScaler/proxies/Nvngx_Proxy.h @@ -431,11 +431,28 @@ struct NgxExports PFN_VULKAN_GetFeatureRequirements VULKAN_GetFeatureRequirements = nullptr; PFN_VULKAN_EvaluateFeature VULKAN_EvaluateFeature = nullptr; + // Custom provider's dll, or a plugin's resolver that LoadExports takes the exports from + void SetSource(const CustomProviders::Exports& exports) + { + dll = exports.dll; + filePath = exports.path.wstring(); + getProc = exports.getProc; + getProcUserData = exports.userData; + } + protected: + OptiGetProcFn getProc = nullptr; + void* getProcUserData = nullptr; + // KernelBase's original GetProcAddress, so no hook can hand out something else FARPROC Export(const char* prefix, const char* name) const { - return KernelBaseProxy::GetProcAddress_()(dll, (std::string(prefix) + name).c_str()); + auto fullName = std::string(prefix) + name; + + if (getProc != nullptr) + return (FARPROC) getProc(getProcUserData, fullName.c_str()); + + return KernelBaseProxy::GetProcAddress_()(dll, fullName.c_str()); } void LoadSharedExports(const char* prefix) @@ -574,11 +591,12 @@ struct NvngxModule : NgxExports } }; -// NGX runtime from custom//dlss, only used by Opti's DLSS upscaler and never hooked +// NGX runtime from custom//dlss or a plugin, only used by Opti's DLSS upscaler and never hooked struct CustomNgxModule { NvngxModule module; bool dx12Inited = false; + bool vulkanInited = false; }; class NVNGXProxy @@ -666,6 +684,34 @@ class NVNGXProxy return nvResult; } + static NVSDK_NGX_Result InitVulkanModule(const NvngxModule& module, VkInstance InInstance, VkPhysicalDevice InPD, + VkDevice InDevice, PFN_vkGetInstanceProcAddr InGIPA, + PFN_vkGetDeviceProcAddr InGDPA) + { + NVSDK_NGX_FeatureCommonInfo fcInfo {}; + GetFeatureCommonInfo(&fcInfo); + NVSDK_NGX_Result nvResult = NVSDK_NGX_Result_Fail; + + if (State::Instance().NVNGX_ProjectId != "" && module.VULKAN_Init_ProjectID != nullptr) + { + LOG_DEBUG("module.VULKAN_Init_ProjectID!"); + nvResult = module.VULKAN_Init_ProjectID( + ProjectIdForDlss(), State::Instance().NVNGX_Engine, State::Instance().NVNGX_EngineVersion.c_str(), + State::Instance().NVNGX_ApplicationDataPath.c_str(), InInstance, InPD, InDevice, InGIPA, InGDPA, + State::Instance().NVNGX_Version, &fcInfo); + } + else if (module.VULKAN_Init_Ext != nullptr) + { + LOG_DEBUG("module.VULKAN_Init_Ext!"); + nvResult = module.VULKAN_Init_Ext(AppIdForDlss(), State::Instance().NVNGX_ApplicationDataPath.c_str(), + InInstance, InPD, InDevice, State::Instance().NVNGX_Version, &fcInfo); + } + + LOG_DEBUG("result: {0:X}", (UINT) nvResult); + + return nvResult; + } + inline static bool _cudaInited = false; inline static bool _dx11Inited = false; inline static bool _dx12Inited = false; @@ -962,8 +1008,8 @@ class NVNGXProxy return _dx12Inited; } - // Loading is only tried once per name, nullptr if it failed - static CustomNgxModule* LoadCustomDx12(const std::string& name) + // Loading is only tried once per name, nullptr if it failed or it can't run DLSS on the API + static CustomNgxModule* LoadCustom(const std::string& name, API api) { std::scoped_lock lock(_customMutex); @@ -973,19 +1019,25 @@ class NVNGXProxy if (inserted) { - auto path = CustomProviders::NgxDllPath(name); - module.dll = CustomProviders::LoadDll(name, path); + auto exports = CustomProviders::Load(name, CustomProviders::Kind::Dlss); - if (module.dll == nullptr) + if (!exports) return nullptr; - module.filePath = path.wstring(); + module.SetSource(exports); module.LoadExports(); } - auto usable = (module.D3D12_Init_ProjectID != nullptr || module.D3D12_Init_Ext != nullptr) && - module.D3D12_CreateFeature != nullptr && module.D3D12_EvaluateFeature != nullptr && - module.D3D12_ReleaseFeature != nullptr; + bool usable = false; + + if (api == API::Vulkan) + usable = (module.VULKAN_Init_ProjectID != nullptr || module.VULKAN_Init_Ext != nullptr) && + module.VULKAN_CreateFeature != nullptr && module.VULKAN_EvaluateFeature != nullptr && + module.VULKAN_ReleaseFeature != nullptr; + else + usable = (module.D3D12_Init_ProjectID != nullptr || module.D3D12_Init_Ext != nullptr) && + module.D3D12_CreateFeature != nullptr && module.D3D12_EvaluateFeature != nullptr && + module.D3D12_ReleaseFeature != nullptr; return usable ? &custom : nullptr; } @@ -1015,6 +1067,17 @@ class NVNGXProxy custom.dx12Inited = false; } + // Inited once, like NVIDIA's runtime on Vulkan + static bool InitCustomVulkan(CustomNgxModule& custom, VkInstance InInstance, VkPhysicalDevice InPD, + VkDevice InDevice, PFN_vkGetInstanceProcAddr InGIPA, PFN_vkGetDeviceProcAddr InGDPA) + { + if (!custom.vulkanInited) + custom.vulkanInited = + InitVulkanModule(custom.module, InInstance, InPD, InDevice, InGIPA, InGDPA) == NVSDK_NGX_Result_Success; + + return custom.vulkanInited; + } + static void SetDx12Inited(bool value) { _dx12Inited = value; } static bool IsDx12Inited() { return _dx12Inited; } @@ -1099,28 +1162,8 @@ class NVNGXProxy if (_module.dll == nullptr) return false; - NVSDK_NGX_FeatureCommonInfo fcInfo {}; - GetFeatureCommonInfo(&fcInfo); - NVSDK_NGX_Result nvResult = NVSDK_NGX_Result_Fail; - - if (State::Instance().NVNGX_ProjectId != "" && _module.VULKAN_Init_ProjectID != nullptr) - { - LOG_DEBUG("_module.VULKAN_Init_ProjectID!"); - nvResult = _module.VULKAN_Init_ProjectID( - ProjectIdForDlss(), State::Instance().NVNGX_Engine, State::Instance().NVNGX_EngineVersion.c_str(), - State::Instance().NVNGX_ApplicationDataPath.c_str(), InInstance, InPD, InDevice, InGIPA, InGDPA, - State::Instance().NVNGX_Version, &fcInfo); - } - else if (_module.VULKAN_Init_Ext != nullptr) - { - LOG_DEBUG("_module.VULKAN_Init_Ext!"); - nvResult = _module.VULKAN_Init_Ext(AppIdForDlss(), State::Instance().NVNGX_ApplicationDataPath.c_str(), - InInstance, InPD, InDevice, State::Instance().NVNGX_Version, &fcInfo); - } - - LOG_DEBUG("result: {0:X}", (UINT) nvResult); - - _vulkanInited = (nvResult == NVSDK_NGX_Result_Success); + _vulkanInited = + InitVulkanModule(_module, InInstance, InPD, InDevice, InGIPA, InGDPA) == NVSDK_NGX_Result_Success; return _vulkanInited; } diff --git a/OptiScaler/proxies/Nvngx_RRDllProxy.cpp b/OptiScaler/proxies/Nvngx_RRDllProxy.cpp index 0cb6272e..0e9ebf75 100644 --- a/OptiScaler/proxies/Nvngx_RRDllProxy.cpp +++ b/OptiScaler/proxies/Nvngx_RRDllProxy.cpp @@ -5,13 +5,12 @@ Nvngx_RRDllProxy::Nvngx_RRDllProxy(const std::string& name) { - auto path = CustomProviders::DlssdDllPath(name); - ngx.dll = CustomProviders::LoadDll(name, path); + auto exports = CustomProviders::Load(name, CustomProviders::Kind::Dlssd); - if (ngx.dll == nullptr) + if (!exports) return; - ngx.filePath = path.wstring(); + ngx.SetSource(exports); ngx.LoadExports(); LOG_INFO("Custom DLSSD {} DX12: {}, Vulkan: {}", name, IsDx12Available(), IsVulkanAvailable()); diff --git a/OptiScaler/upscalers/FeatureProvider_Dx11.cpp b/OptiScaler/upscalers/FeatureProvider_Dx11.cpp index 65a19b2d..aded9920 100644 --- a/OptiScaler/upscalers/FeatureProvider_Dx11.cpp +++ b/OptiScaler/upscalers/FeatureProvider_Dx11.cpp @@ -17,6 +17,7 @@ #include "upscalers/xess/XeSSFeature_Dx11.h" #include "upscalers/xess/XeSSFeature_Dx11on12.h" #include +#include #include bool FeatureProvider_Dx11::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NGX_Parameter* parameters, @@ -28,6 +29,7 @@ bool FeatureProvider_Dx11::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NG // DLSSD is only the game's ray reconstruction, it isn't one of the upscalers const bool rayReconstruction = upscaler == Upscaler::DLSSD; + const auto custom = CustomProviders::Selected(API::DX11, upscaler); switch (upscaler) { @@ -56,7 +58,7 @@ bool FeatureProvider_Dx11::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NG break; case Upscaler::FFX_on12: - *feature = std::make_unique(handleId, parameters); + *feature = std::make_unique(handleId, parameters, custom); break; case Upscaler::DLSS: @@ -73,9 +75,10 @@ bool FeatureProvider_Dx11::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NG } case Upscaler::DLSS_on12: - if (primaryGpu.dlssCapable && state.NVNGX_DLSS_Path.has_value()) + // A custom DLSS doesn't need a DLSS capable GPU + if (!custom.empty() || (primaryGpu.dlssCapable && state.NVNGX_DLSS_Path.has_value())) { - *feature = std::make_unique(handleId, parameters); + *feature = std::make_unique(handleId, parameters, custom); break; } else @@ -129,7 +132,8 @@ bool FeatureProvider_Dx11::ChangeFeature(Upscaler upscaler, ID3D11Device* device Config& cfg = *Config::Instance(); const bool dlssOnNonCapable = !IdentifyGpu::getPrimaryGpu().dlssCapable && - (state.newBackend == Upscaler::DLSS || state.newBackend == Upscaler::DLSS_on12); + (state.newBackend == Upscaler::DLSS || state.newBackend == Upscaler::DLSS_on12) && + CustomProviders::Selected(API::DX11, state.newBackend).empty(); if (state.newBackend == Upscaler::Reset || dlssOnNonCapable) state.newBackend = cfg.Dx11Upscaler.value_or_default(); diff --git a/OptiScaler/upscalers/FeatureProvider_Dx12.cpp b/OptiScaler/upscalers/FeatureProvider_Dx12.cpp index 90d2d5c1..1642895b 100644 --- a/OptiScaler/upscalers/FeatureProvider_Dx12.cpp +++ b/OptiScaler/upscalers/FeatureProvider_Dx12.cpp @@ -25,7 +25,7 @@ bool FeatureProvider_Dx12::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NG auto primaryGpu = IdentifyGpu::getPrimaryGpu(); ScopedSkipHeapCapture skipHeapCapture {}; - const auto custom = cfg.CustomUpscaler.value_or(""); + const auto custom = CustomProviders::Selected(API::DX12, upscaler); switch (upscaler) { @@ -42,11 +42,11 @@ bool FeatureProvider_Dx12::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NG break; case Upscaler::FFX: - *feature = std::make_unique(handleId, parameters, CustomProviders::IsFfx(custom) ? custom : ""); + *feature = std::make_unique(handleId, parameters, custom); break; case Upscaler::DLSS: - if (CustomProviders::IsDlss(custom)) + if (!custom.empty()) { *feature = std::make_unique(handleId, parameters, custom); break; @@ -128,7 +128,7 @@ bool FeatureProvider_Dx12::ChangeFeature(Upscaler upscaler, ID3D12Device* device Upscaler& backend = rayReconstruction ? rrBackend : state.newBackend; const bool dlssOnNonCapable = !IdentifyGpu::getPrimaryGpu().dlssCapable && backend == Upscaler::DLSS && - !CustomProviders::IsDlss(cfg.CustomUpscaler.value_or("")); + CustomProviders::Selected(API::DX12, backend).empty(); if (backend == Upscaler::Reset || dlssOnNonCapable) backend = cfg.Dx12Upscaler.value_or_default(); diff --git a/OptiScaler/upscalers/FeatureProvider_Vk.cpp b/OptiScaler/upscalers/FeatureProvider_Vk.cpp index c1d99ad7..f32db150 100644 --- a/OptiScaler/upscalers/FeatureProvider_Vk.cpp +++ b/OptiScaler/upscalers/FeatureProvider_Vk.cpp @@ -26,7 +26,7 @@ bool FeatureProvider_Vk::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NGX_ Config& cfg = *Config::Instance(); auto primaryGpu = IdentifyGpu::getPrimaryGpu(); - const auto custom = cfg.CustomUpscalerVk.value_or(""); + const auto custom = CustomProviders::Selected(API::Vulkan, upscaler); switch (upscaler) { @@ -47,17 +47,18 @@ bool FeatureProvider_Vk::GetFeature(Upscaler upscaler, UINT handleId, NVSDK_NGX_ break; case Upscaler::FFX: - *feature = std::make_unique(handleId, parameters, CustomProviders::IsFfxVk(custom) ? custom : ""); + *feature = std::make_unique(handleId, parameters, custom); break; case Upscaler::FFX_on12: - *feature = std::make_unique(handleId, parameters); + *feature = std::make_unique(handleId, parameters, custom); break; case Upscaler::DLSS: - if (primaryGpu.dlssCapable && state.NVNGX_DLSS_Path.has_value()) + // A custom DLSS doesn't need a DLSS capable GPU + if (!custom.empty() || (primaryGpu.dlssCapable && state.NVNGX_DLSS_Path.has_value())) { - *feature = std::make_unique(handleId, parameters); + *feature = std::make_unique(handleId, parameters, custom); break; } else @@ -142,8 +143,9 @@ bool FeatureProvider_Vk::ChangeFeature(Upscaler upscaler, VkInstance instance, V Upscaler rrBackend = Nvngx_RR::Backend(API::Vulkan); Upscaler& backend = rayReconstruction ? rrBackend : state.newBackend; - const bool dlssOnNonCapable = - !IdentifyGpu::getPrimaryGpu().dlssCapable && (backend == Upscaler::DLSS || backend == Upscaler::DLSS_on12); + const bool dlssOnNonCapable = !IdentifyGpu::getPrimaryGpu().dlssCapable && + (backend == Upscaler::DLSS || backend == Upscaler::DLSS_on12) && + CustomProviders::Selected(API::Vulkan, backend).empty(); if (backend == Upscaler::Reset || dlssOnNonCapable) backend = cfg.VulkanUpscaler.value_or_default(); diff --git a/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.cpp b/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.cpp index bb53c7ea..afc59cb7 100644 --- a/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.cpp +++ b/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.cpp @@ -3,9 +3,10 @@ #include "DLSSFeature_Dx11On12.h" #include -DLSSFeatureDx11On12::DLSSFeatureDx11On12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters) +DLSSFeatureDx11On12::DLSSFeatureDx11On12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler) : IFeature_Dx11wDx12(InHandleId, InParameters), IFeature_Dx11(InHandleId, InParameters), IFeature(InHandleId, InParameters) { - dx12Feature = std::make_unique(InHandleId, InParameters); + dx12Feature = std::make_unique(InHandleId, InParameters, customUpscaler); } diff --git a/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.h b/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.h index d698fa47..4e8ef3c6 100644 --- a/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.h +++ b/OptiScaler/upscalers/dlss/DLSSFeature_Dx11On12.h @@ -6,5 +6,7 @@ class DLSSFeatureDx11On12 : public IFeature_Dx11wDx12 public: Upscaler GetUpscalerType() const final { return Upscaler::DLSS_on12; } - DLSSFeatureDx11On12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters); + // customUpscaler is the name of a custom upscaler run by the DX12 feature, empty for the regular one + DLSSFeatureDx11On12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler = ""); }; diff --git a/OptiScaler/upscalers/dlss/DLSSFeature_Dx12.cpp b/OptiScaler/upscalers/dlss/DLSSFeature_Dx12.cpp index 393a6e24..feccfcb7 100644 --- a/OptiScaler/upscalers/dlss/DLSSFeature_Dx12.cpp +++ b/OptiScaler/upscalers/dlss/DLSSFeature_Dx12.cpp @@ -51,7 +51,7 @@ bool DLSSFeatureDx12::InitDLSS(ID3D12GraphicsCommandList* InCommandList, NVSDK_N if (!_dlssInited) return false; - // LoadCustomDx12 already checked the functions of a custom runtime + // LoadCustom already checked the functions of a custom runtime if (_custom == nullptr) { _moduleLoaded = @@ -169,7 +169,7 @@ DLSSFeatureDx12::DLSSFeatureDx12(unsigned int InHandleId, NVSDK_NGX_Parameter* I { if (!customUpscaler.empty()) { - _custom = NVNGXProxy::LoadCustomDx12(customUpscaler); + _custom = NVNGXProxy::LoadCustom(customUpscaler, API::DX12); _moduleLoaded = _custom != nullptr; if (!_moduleLoaded) diff --git a/OptiScaler/upscalers/dlss/DLSSFeature_Vk.cpp b/OptiScaler/upscalers/dlss/DLSSFeature_Vk.cpp index dbac459c..c4ace6ca 100644 --- a/OptiScaler/upscalers/dlss/DLSSFeature_Vk.cpp +++ b/OptiScaler/upscalers/dlss/DLSSFeature_Vk.cpp @@ -3,10 +3,35 @@ #include #include "DLSSFeature_Vk.h" +#include + +PFN_VULKAN_CreateFeature DLSSFeatureVk::CreateFeature() const +{ + if (_custom != nullptr) + return _custom->vulkanInited ? _custom->module.VULKAN_CreateFeature : nullptr; + + return NVNGXProxy::VULKAN_CreateFeature(); +} + +PFN_VULKAN_EvaluateFeature DLSSFeatureVk::EvaluateFeature() const +{ + if (_custom != nullptr) + return _custom->vulkanInited ? _custom->module.VULKAN_EvaluateFeature : nullptr; + + return NVNGXProxy::VULKAN_EvaluateFeature(); +} + +PFN_VULKAN_ReleaseFeature DLSSFeatureVk::ReleaseFeature() const +{ + if (_custom != nullptr) + return _custom->vulkanInited ? _custom->module.VULKAN_ReleaseFeature : nullptr; + + return NVNGXProxy::VULKAN_ReleaseFeature(); +} bool DLSSFeatureVk::InitInternal(VkCommandBuffer InCmdList, NVSDK_NGX_Parameter* InParameters) { - if (NVNGXProxy::NVNGXModule() == nullptr) + if (_custom == nullptr && NVNGXProxy::NVNGXModule() == nullptr) { LOG_ERROR("nvngx.dll not loaded!"); @@ -22,17 +47,25 @@ bool DLSSFeatureVk::InitInternal(VkCommandBuffer InCmdList, NVSDK_NGX_Parameter* if (!_dlssInited) { - _dlssInited = NVNGXProxy::InitVulkan(Instance, PhysicalDevice, Device, GIPA, GDPA); + _dlssInited = _custom != nullptr + ? NVNGXProxy::InitCustomVulkan(*_custom, Instance, PhysicalDevice, Device, GIPA, GDPA) + : NVNGXProxy::InitVulkan(Instance, PhysicalDevice, Device, GIPA, GDPA); if (!_dlssInited) return false; - _moduleLoaded = - (NVNGXProxy::VULKAN_Init_ProjectID() != nullptr || NVNGXProxy::VULKAN_Init_Ext() != nullptr) && - (NVNGXProxy::VULKAN_Shutdown() != nullptr || NVNGXProxy::VULKAN_Shutdown1() != nullptr) && - (NVNGXProxy::VULKAN_GetParameters() != nullptr || NVNGXProxy::VULKAN_AllocateParameters() != nullptr) && - NVNGXProxy::VULKAN_DestroyParameters() != nullptr && NVNGXProxy::VULKAN_CreateFeature() != nullptr && - NVNGXProxy::VULKAN_ReleaseFeature() != nullptr && NVNGXProxy::VULKAN_EvaluateFeature() != nullptr; + // LoadCustom already checked the functions of a custom runtime + if (_custom == nullptr) + { + _moduleLoaded = + (NVNGXProxy::VULKAN_Init_ProjectID() != nullptr || NVNGXProxy::VULKAN_Init_Ext() != nullptr) && + (NVNGXProxy::VULKAN_Shutdown() != nullptr || NVNGXProxy::VULKAN_Shutdown1() != nullptr) && + (NVNGXProxy::VULKAN_GetParameters() != nullptr || + NVNGXProxy::VULKAN_AllocateParameters() != nullptr) && + NVNGXProxy::VULKAN_DestroyParameters() != nullptr && + NVNGXProxy::VULKAN_CreateFeature() != nullptr && NVNGXProxy::VULKAN_ReleaseFeature() != nullptr && + NVNGXProxy::VULKAN_EvaluateFeature() != nullptr; + } // delay between init and create feature std::this_thread::sleep_for(std::chrono::milliseconds(500)); @@ -40,13 +73,12 @@ bool DLSSFeatureVk::InitInternal(VkCommandBuffer InCmdList, NVSDK_NGX_Parameter* LOG_INFO("Creating DLSS feature"); - if (NVNGXProxy::VULKAN_CreateFeature() != nullptr) + if (CreateFeature() != nullptr) { ProcessInitParams(InParameters); _p_dlssHandle = &_dlssHandle; - nvResult = NVNGXProxy::VULKAN_CreateFeature()(InCmdList, NVSDK_NGX_Feature_SuperSampling, InParameters, - &_p_dlssHandle); + nvResult = CreateFeature()(InCmdList, NVSDK_NGX_Feature_SuperSampling, InParameters, &_p_dlssHandle); if (nvResult != NVSDK_NGX_Result_Success) { @@ -61,7 +93,7 @@ bool DLSSFeatureVk::InitInternal(VkCommandBuffer InCmdList, NVSDK_NGX_Parameter* break; } - ReadVersion(); + ReadVersion(_custom != nullptr ? _custom->module.filePath : L""); initResult = true; @@ -80,12 +112,11 @@ bool DLSSFeatureVk::EvaluateInternal(VkCommandBuffer InCmdBuffer, NVSDK_NGX_Para return false; } - if (NVNGXProxy::VULKAN_EvaluateFeature() != nullptr) + if (EvaluateFeature() != nullptr) { ProcessEvaluateParams(InParameters); - NVSDK_NGX_Result nvResult = - NVNGXProxy::VULKAN_EvaluateFeature()(InCmdBuffer, _p_dlssHandle, InParameters, NULL); + NVSDK_NGX_Result nvResult = EvaluateFeature()(InCmdBuffer, _p_dlssHandle, InParameters, NULL); if (nvResult != NVSDK_NGX_Result_Success) { @@ -102,9 +133,22 @@ bool DLSSFeatureVk::EvaluateInternal(VkCommandBuffer InCmdBuffer, NVSDK_NGX_Para return true; } -DLSSFeatureVk::DLSSFeatureVk(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters) +DLSSFeatureVk::DLSSFeatureVk(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler) : IFeature(InHandleId, InParameters), IFeature_Vk(InHandleId, InParameters), DLSSFeature(InHandleId, InParameters) { + if (!customUpscaler.empty()) + { + _custom = NVNGXProxy::LoadCustom(customUpscaler, API::Vulkan); + _moduleLoaded = _custom != nullptr; + + if (!_moduleLoaded) + ImGui::InsertNotification( + { ImGuiToastType::Error, 10000, "Can't load custom upscaler %s", customUpscaler.c_str() }); + + return; + } + if (NVNGXProxy::NVNGXModule() == nullptr) { LOG_INFO("nvngx.dll not loaded, now loading"); @@ -119,6 +163,6 @@ DLSSFeatureVk::~DLSSFeatureVk() if (State::Instance().isShuttingDown) return; - if (NVNGXProxy::VULKAN_ReleaseFeature() != nullptr && _p_dlssHandle != nullptr) - NVNGXProxy::VULKAN_ReleaseFeature()(_p_dlssHandle); + if (ReleaseFeature() != nullptr && _p_dlssHandle != nullptr) + ReleaseFeature()(_p_dlssHandle); } diff --git a/OptiScaler/upscalers/dlss/DLSSFeature_Vk.h b/OptiScaler/upscalers/dlss/DLSSFeature_Vk.h index adf3396e..cec26575 100644 --- a/OptiScaler/upscalers/dlss/DLSSFeature_Vk.h +++ b/OptiScaler/upscalers/dlss/DLSSFeature_Vk.h @@ -7,6 +7,14 @@ class DLSSFeatureVk : public DLSSFeature, public IFeature_Vk { private: + // Custom NGX runtime, nullptr for NVIDIA's + CustomNgxModule* _custom = nullptr; + + // Functions of the NGX runtime this runs on + PFN_VULKAN_CreateFeature CreateFeature() const; + PFN_VULKAN_EvaluateFeature EvaluateFeature() const; + PFN_VULKAN_ReleaseFeature ReleaseFeature() const; + protected: // From IFeature_Vk bool InitInternal(VkCommandBuffer InCmdList, NVSDK_NGX_Parameter* InParameters) override; @@ -24,6 +32,6 @@ class DLSSFeatureVk : public DLSSFeature, public IFeature_Vk bool IsWithDx12() override { return false; } - DLSSFeatureVk(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters); + DLSSFeatureVk(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, const std::string& customUpscaler = ""); ~DLSSFeatureVk(); }; diff --git a/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.cpp b/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.cpp index d83f4dbe..c10f3f6a 100644 --- a/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.cpp +++ b/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.cpp @@ -9,9 +9,10 @@ static NVSDK_NGX_Parameter* SetParameters(NVSDK_NGX_Parameter* InParameters) return InParameters; } -FFXFeatureDx11on12::FFXFeatureDx11on12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters) +FFXFeatureDx11on12::FFXFeatureDx11on12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler) : IFeature_Dx11wDx12(InHandleId, InParameters), IFeature_Dx11(InHandleId, InParameters), IFeature(InHandleId, SetParameters(InParameters)) { - dx12Feature = std::make_unique(InHandleId, InParameters); + dx12Feature = std::make_unique(InHandleId, InParameters, customUpscaler); } diff --git a/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.h b/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.h index ff373899..02bee56f 100644 --- a/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.h +++ b/OptiScaler/upscalers/ffx/FFXFeature_Dx11On12.h @@ -6,5 +6,7 @@ class FFXFeatureDx11on12 : public IFeature_Dx11wDx12 public: Upscaler GetUpscalerType() const final { return Upscaler::FFX_on12; } - FFXFeatureDx11on12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters); + // customUpscaler is the name of a custom upscaler run by the DX12 feature, empty for the regular one + FFXFeatureDx11on12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler = ""); }; diff --git a/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.cpp b/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.cpp index f9038288..6b715637 100644 --- a/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.cpp +++ b/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.cpp @@ -9,9 +9,10 @@ static NVSDK_NGX_Parameter* SetParameters(NVSDK_NGX_Parameter* InParameters) return InParameters; } -FFXFeatureVkOn12::FFXFeatureVkOn12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters) +FFXFeatureVkOn12::FFXFeatureVkOn12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler) : IFeature_VkwDx12(InHandleId, InParameters), IFeature_Vk(InHandleId, InParameters), IFeature(InHandleId, SetParameters(InParameters)) { - dx12Feature = std::make_unique(InHandleId, InParameters); + dx12Feature = std::make_unique(InHandleId, InParameters, customUpscaler); } diff --git a/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.h b/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.h index 1912d7b0..a754398b 100644 --- a/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.h +++ b/OptiScaler/upscalers/ffx/FFXFeature_VkOn12.h @@ -6,5 +6,7 @@ class FFXFeatureVkOn12 : public IFeature_VkwDx12 public: Upscaler GetUpscalerType() const final { return Upscaler::FFX_on12; } - FFXFeatureVkOn12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters); + // customUpscaler is the name of a custom upscaler run by the DX12 feature, empty for the regular one + FFXFeatureVkOn12(unsigned int InHandleId, NVSDK_NGX_Parameter* InParameters, + const std::string& customUpscaler = ""); }; diff --git a/OptiScaler/upscalers/nvngx/Nvngx_RR.cpp b/OptiScaler/upscalers/nvngx/Nvngx_RR.cpp index 3be21cdb..5f9b2260 100644 --- a/OptiScaler/upscalers/nvngx/Nvngx_RR.cpp +++ b/OptiScaler/upscalers/nvngx/Nvngx_RR.cpp @@ -51,7 +51,7 @@ Nvngx_RRDllProxy* Nvngx_RR::Find(const std::string& name, API api, bool load) if (it == _modules.end()) { - if (!load || !CustomProviders::IsDlssd(name)) + if (!load || !CustomProviders::Has(name, CustomProviders::Kind::Dlssd)) return nullptr; // Kept when it fails so it's not loaded again @@ -79,7 +79,7 @@ std::string Nvngx_RR::SelectedName(API api, bool load) if (NativeAvailable()) return {}; - for (const auto& name : CustomProviders::Scan().dlssd) + for (const auto& name : CustomProviders::List(CustomProviders::Kind::Dlssd)) { if (Find(name, api, load) != nullptr) return name; diff --git a/OptiScaler/upscalers/nvngx/Nvngx_RR.h b/OptiScaler/upscalers/nvngx/Nvngx_RR.h index bfc2acec..0218d892 100644 --- a/OptiScaler/upscalers/nvngx/Nvngx_RR.h +++ b/OptiScaler/upscalers/nvngx/Nvngx_RR.h @@ -39,7 +39,10 @@ class Nvngx_RR static bool NativeAvailable(); // NVIDIA's or a custom one could run, without loading any - static bool DlssdAvailable() { return NativeAvailable() || !CustomProviders::Scan().dlssd.empty(); } + static bool DlssdAvailable() + { + return NativeAvailable() || !CustomProviders::List(CustomProviders::Kind::Dlssd).empty(); + } // Opti reports ray reconstruction to the game: a custom DLSSD runs, or no DLSSD can and a regular upscaler // is picked for it. NVIDIA's reports itself. Without load only an already loaded custom one counts diff --git a/plugin_sdk/README.md b/plugin_sdk/README.md index 71128386..52659445 100644 --- a/plugin_sdk/README.md +++ b/plugin_sdk/README.md @@ -4,7 +4,7 @@ Dlls loaded by OptiScaler can add their own tabs to the OptiScaler menu and keep their settings in `OptiScaler.ini`. Two kinds of dlls get the API: - **ASI plugins** in the `plugins` folder, loaded when `LoadAsiPlugins=true`. -- **Custom upscaler and FG dlls** in `custom//` (`ffx`, `ffx_vk`, `dlss`, `dlssg` or `dlssd`). +- **Custom upscaler and FG dlls** in `custom//` (`ffx`, `ffx_vk`, `ffx_fg`, `ffx_fg_vk`, `dlss`, `dlssg` or `dlssd`). Both use the API the same way. Below, "plugin" means either kind. @@ -55,9 +55,33 @@ Settings are stored in the `[Plugin.]` section of `OptiScaler.ini`, where - `Set*` only changes the value in memory. `SaveSettings`, or **Save INI** in the menu, writes the file. - `ResetValue` removes the key. +## Providers + +An ASI plugin can be an upscaler or FG itself, without a dll in `custom`. Register it from `OptiPluginInit`: + +```cpp +static void* GetProc(void* userData, const char* exportName) +{ + if (strcmp(exportName, "ffxCreateContext") == 0) + return (void*) MyCreateContext; + // ffxDestroyContext, ffxConfigure, ffxQuery, ffxDispatch ... + return nullptr; +} + +if (OPTI_API_HAS(api, RegisterProvider)) + api->RegisterProvider(plugin, "My Upscaler", OptiProvider_Ffx, GetProc, nullptr); +``` + +- `GetProc` returns the functions a dll of that kind would export, under the same names. OptiScaler calls them exactly like the dll's. +- The name shows up in the upscaler or FG lists like a `custom/` folder and can be put in `OptiScaler.ini` (`Dx12Upscaler=My Upscaler`). A registered name replaces a folder with the same name. +- `OptiProvider_Ffx` and `OptiProvider_Dlss` also run in DX11 games through DX12, `OptiProvider_Ffx` in Vulkan games too. +- `OptiProvider_FfxFg` and `OptiProvider_FfxFgVk` are picked as the FSR FG Provider. They create the frame generation swapchain context as well, so the plugin runs its own swapchain. +- `OptiProvider_Dlssd` runs the game's ray reconstruction, it's picked as the RR upscaler (`RRUpscaler=`). +- Vulkan FFX providers take the FFX SDK 2.x backend type, `FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_V2`. + ## Sample -[`sample/`](sample) contains a plugin that uses every function of the API. +[`sample/`](sample) contains a plugin that uses every function of the API. It registers two upscaler providers, "Sample FSR" and "Sample DLSS", whose functions always fail, to show the registration without a real upscaler. To build it: diff --git a/plugin_sdk/optiscaler_plugin.h b/plugin_sdk/optiscaler_plugin.h index c568dd94..34fcac3c 100644 --- a/plugin_sdk/optiscaler_plugin.h +++ b/plugin_sdk/optiscaler_plugin.h @@ -14,6 +14,7 @@ * Export OptiPluginInit from the plugin. OptiScaler calls it once, right after InitializeASI (if present). * Custom upscaler and FG dlls (custom//) can export it too, it's called when OptiScaler loads them, * which can be long after the game started. + * An ASI plugin can be an upscaler or FG itself, see RegisterProvider. * Keep the api pointer, it stays valid for the lifetime of the process. * * Compatibility rules: @@ -47,7 +48,7 @@ extern "C" { #endif -#define OPTI_PLUGIN_API_VERSION 2 +#define OPTI_PLUGIN_API_VERSION 3 // Handle of the calling plugin, given to OptiPluginInit typedef struct OptiPlugin OptiPlugin; @@ -63,6 +64,23 @@ extern "C" OptiLog_Error = 3, } OptiLogLevel; + // Kinds of custom providers, the same as the folders in custom// + typedef enum OptiProviderKind + { + OptiProvider_Ffx = 0, // DX12 FFX API upscaler, also on DX11 and Vulkan through DX12 interop + OptiProvider_FfxVk = 1, // Vulkan FFX API upscaler, takes FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_V2 + OptiProvider_FfxFg = 2, // DX12 FFX API frame generation and its frame generation swapchain + OptiProvider_FfxFgVk = 3, // Vulkan FFX API frame generation and its swapchain, the V2 backend type + OptiProvider_Dlss = 4, // NGX runtime that runs DLSS (NVSDK_NGX_D3D12_* and NVSDK_NGX_VULKAN_*) + OptiProvider_Dlssg = 5, // nvngx_dlssg replacement (NVSDK_NGX_D3D12_* and NVSDK_NGX_VULKAN_*) + OptiProvider_Dlssd = + 6, // nvngx_dlssd replacement, ray reconstruction (NVSDK_NGX_D3D12_* and NVSDK_NGX_VULKAN_*) + } OptiProviderKind; + + // Returns the function a dll of that kind exports under exportName (ffxCreateContext, + // NVSDK_NGX_D3D12_Init_Ext, ...) or NULL when the provider doesn't have it + typedef void* (*OptiGetProcFn)(void* userData, const char* exportName); + typedef struct OptiPluginApi { uint32_t size; // sizeof(OptiPluginApi) of the running OptiScaler @@ -152,6 +170,16 @@ extern "C" // Can be called from any thread. Check with OPTI_API_HAS(api, ReInitUpscalers). bool (*ReInitUpscalers)(OptiPlugin* plugin); + // Providers (version 3) ---------------------------------------------------------------------------------- + + // Adds name to the upscaler or FG lists like a custom// folder, OptiScaler gets its functions + // from getProc instead of a dll. A name can be registered once per kind and replaces a folder with the + // same name. getProc and userData have to stay valid for the lifetime of the process. + // Register from OptiPluginInit, so an upscaler or FG selected in OptiScaler.ini is found when the game + // starts. Check with OPTI_API_HAS(api, RegisterProvider). + bool (*RegisterProvider)(OptiPlugin* plugin, const char* name, OptiProviderKind kind, OptiGetProcFn getProc, + void* userData); + } OptiPluginApi; // True when the running OptiScaler has the given field of OptiPluginApi diff --git a/plugin_sdk/sample/SamplePlugin.cpp b/plugin_sdk/sample/SamplePlugin.cpp index a56e6d5e..502ea95f 100644 --- a/plugin_sdk/sample/SamplePlugin.cpp +++ b/plugin_sdk/sample/SamplePlugin.cpp @@ -4,10 +4,13 @@ // bin/Release/SamplePlugin.asi to the plugins folder next to OptiScaler and set LoadAsiPlugins=true // in OptiScaler.ini. Two tabs show up under PLUGINS in the menu and // the settings are kept in the [Plugin.SamplePlugin] section of OptiScaler.ini. +// It also registers two upscalers, "Sample FSR" and "Sample DLSS", that always fail. #include #include +#include +#include #include "../optiscaler_plugin.h" @@ -222,6 +225,70 @@ void DrawInfoTab(void* userData) snprintf(text, sizeof(text), "Clicked %d times", *counter); api->Text(text); } + +// Providers ------------------------------------------------------------------------------------------------ +// "Sample FSR" and "Sample DLSS" show up in the upscaler lists. Every function fails, so picking one only +// shows how OptiScaler handles a provider that errors out. A real provider would include the FFX API (ffx_api.h) +// and NGX (nvsdk_ngx.h) headers, these stubs only take the right number of arguments. + +constexpr uint32_t FfxReturnError = 1; // FFX_API_RETURN_ERROR +constexpr uint32_t NgxResultFail = 0xBAD00000; // NVSDK_NGX_Result_Fail + +uint32_t NgxFailWith1(void*) { return NgxResultFail; } +uint32_t FfxFailWith2(void*, void*) { return FfxReturnError; } +uint32_t FfxFailWith3(void*, void*, void*) { return FfxReturnError; } +uint32_t NgxFailWith4(void*, void*, void*, void*) { return NgxResultFail; } +uint32_t NgxFailWith5(void*, void*, void*, void*, void*) { return NgxResultFail; } +uint32_t NgxFailWith7(void*, void*, void*, void*, void*, void*, void*) { return NgxResultFail; } + +struct Export +{ + const char* name; + void* function; +}; + +// Same names as the exports of amd_fidelityfx_upscaler_dx12.dll +const Export ffxExports[] = { + { "ffxCreateContext", (void*) FfxFailWith3 }, { "ffxDestroyContext", (void*) FfxFailWith2 }, + { "ffxConfigure", (void*) FfxFailWith2 }, { "ffxQuery", (void*) FfxFailWith2 }, + { "ffxDispatch", (void*) FfxFailWith2 }, +}; + +// Same names as the exports of nvngx.dll, the ones OptiScaler needs to run DLSS on D3D12 and Vulkan +const Export ngxExports[] = { + { "NVSDK_NGX_D3D12_Init_Ext", (void*) NgxFailWith5 }, + { "NVSDK_NGX_D3D12_CreateFeature", (void*) NgxFailWith4 }, + { "NVSDK_NGX_D3D12_EvaluateFeature", (void*) NgxFailWith4 }, + { "NVSDK_NGX_D3D12_ReleaseFeature", (void*) NgxFailWith1 }, + { "NVSDK_NGX_VULKAN_Init_Ext", (void*) NgxFailWith7 }, + { "NVSDK_NGX_VULKAN_CreateFeature", (void*) NgxFailWith4 }, + { "NVSDK_NGX_VULKAN_EvaluateFeature", (void*) NgxFailWith4 }, + { "NVSDK_NGX_VULKAN_ReleaseFeature", (void*) NgxFailWith1 }, +}; + +// userData is the export table of the provider +template void* GetProc(void* userData, const char* exportName) +{ + for (const auto& entry : *(const Export(*)[N]) userData) + { + if (strcmp(entry.name, exportName) == 0) + return entry.function; + } + + return nullptr; // Not provided, OptiScaler skips what it doesn't need +} + +void RegisterProviders() +{ + if (!OPTI_API_HAS(api, RegisterProvider)) + { + api->Log(self, OptiLog_Info, "OptiScaler is too old to register providers"); + return; + } + + api->RegisterProvider(self, "Sample FSR", OptiProvider_Ffx, GetProc, (void*) &ffxExports); + api->RegisterProvider(self, "Sample DLSS", OptiProvider_Dlss, GetProc, (void*) &ngxExports); +} } // namespace extern "C" __declspec(dllexport) bool OptiPluginInit(const OptiPluginApi* optiApi, OptiPlugin* plugin) @@ -234,6 +301,8 @@ extern "C" __declspec(dllexport) bool OptiPluginInit(const OptiPluginApi* optiAp api->RegisterTab(self, "Sample", "Settings of the sample plugin", DrawMainTab, nullptr); api->RegisterTab(self, "Sample Info", "What the plugin API reports", DrawInfoTab, &clickCount); + RegisterProviders(); + api->Log(self, OptiLog_Info, "Sample plugin initialized"); return true;