From 5488a4c75340bfa64b3e1a0b0a45ca11a3ec32ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Tue, 24 Nov 2026 20:35:48 +0100 Subject: [PATCH 1/8] Fixing dlss for linux and some other minor fixes --- .../nvidia-dlss/nvidia-dlss-config.cmake | 22 +- cmake/vcpkg-ports/nvidia-dlss/portfile.cmake | 33 +- cmake/vcpkg-ports/nvidia-dlss/vcpkg.json | 2 +- editor/Assets/Types/EnvironmentMapAsset.cs | 2 + editor/Workspace/InspectorViewModel.cs | 13 +- engine/CMakeLists.txt | 9 +- engine/assets/shaders/debris.slang | 5 +- engine/src/toast/assets/asset_registry.cpp | 1 + engine/src/toast/assets/environment_map.hpp | 23 ++ engine/src/toast/assets/types.hpp | 1 + .../renderer/settings/renderer_settings.cpp | 10 +- .../toast/renderer/upscale/dlss_upscaler.cpp | 21 +- engine/src/toast/renderer/vulkan_renderer.hpp | 12 + .../toast/renderer/vulkan_renderer_scene.cpp | 28 ++ engine/src/toast/world/ambient_light.hpp | 10 + vcpkg.json | 298 ++++++++---------- 16 files changed, 290 insertions(+), 200 deletions(-) create mode 100644 engine/src/toast/assets/environment_map.hpp diff --git a/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake b/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake index 21dc9af81..bc4f0e442 100644 --- a/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake +++ b/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake @@ -1,17 +1,31 @@ get_filename_component(_nvidia_dlss_prefix "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) if(NOT TARGET nvidia::dlss) - # The NGX loader is a static library, nvngx_dlss.dll is loaded by it at run time and never linked + # The NGX loader is a static library, the Super Resolution runtime is loaded by it at run time and never linked add_library(nvidia::dlss STATIC IMPORTED) set_target_properties(nvidia::dlss PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${_nvidia_dlss_prefix}/include/ngx" IMPORTED_CONFIGURATIONS "RELEASE;DEBUG" - IMPORTED_LOCATION_RELEASE "${_nvidia_dlss_prefix}/lib/nvsdk_ngx_d.lib" - IMPORTED_LOCATION_DEBUG "${_nvidia_dlss_prefix}/debug/lib/nvsdk_ngx_d_dbg.lib" MAP_IMPORTED_CONFIG_RELWITHDEBINFO "RELEASE" MAP_IMPORTED_CONFIG_MINSIZEREL "RELEASE" ) + if(WIN32) + set_target_properties(nvidia::dlss PROPERTIES + IMPORTED_LOCATION_RELEASE "${_nvidia_dlss_prefix}/lib/nvsdk_ngx_d.lib" + IMPORTED_LOCATION_DEBUG "${_nvidia_dlss_prefix}/debug/lib/nvsdk_ngx_d_dbg.lib" + ) + else() + set_target_properties(nvidia::dlss PROPERTIES + IMPORTED_LOCATION_RELEASE "${_nvidia_dlss_prefix}/lib/libnvsdk_ngx.a" + IMPORTED_LOCATION_DEBUG "${_nvidia_dlss_prefix}/debug/lib/libnvsdk_ngx.a" + INTERFACE_LINK_LIBRARIES "${CMAKE_DL_LIBS}" + ) + endif() endif() -set(NVIDIA_DLSS_RUNTIME_DLL "${_nvidia_dlss_prefix}/bin/nvngx_dlss.dll") +if(WIN32) + set(NVIDIA_DLSS_RUNTIME_DLL "${_nvidia_dlss_prefix}/bin/nvngx_dlss.dll") +else() + file(GLOB NVIDIA_DLSS_RUNTIME_DLL "${_nvidia_dlss_prefix}/lib/libnvidia-ngx-dlss.so.*") +endif() unset(_nvidia_dlss_prefix) diff --git a/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake index fd78342bb..4b4dabc53 100644 --- a/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake +++ b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake @@ -23,11 +23,20 @@ set(_dlss_files include/nvsdk_ngx_standalone_common.h 7bd34e71dd346650d9194e3792fa0a95a5bef1fb1b514b678abebadbd4385a8ee6bcec75963ef66151dd4ec45220793dcc09bb984dd4af03fdf10abe4da71ac0 include/nvsdk_ngx_standalone_cuda.h 7cefa9dd4c35c8e6ef6213ae90deecd3fe180d5482dac35800bc7c853f76a188841baff1c2e48343590bd6cc0d544337046601ce67b9146883ec28eb33310167 include/nvsdk_ngx_vk.h 610fd37c9d059f939a1d9899662d9c8bf6f9b7059a22efdff78c4ef13466e211c51abef13f8098cb6b8c357a9574de617a1ca41bbe0a30107543d414e6eccecc - lib/Windows_x86_64/x64/nvsdk_ngx_d.lib 0809baf904b4246e2ecc35ffc4a5a88155f9c74722427a6b02d0fa85c5a4f24e9d9f759863e6fc3c7038927a14e003215f50215cda4dfbc7b4edb513e5bf58df - lib/Windows_x86_64/x64/nvsdk_ngx_d_dbg.lib 781cbe38adffc42b47b31a047d73e9de7e77242a2ad0d50a787335920985b2b3160f025c509bb9a31750f6094aecb0dd80607e12ed3029ed9bc7e79b33ef4d3b - lib/Windows_x86_64/rel/nvngx_dlss.dll 0e1fbd01ef2374f68e6ff8728f8b394279e58670c02d1f2aadbc8927db97476eb7bc8dca2a3dfd17d13789e6b5ef101850dec836a7fda3e67d379d4a34dfae7d LICENSE.txt 72f5b66daad2df8b49098857adc8705dae17b60fcbefb3f8625fd252aa1e5b82dd92cb9824dd052976c73f5a0d7437ca54e593b8e9a9010758aba8887f853390 ) +if(VCPKG_TARGET_IS_WINDOWS) + list(APPEND _dlss_files + lib/Windows_x86_64/x64/nvsdk_ngx_d.lib 0809baf904b4246e2ecc35ffc4a5a88155f9c74722427a6b02d0fa85c5a4f24e9d9f759863e6fc3c7038927a14e003215f50215cda4dfbc7b4edb513e5bf58df + lib/Windows_x86_64/x64/nvsdk_ngx_d_dbg.lib 781cbe38adffc42b47b31a047d73e9de7e77242a2ad0d50a787335920985b2b3160f025c509bb9a31750f6094aecb0dd80607e12ed3029ed9bc7e79b33ef4d3b + lib/Windows_x86_64/rel/nvngx_dlss.dll 0e1fbd01ef2374f68e6ff8728f8b394279e58670c02d1f2aadbc8927db97476eb7bc8dca2a3dfd17d13789e6b5ef101850dec836a7fda3e67d379d4a34dfae7d + ) +else() + list(APPEND _dlss_files + lib/Linux_x86_64/libnvsdk_ngx.a ed292252d5a7f905f63b85ada671827300cf28d0cc18c6ae7679261289907518500cb5167991e90972cc1f412745dcd674281afaab60b4253095f0939ed1ce4a + lib/Linux_x86_64/rel/libnvidia-ngx-dlss.so.${VERSION} e95c833c790c656d93392d08938616596776581da6b2e88426b75bec1fccba24ea838d3ba472fea22ab2405726a2dba63e2b1b6badc577068df4b388dcb9b7c5 + ) +endif() while(_dlss_files) list(POP_FRONT _dlss_files _path _sha512) @@ -43,11 +52,19 @@ while(_dlss_files) endif() endwhile() -file(INSTALL "${_dlss_nvsdk_ngx_d.lib}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib" RENAME "nvsdk_ngx_d.lib") -file(INSTALL "${_dlss_nvsdk_ngx_d_dbg.lib}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib" RENAME "nvsdk_ngx_d_dbg.lib") -# NVIDIA ships only a release runtime, NGX loads it at run time in every configuration -file(INSTALL "${_dlss_nvngx_dlss.dll}" DESTINATION "${CURRENT_PACKAGES_DIR}/bin" RENAME "nvngx_dlss.dll") -file(INSTALL "${_dlss_nvngx_dlss.dll}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/bin" RENAME "nvngx_dlss.dll") +if(VCPKG_TARGET_IS_WINDOWS) + file(INSTALL "${_dlss_nvsdk_ngx_d.lib}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib" RENAME "nvsdk_ngx_d.lib") + file(INSTALL "${_dlss_nvsdk_ngx_d_dbg.lib}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib" RENAME "nvsdk_ngx_d_dbg.lib") + # NVIDIA ships only a release runtime, NGX loads it at run time in every configuration + file(INSTALL "${_dlss_nvngx_dlss.dll}" DESTINATION "${CURRENT_PACKAGES_DIR}/bin" RENAME "nvngx_dlss.dll") + file(INSTALL "${_dlss_nvngx_dlss.dll}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/bin" RENAME "nvngx_dlss.dll") +else() + # One static loader for both configurations, the runtime keeps NVIDIA's versioned file name because NGX looks for it + file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib") + file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib") + file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib") + file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib") +endif() file(INSTALL "${CMAKE_CURRENT_LIST_DIR}/nvidia-dlss-config.cmake" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}") vcpkg_install_copyright(FILE_LIST "${_dlss_LICENSE.txt}") diff --git a/cmake/vcpkg-ports/nvidia-dlss/vcpkg.json b/cmake/vcpkg-ports/nvidia-dlss/vcpkg.json index 4e270e176..5565325c4 100644 --- a/cmake/vcpkg-ports/nvidia-dlss/vcpkg.json +++ b/cmake/vcpkg-ports/nvidia-dlss/vcpkg.json @@ -4,5 +4,5 @@ "description": "NVIDIA DLSS SDK (NGX headers, static loader library and the Super Resolution runtime) from github.com/NVIDIA/DLSS", "homepage": "https://github.com/NVIDIA/DLSS", "license": null, - "supports": "windows & x64" + "supports": "(windows | linux) & x64" } diff --git a/editor/Assets/Types/EnvironmentMapAsset.cs b/editor/Assets/Types/EnvironmentMapAsset.cs index 1c8a09290..33f3547ca 100644 --- a/editor/Assets/Types/EnvironmentMapAsset.cs +++ b/editor/Assets/Types/EnvironmentMapAsset.cs @@ -1,9 +1,11 @@ +using System.Collections.Generic; using Lucide.Avalonia; namespace editor.Assets.Types; public sealed class EnvironmentMapAsset : BaseAsset { public override string Type => "environment_map"; + public override IReadOnlyList CppTypeNames => ["EnvironmentMap"]; public override string Extension => ".hdr"; public override string DisplayName => "Environment Map"; public override string ChipText => "HDRI"; diff --git a/editor/Workspace/InspectorViewModel.cs b/editor/Workspace/InspectorViewModel.cs index 9a170848c..07b79260e 100644 --- a/editor/Workspace/InspectorViewModel.cs +++ b/editor/Workspace/InspectorViewModel.cs @@ -479,7 +479,7 @@ private void Rebuild(string uid, string type, InspectorState state) { // walk the inheritance chain most-derived -> base var current = Bare(type); while (ReflectionDatabase.Nodes.TryGetValue(current, out var info)) { - Cards.Add(BuildCard(info, ref colorCounter)); + Cards.Add(BuildCard(info, ref colorCounter, HiddenGroups(Bare(type), info.Name))); if (info.Parent is null) break; current = Bare(info.Parent.Name); } @@ -520,7 +520,15 @@ private void BuildProfiledCards(string type, IReadOnlyList sec } } - private ClassCardVM BuildCard(NodeInfo info, ref int colorCounter) { + // Groups an inherited class card must not show for a given concrete type + private static readonly string[] s_noGroups = []; + private static readonly string[] s_ambientLightHidden = ["Optimization", "Area"]; + + // ambient light has no position, shadow or shape, so Light's shadow/cull and area groups mean nothing there + private static string[] HiddenGroups(string type, string cardClass) => + type == "AmbientLight" && cardClass == "Light" ? s_ambientLightHidden : s_noGroups; + + private ClassCardVM BuildCard(NodeInfo info, ref int colorCounter, string[] hiddenGroups) { // class cards show the bare type name; the namespaced form lives in the header label only var typeName = info.Name; var card = new ClassCardVM(typeName, ReflectionDatabase.ResolveColor(typeName), @@ -529,6 +537,7 @@ private ClassCardVM BuildCard(NodeInfo info, ref int colorCounter) { foreach (var f in info.GlobalFields) AddField(card.Fields, f); foreach (var g in info.Groups) { + if (hiddenGroups.Contains(g.Name)) continue; var colorKey = Palette[colorCounter++ % Palette.Length]; var group = new GroupVM(g.Name, colorKey, $"group:{typeName}/{g.Name}", m_state!, this); foreach (var f in g.Fields) AddField(group.Fields, f); diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index ee1d6105c..760c39fb2 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -138,9 +138,9 @@ endforeach () target_compile_definitions(toast_engine PRIVATE TOAST_EXPORT) -# NVIDIA ships NGX for Windows x64 only, a missing package builds without DLSS instead of failing +# Only x86_64 Windows and Linux are wired up, a missing package builds without DLSS instead of failing include(CMakeDependentOption) -cmake_dependent_option(TOAST_DLSS "NVIDIA DLSS" ON "WIN32;ARCH STREQUAL x86_64" OFF) +cmake_dependent_option(TOAST_DLSS "NVIDIA DLSS" ON "WIN32 OR CMAKE_SYSTEM_NAME STREQUAL Linux;ARCH STREQUAL x86_64" OFF) if (TOAST_DLSS) find_package(nvidia-dlss CONFIG QUIET) if (nvidia-dlss_FOUND) @@ -338,6 +338,11 @@ if (WIN32) COMMAND_EXPAND_LISTS VERBATIM ) +else () + if (NOT TOAST_DLSS OR NOT nvidia-dlss_FOUND) + list(FILTER _vcpkg_dlls_debug EXCLUDE REGEX "/nvngx_dlss\\.so$") + list(FILTER _vcpkg_dlls_release EXCLUDE REGEX "/nvngx_dlss\\.so$") + endif () endif () diff --git a/engine/assets/shaders/debris.slang b/engine/assets/shaders/debris.slang index 28ad88f0b..a9b0716d0 100644 --- a/engine/assets/shaders/debris.slang +++ b/engine/assets/shaders/debris.slang @@ -144,7 +144,8 @@ static const float kInertia = 0.667; static const float kAirDrag = 0.15; static const float kSpinDrag = 0.3; static const float kRollDrag = 6.0; -static const float kSpawnGrace = 0.25; // seconds a new piece ignores being buried +static const float kEmissiveDecay = 0.4; // seconds for the glow to fall to 1/e +static const float kSpawnGrace = 0.25; // seconds a new piece ignores being buried static const uint kGridCells = 1u << 16; // mirrors DebrisSimulation::k_grid_cells static const uint kGridStride = 8; // mirrors DebrisSimulation::k_grid_stride static const uint kGridSlots = kGridStride - 1u; @@ -484,6 +485,8 @@ void integrateMain(uint3 id : SV_DispatchThreadID, uint3 groupThread : SV_GroupT DebrisMotion motion = gMotion[i]; const float stepTime = gParams.dt * float(gParams.substeps); motion.age += stepTime; + // Glow cools off shortly after the break + particle.emissive *= exp(-stepTime / kEmissiveDecay); if (motion.age > motion.lifetime) { particle.packed = 0u; gCurrent[i] = particle; diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 790a08bea..1ef23aef1 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -42,6 +42,7 @@ void AssetRegistry::init() { s_raw["animation"] = [](const std::vector& d) { return std::make_unique(d); }; s_raw["skeleton"] = [](const std::vector& d) { return std::make_unique(d); }; s_raw["voxel_model"] = [](const std::vector& d) { return std::make_unique(d); }; + s_raw["environment_map"] = [](const std::vector&) { return std::make_unique(); }; // Plain TOML loaders s_toml["curve"] = [](const toml::table& t) { return Curve::fromToml(t); }; diff --git a/engine/src/toast/assets/environment_map.hpp b/engine/src/toast/assets/environment_map.hpp new file mode 100644 index 000000000..3f4bd008f --- /dev/null +++ b/engine/src/toast/assets/environment_map.hpp @@ -0,0 +1,23 @@ +/** + * @file environment_map.hpp + * @author dario + * @date 24/11/2026 + * + * @brief Radiance .hdr sky and image-based lighting source, referenced by nodes through a handle + */ + +#pragma once +#include "core_types.hpp" + +namespace assets { + +/// Holds no pixels: the environment pass decodes the file from Handle::path() when it switches maps +class TOAST_API EnvironmentMap : public Asset { +public: + [[nodiscard]] + auto type() const -> std::string_view override { + return "environment_map"; + } +}; + +} diff --git a/engine/src/toast/assets/types.hpp b/engine/src/toast/assets/types.hpp index 497025dd4..409530720 100644 --- a/engine/src/toast/assets/types.hpp +++ b/engine/src/toast/assets/types.hpp @@ -18,6 +18,7 @@ #include "curve.hpp" #include "data.hpp" #include "data_value.hpp" +#include "environment_map.hpp" #include "material.hpp" #include "material_instance.hpp" #include "mesh.hpp" diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index a3a8c3801..50f8c6b37 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -445,7 +445,7 @@ void registerQuality(VulkanRenderer& renderer) { {.label = "Render scale", .category = "Quality", .description = "Share of the output resolution the world renders at before TAA upsamples it. Preset Custom only", - .min = 0.5, + .min = 0.1, .max = 1.0, .step = 0.05} ) @@ -1141,14 +1141,10 @@ void registerEnvironment(VulkanRenderer& renderer) { .asset_type = "environment_map"} ) .onChange([&renderer](const std::string& v) { - auto* pass = renderer.getEnvironmentPassMutable(); - if (pass == nullptr) { - return; - } if (v.empty() || v.contains("://")) { - pass->setEnvironmentMap(v); + renderer.setGlobalEnvironmentMap(v); } else { - pass->setEnvironmentMap(assets::AssetManager::getURI(toast::UID(toast::UID::fromString(v)))); + renderer.setGlobalEnvironmentMap(assets::AssetManager::getURI(toast::UID(toast::UID::fromString(v)))); } }); diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.cpp b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp index c12ea27ff..cff5bdf74 100644 --- a/engine/src/toast/renderer/upscale/dlss_upscaler.cpp +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp @@ -14,7 +14,11 @@ #ifdef TOAST_DLSS #include #include +#ifdef _WIN32 #include +#else +#include +#endif #endif namespace renderer { @@ -28,8 +32,9 @@ constexpr const char* k_engine_version = "1.0"; constexpr uint32_t k_vendor_nvidia = 0x10DE; /// %AppData%/nullptr-studios/toast-engine/logs like the log server, NGX writes its own logs there -auto dataPath() -> const std::filesystem::path& { - static const std::filesystem::path path = [] { +auto dataPath() -> const std::wstring& { + // NGX takes wchar_t paths, std::filesystem::path::c_str() is char on Linux + static const std::wstring path = [] { std::filesystem::path dir; std::error_code ec; if (char* pref_path = SDL_GetPrefPath("nullptr-studios", "toast-engine")) { @@ -39,13 +44,20 @@ auto dataPath() -> const std::filesystem::path& { dir = std::filesystem::temp_directory_path(ec) / "nullptr-studios" / "toast-engine" / "logs"; } std::filesystem::create_directories(dir, ec); - return dir; + return dir.wstring(); }(); return path; } /// NGX itself only searches the exe directory and the editor exe lives elsewhere auto engineDirectory() -> std::wstring { +#ifndef _WIN32 + Dl_info info {}; + if (dladdr(reinterpret_cast(&engineDirectory), &info) == 0 || info.dli_fname == nullptr) { + return {}; + } + return std::filesystem::path(info.dli_fname).parent_path().wstring(); +#else HMODULE module = nullptr; if (!GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -60,6 +72,7 @@ auto engineDirectory() -> std::wstring { return {}; } return std::filesystem::path(path.data()).parent_path().wstring(); +#endif } auto discoveryInfo() -> NVSDK_NGX_FeatureDiscoveryInfo { @@ -68,7 +81,7 @@ auto discoveryInfo() -> NVSDK_NGX_FeatureDiscoveryInfo { info.FeatureID = NVSDK_NGX_Feature_SuperSampling; info.Identifier.IdentifierType = NVSDK_NGX_Application_Identifier_Type_Project_Id; info.Identifier.v.ProjectDesc = {k_project_id, NVSDK_NGX_ENGINE_TYPE_CUSTOM, k_engine_version}; - info.ApplicationDataPath = dataPath().c_str(); + info.ApplicationDataPath = dataPath().c_str(); // same wide string, see dataPath() return info; } diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index eade38877..2dd42b7ae 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -960,6 +960,12 @@ class VulkanRenderer { void setEnvironmentPass(EnvironmentPass* pass) noexcept { m_environment_pass = pass; } + /// The Renderer Settings map, used whenever no enabled AmbientLight carries its own. Applied on the next tick + void setGlobalEnvironmentMap(std::string uri) { + std::scoped_lock lock(m_environment_mutex); + m_global_environment_uri = std::move(uri); + } + [[nodiscard]] auto getEnvironmentPass() const noexcept -> const EnvironmentPass* { return m_environment_pass; @@ -1571,6 +1577,12 @@ class VulkanRenderer { const ShadowPass* m_shadow_pass = nullptr; EnvironmentPass* m_environment_pass = nullptr; + std::mutex m_environment_mutex; + std::string m_global_environment_uri; + /// Last map the tick asked the pass for, so a map that fails to load is not retried every frame + std::string m_requested_environment_uri; + uint64_t m_ambient_environment_uid = 0; + std::string m_ambient_environment_uri; ReflectionProbePass* m_reflection_probe_pass = nullptr; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index 6286541ee..a7134d17e 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -987,6 +988,8 @@ auto VulkanRenderer::gatherLights(RenderFrame& frame) -> LightGather { const auto& light_nodes_snapshot = m_tick_light_nodes; glm::vec3 ambient_sum(0.0f); + // First enabled ambient light carrying its own HDRI wins over the global map + uint64_t environment_override = 0; uint32_t directional_count = 0; frame.lights.reserve(light_nodes_snapshot.size()); @@ -1114,6 +1117,9 @@ auto VulkanRenderer::gatherLights(RenderFrame& frame) -> LightGather { switch (light->lightType()) { case toast::LightType::ambient: { ambient_sum += light->color() * light->intensity(); + if (environment_override == 0) { + environment_override = static_cast(light)->environmentMapUid().data(); + } break; } case toast::LightType::directional: { @@ -1208,6 +1214,28 @@ auto VulkanRenderer::gatherLights(RenderFrame& frame) -> LightGather { } } + if (m_environment_pass != nullptr) { + std::string global; + { + std::scoped_lock lock(m_environment_mutex); + global = m_global_environment_uri; + } + // Resolved from the UID the field holds, so picking another asset changes it on the very next tick + if (environment_override != m_ambient_environment_uid) { + m_ambient_environment_uid = environment_override; + m_ambient_environment_uri = + environment_override != 0 ? assets::AssetManager::getURI(toast::UID(environment_override)) : std::string {}; + } + std::string wanted = m_ambient_environment_uri.empty() ? global : m_ambient_environment_uri; + if (wanted != m_requested_environment_uri) { + m_requested_environment_uri = wanted; + // A light still pointing at a deleted or reimported HDRI must not hide the global map + if (!m_environment_pass->setEnvironmentMap(wanted) && wanted != global) { + std::ignore = m_environment_pass->setEnvironmentMap(global); + } + } + } + return {ambient_sum, directional_count, shadow_caster_index, shadow_caster_direction}; } diff --git a/engine/src/toast/world/ambient_light.hpp b/engine/src/toast/world/ambient_light.hpp index cf404edd7..fd956d007 100644 --- a/engine/src/toast/world/ambient_light.hpp +++ b/engine/src/toast/world/ambient_light.hpp @@ -9,6 +9,7 @@ #pragma once #include "light.hpp" +#include #include namespace toast { @@ -18,6 +19,15 @@ class [[ToastNode, Icon("Environment")]] TOAST_API AmbientLight : public Light { ~AmbientLight() override = default; + /// @returns the HDRI that replaces the global environment map, data() 0 to keep the global one + [[nodiscard]] + auto environmentMapUid() const noexcept -> UID { + return m_environment_map.uid(); + } + private: + /// Replaces the Renderer Settings environment map while this light is enabled + [[Reflect, Name("Environment Map")]] + assets::Handle m_environment_map; }; } diff --git a/vcpkg.json b/vcpkg.json index 9e61a4ab0..2820fac04 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,173 +1,129 @@ { - "name": "engine", - "version-string": "1.0.0", - "builtin-baseline": "e06564091c10e0b042900800c9fd48aad7f00643", - "vcpkg-configuration": { - "overlay-ports": [ - "./cmake/vcpkg-ports" - ] + "name" : "engine", + "version-string" : "1.0.0", + "builtin-baseline" : "e06564091c10e0b042900800c9fd48aad7f00643", + "vcpkg-configuration" : { + "overlay-ports" : [ "./cmake/vcpkg-ports" ] }, - "dependencies": [ - { - "name": "asio", - "version>=": "1.32.0" - }, - { - "name": "sdl3", - "default-features": false, - "features": [ - { - "name": "vulkan" - }, - { - "name": "x11", - "platform": "linux" - }, - { - "name": "wayland", - "platform": "linux" - }, - { - "name": "dbus", - "platform": "linux" - }, - { - "name": "ibus", - "platform": "linux" - } - ], - "version>=": "3.4.8" - }, - { - "name": "vulkan", - "version>=": "2023-12-17" - }, - { - "name": "vulkan-loader", - "version>=": "1.4.341.0" - }, - { - "name": "vulkan-memory-allocator-hpp", - "version>=": "3.3.0" - }, - { - "name": "vulkan-memory-allocator", - "version>=": "3.3.0" - }, - { - "name": "tracy", - "features": [ - "on-demand" - ], - "version>=": "0.13.1" - }, - { - "name": "shader-slang", - "version>=": "2026.20" - }, - { - "name": "tomlplusplus", - "version>=": "3.4.0#1" - }, - { - "name": "nlohmann-json", - "version>=": "3.12.0#2" - }, - { - "name": "ktx", - "version>=": "4.4.2" - }, - { - "name": "glm", - "version>=": "1.0.3" - }, - { - "name": "protobuf", - "version>=": "6.33.4#2" - }, - { - "name": "tinyspline", - "version>=": "0.6.0" - }, - { - "name": "tinygltf", - "version>=": "3.0.0" - }, - { - "name": "json-schema-validator", - "version>=": "2.4.0" - }, - { - "name": "lz4", - "version>=": "1.10.0" - }, - { - "name": "sqlite3" - }, - { - "name": "indicators", - "version>=": "2.3" - }, - { - "name": "curl" - }, - { - "name": "zlib" - }, - { - "name": "luabridge3", - "version>=": "3.0-rc3" - }, - { - "name": "lua", - "version>=": "5.5.0#1" - }, - { - "name": "imgui", - "default-features": false, - "features": [ - { - "name": "vulkan-binding" - } - ], - "version>=": "1.92.7" - }, - { - "name": "rmlui", - "version>=": "6.2" - }, - { - "name": "cpptrace", - "features": [ - { - "name": "libunwind", - "platform": "linux" - } - ], - "version>=": "1.0.4" - }, - { - "name": "nvidia-dlss", - "platform": "windows & x64" - } - ], - "overrides": [ - { - "name": "tracy", - "version": "0.15.0" - }, - { - "name": "lua", - "version": "5.4.7" - }, - { - "name": "vulkan-memory-allocator", - "version": "3.3.0" - }, - { - "name": "vulkan-memory-allocator-hpp", - "version": "3.3.0", - "port-version": 1 - } - ] -} + "dependencies" : [ { + "name" : "asio", + "version>=" : "1.32.0" + }, { + "name" : "sdl3", + "default-features" : false, + "features" : [ { + "name" : "vulkan" + }, { + "name" : "x11", + "platform" : "linux" + }, { + "name" : "wayland", + "platform" : "linux" + }, { + "name" : "dbus", + "platform" : "linux" + }, { + "name" : "ibus", + "platform" : "linux" + } ], + "version>=" : "3.4.8" + }, { + "name" : "vulkan", + "version>=" : "2023-12-17" + }, { + "name" : "vulkan-loader", + "version>=" : "1.4.341.0" + }, { + "name" : "vulkan-memory-allocator-hpp", + "version>=" : "3.3.0" + }, { + "name" : "vulkan-memory-allocator", + "version>=" : "3.3.0" + }, { + "name" : "tracy", + "features" : [ "on-demand" ], + "version>=" : "0.13.1" + }, { + "name" : "shader-slang", + "version>=" : "2026.20" + }, { + "name" : "tomlplusplus", + "version>=" : "3.4.0#1" + }, { + "name" : "nlohmann-json", + "version>=" : "3.12.0#2" + }, { + "name" : "ktx", + "version>=" : "4.4.2" + }, { + "name" : "glm", + "version>=" : "1.0.3" + }, { + "name" : "protobuf", + "version>=" : "6.33.4#2" + }, { + "name" : "tinyspline", + "version>=" : "0.6.0" + }, { + "name" : "tinygltf", + "version>=" : "3.0.0" + }, { + "name" : "json-schema-validator", + "version>=" : "2.4.0" + }, { + "name" : "lz4", + "version>=" : "1.10.0" + }, { + "name" : "sqlite3" + }, { + "name" : "indicators", + "version>=" : "2.3" + }, { + "name" : "curl" + }, { + "name" : "zlib" + }, { + "name" : "luabridge3", + "version>=" : "3.0-rc3" + }, { + "name" : "lua", + "version>=" : "5.5.0#1" + }, { + "name" : "imgui", + "default-features" : false, + "features" : [ { + "name" : "vulkan-binding" + } ], + "version>=" : "1.92.7" + }, { + "name" : "rmlui", + "version>=" : "6.2" + }, { + "name" : "cpptrace", + "features" : [ { + "name" : "libunwind", + "platform" : "linux" + } ], + "version>=" : "1.0.4" + }, { + "name" : "nvidia-dlss", + "platform" : "(windows | linux) & x64" + }, { + "name" : "ffmpeg", + "version>=" : "9.0.2#7" + } ], + "overrides" : [ { + "name" : "tracy", + "version" : "0.15.0" + }, { + "name" : "lua", + "version" : "5.4.7" + }, { + "name" : "vulkan-memory-allocator", + "version" : "3.3.0" + }, { + "name" : "vulkan-memory-allocator-hpp", + "version" : "3.3.0", + "port-version" : 1 + } ] +} \ No newline at end of file From 470fef90130f9bb7e9f74ecd94e798436625db2b Mon Sep 17 00:00:00 2001 From: Dante Harper Date: Tue, 24 Nov 2026 21:06:59 +0100 Subject: [PATCH 2/8] i dunno dario stuff a --- cmake/vcpkg-ports/nvidia-dlss/portfile.cmake | 8 ++++---- flake.nix | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake index 4b4dabc53..1c4127911 100644 --- a/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake +++ b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake @@ -60,10 +60,10 @@ if(VCPKG_TARGET_IS_WINDOWS) file(INSTALL "${_dlss_nvngx_dlss.dll}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/bin" RENAME "nvngx_dlss.dll") else() # One static loader for both configurations, the runtime keeps NVIDIA's versioned file name because NGX looks for it - file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib") - file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib") - file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib") - file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib") + file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib" RENAME "libnvsdk_ngx.a") + file(INSTALL "${_dlss_libnvsdk_ngx.a}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib" RENAME "libnvsdk_ngx.a") + file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/lib" RENAME "libnvidia-ngx-dlss.so.${VERSION}") + file(INSTALL "${_dlss_libnvidia-ngx-dlss.so.${VERSION}}" DESTINATION "${CURRENT_PACKAGES_DIR}/debug/lib" RENAME "libnvidia-ngx-dlss.so.${VERSION}") endif() file(INSTALL "${CMAKE_CURRENT_LIST_DIR}/nvidia-dlss-config.cmake" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}") diff --git a/flake.nix b/flake.nix index 3a934ac5b..95e16d942 100644 --- a/flake.nix +++ b/flake.nix @@ -103,6 +103,7 @@ grpc pkg-config vcpkg + nasm dotnet-sdk clang-tools buf From b6c66b4dc3e00d4318d750926023c7c084e0ecb0 Mon Sep 17 00:00:00 2001 From: Dante Harper Date: Wed, 25 Nov 2026 10:59:36 +0100 Subject: [PATCH 3/8] linux-fixes --- flake.nix | 4 +- vcpkg.json | 302 +++++++++++++++++++++++++++++++---------------------- 2 files changed, 178 insertions(+), 128 deletions(-) diff --git a/flake.nix b/flake.nix index 95e16d942..a1e3c27f9 100644 --- a/flake.nix +++ b/flake.nix @@ -131,6 +131,7 @@ doxygen graphviz util-linux + nasm ]; @@ -154,11 +155,12 @@ export VCPKG_ROOT="${pkgs.vcpkg}/share/vcpkg" export NIX_SSL_CERT_FILE="${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt" export PKG_CONFIG="${pkgs.pkg-config}/bin/pkg-config" - export VCPKG_DEFAULT_BINARY_CACHE="/var/cache/vcpkg" + # export VCPKG_DEFAULT_BINARY_CACHE="/var/cache/vcpkg" export VCPKG_KEEP_ENV_VARS=$(env | grep -E '^(NIX_|PKG_CONFIG|VCPKG_DEFAULT_BINARY_CACHE)' | cut -d= -f1 | tr '\n' ';') export PROTOBUF_PROTOC="${pkgs.protobuf}/bin/protoc" export GRPC_PROTOC_PLUGIN="${pkgs.grpc}/bin/grpc_csharp_plugin" export VK_LAYER_PATH="${pkgs.vulkan-validation-layers}/share/vulkan/explicit_layer.d:${pkgs.vulkan-extension-layer}/share/vulkan/explicit_layer.d"; + export LD_LIBRARY_PATH="/usr/lib''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ''; }; }; diff --git a/vcpkg.json b/vcpkg.json index 2820fac04..002b3b8aa 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,129 +1,177 @@ { - "name" : "engine", - "version-string" : "1.0.0", - "builtin-baseline" : "e06564091c10e0b042900800c9fd48aad7f00643", - "vcpkg-configuration" : { - "overlay-ports" : [ "./cmake/vcpkg-ports" ] + "name": "engine", + "version-string": "1.0.0", + "builtin-baseline": "7281d8d64321f945f296e696d8561f68c8186c67", + "vcpkg-configuration": { + "overlay-ports": [ + "./cmake/vcpkg-ports" + ] }, - "dependencies" : [ { - "name" : "asio", - "version>=" : "1.32.0" - }, { - "name" : "sdl3", - "default-features" : false, - "features" : [ { - "name" : "vulkan" - }, { - "name" : "x11", - "platform" : "linux" - }, { - "name" : "wayland", - "platform" : "linux" - }, { - "name" : "dbus", - "platform" : "linux" - }, { - "name" : "ibus", - "platform" : "linux" - } ], - "version>=" : "3.4.8" - }, { - "name" : "vulkan", - "version>=" : "2023-12-17" - }, { - "name" : "vulkan-loader", - "version>=" : "1.4.341.0" - }, { - "name" : "vulkan-memory-allocator-hpp", - "version>=" : "3.3.0" - }, { - "name" : "vulkan-memory-allocator", - "version>=" : "3.3.0" - }, { - "name" : "tracy", - "features" : [ "on-demand" ], - "version>=" : "0.13.1" - }, { - "name" : "shader-slang", - "version>=" : "2026.20" - }, { - "name" : "tomlplusplus", - "version>=" : "3.4.0#1" - }, { - "name" : "nlohmann-json", - "version>=" : "3.12.0#2" - }, { - "name" : "ktx", - "version>=" : "4.4.2" - }, { - "name" : "glm", - "version>=" : "1.0.3" - }, { - "name" : "protobuf", - "version>=" : "6.33.4#2" - }, { - "name" : "tinyspline", - "version>=" : "0.6.0" - }, { - "name" : "tinygltf", - "version>=" : "3.0.0" - }, { - "name" : "json-schema-validator", - "version>=" : "2.4.0" - }, { - "name" : "lz4", - "version>=" : "1.10.0" - }, { - "name" : "sqlite3" - }, { - "name" : "indicators", - "version>=" : "2.3" - }, { - "name" : "curl" - }, { - "name" : "zlib" - }, { - "name" : "luabridge3", - "version>=" : "3.0-rc3" - }, { - "name" : "lua", - "version>=" : "5.5.0#1" - }, { - "name" : "imgui", - "default-features" : false, - "features" : [ { - "name" : "vulkan-binding" - } ], - "version>=" : "1.92.7" - }, { - "name" : "rmlui", - "version>=" : "6.2" - }, { - "name" : "cpptrace", - "features" : [ { - "name" : "libunwind", - "platform" : "linux" - } ], - "version>=" : "1.0.4" - }, { - "name" : "nvidia-dlss", - "platform" : "(windows | linux) & x64" - }, { - "name" : "ffmpeg", - "version>=" : "9.0.2#7" - } ], - "overrides" : [ { - "name" : "tracy", - "version" : "0.15.0" - }, { - "name" : "lua", - "version" : "5.4.7" - }, { - "name" : "vulkan-memory-allocator", - "version" : "3.3.0" - }, { - "name" : "vulkan-memory-allocator-hpp", - "version" : "3.3.0", - "port-version" : 1 - } ] -} \ No newline at end of file + "dependencies": [ + { + "name": "asio", + "version>=": "1.32.0" + }, + { + "name": "sdl3", + "default-features": false, + "features": [ + { + "name": "vulkan" + }, + { + "name": "x11", + "platform": "linux" + }, + { + "name": "wayland", + "platform": "linux" + }, + { + "name": "dbus", + "platform": "linux" + }, + { + "name": "ibus", + "platform": "linux" + } + ], + "version>=": "3.4.8" + }, + { + "name": "vulkan", + "version>=": "2023-12-17" + }, + { + "name": "vulkan-loader", + "version>=": "1.4.341.0" + }, + { + "name": "vulkan-memory-allocator-hpp", + "version>=": "3.3.0" + }, + { + "name": "vulkan-memory-allocator", + "version>=": "3.3.0" + }, + { + "name": "tracy", + "features": [ + "on-demand" + ], + "version>=": "0.13.1" + }, + { + "name": "shader-slang", + "version>=": "2026.20" + }, + { + "name": "tomlplusplus", + "version>=": "3.4.0#1" + }, + { + "name": "nlohmann-json", + "version>=": "3.12.0#2" + }, + { + "name": "ktx", + "version>=": "4.4.2" + }, + { + "name": "glm", + "version>=": "1.0.3" + }, + { + "name": "protobuf", + "version>=": "6.33.4#2" + }, + { + "name": "tinyspline", + "version>=": "0.6.0" + }, + { + "name": "tinygltf", + "version>=": "3.0.0" + }, + { + "name": "json-schema-validator", + "version>=": "2.4.0" + }, + { + "name": "lz4", + "version>=": "1.10.0" + }, + { + "name": "sqlite3" + }, + { + "name": "indicators", + "version>=": "2.3" + }, + { + "name": "curl" + }, + { + "name": "zlib" + }, + { + "name": "luabridge3", + "version>=": "3.0-rc3" + }, + { + "name": "lua", + "version>=": "5.5.0#1" + }, + { + "name": "imgui", + "default-features": false, + "features": [ + { + "name": "vulkan-binding" + } + ], + "version>=": "1.92.7" + }, + { + "name": "rmlui", + "version>=": "6.2" + }, + { + "name": "cpptrace", + "features": [ + { + "name": "libunwind", + "platform": "linux" + } + ], + "version>=": "1.0.4" + }, + { + "name": "nvidia-dlss", + "platform": "(windows | linux) & x64" + }, + { + "name": "ffmpeg", + "version>=": "9.0.2#7" + } + ], + "overrides": [ + { + "name": "tracy", + "version": "0.15.0" + }, + { + "name": "lua", + "version": "5.4.7" + }, + { + "name": "vulkan-memory-allocator", + "version": "3.3.0" + }, + { + "name": "vulkan-memory-allocator-hpp", + "version": "3.3.0", + "port-version": 1 + } + ] +} From 8bf657191c5b262abb1e13d73b3615e0975441b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Thu, 26 Nov 2026 11:02:16 +0100 Subject: [PATCH 4/8] shader warps optimization --- engine/assets/shaders/gi_common.slang | 377 ----- engine/assets/shaders/gi_debug.slang | 228 --- engine/assets/shaders/gi_debug.slang.meta | 4 - engine/assets/shaders/gi_merge.slang | 375 ----- engine/assets/shaders/gi_merge.slang.meta | 4 - engine/assets/shaders/gi_probes.slang | 601 -------- engine/assets/shaders/gi_probes.slang.meta | 4 - engine/assets/shaders/gi_rays.slang | 608 -------- engine/assets/shaders/gi_rays.slang.meta | 4 - engine/assets/shaders/gi_sample.slang | 215 +-- engine/assets/shaders/gi_sky.slang | 9 - engine/assets/shaders/gi_sky.slang.meta | 4 - engine/assets/shaders/lighting.slang | 132 +- engine/assets/shaders/volumetrics.slang | 53 +- engine/assets/shaders/voxel_denoise.slang | 85 +- engine/assets/shaders/voxel_glass.slang | 128 +- engine/assets/shaders/voxel_lighting.slang | 132 +- engine/assets/shaders/voxel_specular.slang | 108 +- engine/src/toast/engine.cpp | 23 +- engine/src/toast/renderer/core/gpu_timer.hpp | 2 +- .../src/toast/renderer/core/vulkan_common.hpp | 2 + .../src/toast/renderer/core/vulkan_core.cpp | 67 +- .../src/toast/renderer/core/vulkan_core.hpp | 8 + .../renderer/passes/debug/perf_window.cpp | 84 -- .../passes/debug/selection_outline.cpp | 4 +- .../passes/geometry/depth_prepass.cpp | 4 +- .../renderer/passes/geometry/voxel_pass.cpp | 85 +- .../renderer/passes/geometry/voxel_pass.hpp | 18 +- .../passes/lighting/gi_clipmap_pass.cpp | 20 +- .../passes/lighting/gi_clipmap_pass.hpp | 6 + .../renderer/passes/lighting/gi_pass.cpp | 1276 ----------------- .../renderer/passes/lighting/gi_pass.hpp | 318 ---- .../passes/lighting/traced_specular_pass.cpp | 102 +- .../passes/lighting/traced_specular_pass.hpp | 6 +- .../renderer/passes/post/lens_flare_pass.cpp | 65 +- .../toast/renderer/passes/post/taa_pass.cpp | 7 +- .../resources/scene_descriptor_set.cpp | 21 - .../toast/renderer/settings/gi_settings.hpp | 35 +- .../renderer/settings/renderer_settings.cpp | 256 +--- .../renderer/shaders/vulkan_pipeline.cpp | 39 +- engine/src/toast/renderer/vulkan_renderer.hpp | 15 +- .../toast/renderer/vulkan_renderer_record.cpp | 44 +- .../renderer/vulkan_renderer_resources.cpp | 1 + 43 files changed, 884 insertions(+), 4695 deletions(-) delete mode 100644 engine/assets/shaders/gi_debug.slang delete mode 100644 engine/assets/shaders/gi_debug.slang.meta delete mode 100644 engine/assets/shaders/gi_merge.slang delete mode 100644 engine/assets/shaders/gi_merge.slang.meta delete mode 100644 engine/assets/shaders/gi_probes.slang delete mode 100644 engine/assets/shaders/gi_probes.slang.meta delete mode 100644 engine/assets/shaders/gi_rays.slang delete mode 100644 engine/assets/shaders/gi_rays.slang.meta delete mode 100644 engine/assets/shaders/gi_sky.slang delete mode 100644 engine/assets/shaders/gi_sky.slang.meta delete mode 100644 engine/src/toast/renderer/passes/lighting/gi_pass.cpp delete mode 100644 engine/src/toast/renderer/passes/lighting/gi_pass.hpp diff --git a/engine/assets/shaders/gi_common.slang b/engine/assets/shaders/gi_common.slang index a9a36ccb9..a901e8a2a 100644 --- a/engine/assets/shaders/gi_common.slang +++ b/engine/assets/shaders/gi_common.slang @@ -1,113 +1,7 @@ // No resources so every GI pass can import it import depth_convention; -static const uint kGiMaxCascades = 6u; static const uint kGiEmpty = 0xFFFFFFFFu; -static const uint kGiFlagSeen = 1u; - -/// Mirrors renderer::GiPass counters with counts per parity then failures then probes pixels touched -static const uint kGiCounterTableFull = 16u; -static const uint kGiCounterPoolFull = 17u; -static const uint kGiCounterSeen = 18u; -static const uint kGiCounterDepositFull = 24u; -static const uint kGiCounterRays = 25u; -static const uint kGiCounterSlots = 26u; -static const uint kGiCounterInvalidated = 27u; -/// Hit points stored for the secondary cache per pool parity then the ones past the buffer -static const uint kGiCounterPoints = 28u; -static const uint kGiCounterPointsDropped = 30u; -static const uint kGiCounterFresh = 31u; -/// Pixels that found a deposit and may exceed the spawn list -static const uint kGiCounterSpawn = 38u; -/// Hits queued by pixel rays -static const uint kGiCounterPixelHits = 39u; -/// Hits queued by point rays -static const uint kGiCounterPointHits = 40u; - -/// Frames an unseen probe keeps its history and tile -static const uint kGiKeepFrames = 16u; - -/// LODs coarser than its points -static const uint kGiSecondaryLods = 2u; - -static const float kGiMaxHistory = 4096.0; -static const float kGiMinHistory = 1.0 / 64.0; -/// Sixteenths of the history rays of every 64th bucket summed per cascade -static const uint kGiCounterDepth = 32u; - -/// Grid stride passes always dispatch this many and loop over the counters -static const uint kGiStrideThreads = 4096u * 64u; - -/// Equal area directions per probe are 2N by N with N this times 2 per cascade -static const uint kGiBaseDirections = 4u; -static const uint kGiC0Directions = 2u * kGiBaseDirections * kGiBaseDirections; - -/// 6 by 6 octahedral texels inside a one texel border -static const uint kGiTileSize = 8u; -static const uint kGiTileInterior = 6u; -/// Mirrors renderer::GiPass k_atlas_tiles_per_row and k_atlas_rows -static const uint kGiAtlasTilesPerRow = 256u; -static const uint kGiAtlasRows = 128u; -static const float2 kGiAtlasSize = float2(kGiAtlasTilesPerRow * kGiTileSize, kGiAtlasRows * kGiTileSize); - -/// x table offset y table mask z pool offset w pool capacity -typedef uint4 GiCascadeLayout; - -/// Mirrors renderer::GiPass::FrameData -struct GiFrame -{ - /// Jittered since depth was rasterized with it - float4x4 inverseViewProjection; - /// xyz camera w probe spacing at LOD 0 cascade 0 - float4 camera; - /// x Chebyshev distance where LOD 1 starts y LOD overlap share z lifetime in frames w spawn step in pixels - float4 lod; - /// x frame y cascades z pool parity written this frame w 0 drops every carried probe - uint4 frame; - /// x width y height zw spawn offset inside the step - uint4 viewport; - /// x pool entries per parity y table entries of every cascade z deposit probes of every cascade w direction slots - uint4 pool; - /// x interval of c0 in units of its probe spacing y sun reach in meters z deposit fixed point scale w cone slope - float4 rays; - /// xy R2 jitter z history kept per frame w history left after a change nearby - float4 jitter; - /// x hit points per parity y secondary cache on z asfloat share of off screen hits kept w points kept - uint4 secondary; - /// x max ray luminance y history floor in rays z keep of that floor - float4 limits; - GiCascadeLayout cascades[kGiMaxCascades]; - /// x deposit probe offset y deposit probe capacity w directions per probe - uint4 deposits[kGiMaxCascades]; - /// x spawn list capacity y point hit offset z hit capacity - uint4 queues; -}; - -struct GiPoint -{ - float3 position; - /// giOctEncode of the hit normal as two unorm16 - uint normal; -}; - -struct GiProbe -{ - /// xyz cell w LOD - int4 cell; - uint lastSeen; - /// Index in the previous pool or kGiEmpty for a new probe - uint previous; - /// kGiEmpty unless a pixel touched the probe this frame - uint deposit; - /// First direction slot this frame or kGiEmpty - uint slots; -}; - -/// Cell coordinates modulo 512 stay unique inside the few hundred cells one LOD spans around the camera -uint giKey(int3 cell, uint lod) -{ - return (uint(cell.x) & 511u) | ((uint(cell.y) & 511u) << 9) | ((uint(cell.z) & 511u) << 18) | ((lod & 31u) << 27); -} uint giHash(uint key) { @@ -119,254 +13,12 @@ uint giHash(uint key) return key; } -/// Deposit transmittance in sixteenths so a ray through fog keeps a fraction -static const float kGiTransmittanceScale = 16.0; - float giRandom(inout uint state) { state = giHash(state + 0x9e3779b9u); return float(state >> 8) / 16777216.0; } -float giSpacing(GiFrame frame, uint lod, uint cascade) -{ - return frame.camera.w * float(1u << min(lod + cascade, 30u)); -} - -int3 giCell(float3 world, float spacing) -{ - return int3(floor(world / spacing)); -} - -/// Chebyshev so LOD shells follow the grid -uint giLod(GiFrame frame, float3 world, out bool overlap) -{ - const float3 offset = abs(world - frame.camera.xyz); - const float distance = max(offset.x, max(offset.y, offset.z)); - const float start = frame.lod.x; - const uint lod = distance <= start ? 0u : min(uint(floor(log2(distance / start))), 29u); - overlap = distance >= frame.lod.y * start * float(1u << (lod + 1u)); - return lod; -} - -float3 giWorldAt(GiFrame frame, float2 uv, float depth) -{ - const float4 world = mul(frame.inverseViewProjection, float4(uv * 2.0 - 1.0, depth, 1.0)); - return world.xyz / world.w; -} - -bool giIsSky(float depth) -{ - return depth == kFarDepth; -} - -/// Share of a c0 cell along the normal since voxel faces lie on cell planes and jittered depth would flip the cell -static const float kGiSurfaceBias = 0.25; - -/// Toward the camera where nothing wrote a normal -float3 giSurfaceNormal(float4 encoded, float3 world, float3 camera) -{ - const float length2 = dot(encoded.xyz, encoded.xyz); - return length2 > 0.25 ? encoded.xyz * rsqrt(length2) : normalize(camera - world); -} - -float giIntervalEnd(GiFrame frame, uint lod, uint cascade) -{ - return frame.rays.x * giSpacing(frame, lod, 0u) * float(1u << min(2u * cascade, 30u)); -} - -/// Equal area map so every direction bucket covers the same solid angle -float2 giEncodeDirection(float3 direction) -{ - const float phi = atan2(direction.y, direction.x); - return float2(frac(phi / 6.28318531), saturate(direction.z * 0.5 + 0.5)); -} - -float3 giDecodeDirection(float2 uv) -{ - const float phi = uv.x * 6.28318531; - const float z = uv.y * 2.0 - 1.0; - const float r = sqrt(saturate(1.0 - z * z)); - return float3(r * cos(phi), r * sin(phi), z); -} - -uint giSide(uint cascade) -{ - return kGiBaseDirections << cascade; -} - -uint giMortonSpread(uint value) -{ - value &= 0x0000ffffu; - value = (value | (value << 8)) & 0x00ff00ffu; - value = (value | (value << 4)) & 0x0f0f0f0fu; - value = (value | (value << 2)) & 0x33333333u; - value = (value | (value << 1)) & 0x55555555u; - return value; -} - -/// Morton ordered halves so the four children of a direction are contiguous one cascade up -uint giDirectionIndex(float2 uv, uint cascade) -{ - const uint side = giSide(cascade); - const uint x = min(uint(uv.x * float(2u * side)), 2u * side - 1u); - const uint y = min(uint(uv.y * float(side)), side - 1u); - return (x / side) * side * side + (giMortonSpread(x % side) | (giMortonSpread(y) << 1)); -} - -uint giMortonCompact(uint value) -{ - value &= 0x55555555u; - value = (value | (value >> 1)) & 0x33333333u; - value = (value | (value >> 2)) & 0x0f0f0f0fu; - value = (value | (value >> 4)) & 0x00ff00ffu; - value = (value | (value >> 8)) & 0x0000ffffu; - return value; -} - -static const float3 kGiC0DirectionsTable[32] = { - float3(0.61108887, 0.25312130, -0.75000000), - float3(0.25312130, 0.61108887, -0.75000000), - float3(0.89454251, 0.37053164, -0.25000000), - float3(0.37053164, 0.89454251, -0.25000000), - float3(-0.25312130, 0.61108887, -0.75000000), - float3(-0.61108887, 0.25312130, -0.75000000), - float3(-0.37053164, 0.89454251, -0.25000000), - float3(-0.89454251, 0.37053164, -0.25000000), - float3(0.89454251, 0.37053164, 0.25000000), - float3(0.37053164, 0.89454251, 0.25000000), - float3(0.61108887, 0.25312130, 0.75000000), - float3(0.25312130, 0.61108887, 0.75000000), - float3(-0.37053164, 0.89454251, 0.25000000), - float3(-0.89454251, 0.37053164, 0.25000000), - float3(-0.25312130, 0.61108887, 0.75000000), - float3(-0.61108887, 0.25312130, 0.75000000), - float3(-0.61108887, -0.25312130, -0.75000000), - float3(-0.25312130, -0.61108887, -0.75000000), - float3(-0.89454251, -0.37053164, -0.25000000), - float3(-0.37053164, -0.89454251, -0.25000000), - float3(0.25312130, -0.61108887, -0.75000000), - float3(0.61108887, -0.25312130, -0.75000000), - float3(0.37053164, -0.89454251, -0.25000000), - float3(0.89454251, -0.37053164, -0.25000000), - float3(-0.89454251, -0.37053164, 0.25000000), - float3(-0.37053164, -0.89454251, 0.25000000), - float3(-0.61108887, -0.25312130, 0.75000000), - float3(-0.25312130, -0.61108887, 0.75000000), - float3(0.37053164, -0.89454251, 0.25000000), - float3(0.89454251, -0.37053164, 0.25000000), - float3(0.25312130, -0.61108887, 0.75000000), - float3(0.61108887, -0.25312130, 0.75000000), -}; - -float3 giDirectionOf(uint index, uint cascade) -{ - if (cascade == 0u && index < 32u) - { - return kGiC0DirectionsTable[index]; - } - const uint side = giSide(cascade); - const uint half = index / (side * side); - const uint morton = index % (side * side); - const uint x = half * side + giMortonCompact(morton); - const uint y = giMortonCompact(morton >> 1); - return giDecodeDirection((float2(x, y) + 0.5) / float2(2u * side, side)); -} - -float2 giRayPoint(GiFrame frame, uint index) -{ - // Fixed point since a float index loses the fraction past a few hundred thousand rays - const uint2 r2 = uint2(0x80000000u, 0x80000000u) + index * uint2(3242174889u, 2447445414u); - return frac(float2(r2 >> 8) / 16777216.0 + frame.jitter.xy); -} - -int3 giSurfaceCell(GiFrame frame, float3 world, float3 normal, uint lod, uint cascade) -{ - const float3 point = world + normal * (kGiSurfaceBias * giSpacing(frame, lod, 0u)); - return giCell(point, giSpacing(frame, lod, cascade)); -} - -/// 16 bit transmittance since a small blend moves the mean in steps a byte would round away -struct GiHistory -{ - /// Red and green halves - uint redGreen; - /// Blue half then transmittance as unorm16 - uint blueTransmittance; - float rays; -}; - -/// PackHalf2x16 since f32tof16 needs shaderFloat16 which is off and clamped since overflow packs as infinity -uint giFloatToHalf(float value) -{ - const float2 clamped = float2(clamp(value, -65504.0, 65504.0), 0.0); - return spirv_asm { result:$$uint = OpExtInst glsl450 PackHalf2x16 $clamped }; -} - -/// Reads the low 16 bits of @p half -float giHalfToFloat(uint half) -{ - const float2 unpacked = spirv_asm { result:$$float2 = OpExtInst glsl450 UnpackHalf2x16 $half }; - return unpacked.x; -} - -GiHistory giPackHistory(float3 radiance, float transmittance, float rays) -{ - GiHistory history; - if (rays < kGiMinHistory) - { - history.redGreen = 0u; - history.blueTransmittance = 0u; - history.rays = 0.0; - return history; - } - history.redGreen = giFloatToHalf(radiance.r) | (giFloatToHalf(radiance.g) << 16); - history.blueTransmittance = giFloatToHalf(radiance.b) | (uint(saturate(transmittance) * 65535.0 + 0.5) << 16); - history.rays = min(rays, kGiMaxHistory); - return history; -} - -/// Transparent with @p rays 0 where nothing ever landed so the cascade above fills it in -float4 giHistoryBucket(GiHistory history, out float rays) -{ - rays = history.rays; - if (rays < kGiMinHistory) - { - rays = 0.0; - return float4(0.0, 0.0, 0.0, 1.0); - } - const float3 radiance = float3( - giHalfToFloat(history.redGreen & 0xffffu), giHalfToFloat(history.redGreen >> 16), giHalfToFloat(history.blueTransmittance & 0xffffu) - ); - return float4(radiance, float(history.blueTransmittance >> 16) / 65535.0); -} - -int3 giNeighbourOffset(uint corner) -{ - return int3(int(corner & 1u), int((corner >> 1) & 1u), int((corner >> 2) & 1u)); -} - -float giNeighbourWeight(uint corner, float3 upper) -{ - const int3 offset = giNeighbourOffset(corner); - return (offset.x != 0 ? upper.x : 1.0 - upper.x) * (offset.y != 0 ? upper.y : 1.0 - upper.y) * - (offset.z != 0 ? upper.z : 1.0 - upper.z); -} - -/// Lowest of the 8 parent cascade probes around a probe centre and the weight of the upper one per axis -void giParentNeighbourhood(int3 cell, out int3 base, out float3 upper) -{ - const int3 odd = cell & 1; - base = (cell >> 1) - (int3(1, 1, 1) - odd); - upper = float3(odd.x != 0 ? 0.25 : 0.75, odd.y != 0 ? 0.25 : 0.75, odd.z != 0 ? 0.25 : 0.75); -} - -uint giParentCorner(int3 cell) -{ - const int3 even = int3(1, 1, 1) - (cell & 1); - return uint(even.x) | (uint(even.y) << 1) | (uint(even.z) << 2); -} - float2 giOctEncode(float3 n) { n /= abs(n.x) + abs(n.y) + abs(n.z); @@ -387,32 +39,3 @@ float3 giOctDecode(float2 uv) n.y += n.y >= 0.0 ? -fold : fold; return normalize(n); } - -uint2 giTileOrigin(uint tile) -{ - return uint2(tile % kGiAtlasTilesPerRow, tile / kGiAtlasTilesPerRow) * kGiTileSize; -} - -/// Texels 1 to 7 are the interior so bilinear taps reach the border at most -float2 giTileUv(uint tile, float3 normal) -{ - const float2 texel = float2(giTileOrigin(tile)) + 1.0 + giOctEncode(normal) * float(kGiTileInterior); - return texel / kGiAtlasSize; -} - -uint giPackNormal(float3 normal) -{ - const uint2 packed = uint2(saturate(giOctEncode(normal)) * 65535.0 + 0.5); - return packed.x | (packed.y << 16); -} - -float3 giUnpackNormal(uint packed) -{ - return giOctDecode(float2(packed & 0xffffu, packed >> 16) / 65535.0); -} - -uint giSecondaryLod(GiFrame frame, float3 world) -{ - bool overlap = false; - return giLod(frame, world, overlap) + kGiSecondaryLods; -} diff --git a/engine/assets/shaders/gi_debug.slang b/engine/assets/shaders/gi_debug.slang deleted file mode 100644 index fe10d113b..000000000 --- a/engine/assets/shaders/gi_debug.slang +++ /dev/null @@ -1,228 +0,0 @@ -// Red where a pixel finds no probe -import fullscreen; -import gi_common; - -[[vk::binding(0, 0)]] -Sampler2D gSource; - -[[vk::binding(1, 0)]] -Sampler2D gDepth; - -[[vk::binding(2, 0)]] -StructuredBuffer gFrame; - -[[vk::binding(3, 0)]] -StructuredBuffer gTableKeys; - -[[vk::binding(4, 0)]] -StructuredBuffer gTableValues; - -[[vk::binding(5, 0)]] -StructuredBuffer gPool; - -[[vk::binding(6, 0)]] -Sampler2D gNormal; - -[[vk::binding(7, 0)]] -StructuredBuffer gDeposits; - -[[vk::binding(8, 0)]] -StructuredBuffer gDepositSlots; - -[[vk::binding(9, 0)]] -Sampler2D gIrradiance; - -[[vk::binding(10, 0)]] -StructuredBuffer gHistory; - -/// y smoothed share the irradiance changed per frame -[[vk::binding(11, 0)]] -StructuredBuffer gChange; - -struct GiDebugPush -{ - uint cascade; - /// Mirrors renderer::GiSettings debug_mode - uint mode; -}; - -[[vk::push_constant]] -GiDebugPush gPush; - -static const uint kGiDebugCells = 0u; -static const uint kGiDebugRadiance = 1u; -static const uint kGiDebugCoverage = 2u; -static const uint kGiDebugIrradiance = 3u; -static const uint kGiDebugDepth = 4u; -static const uint kGiDebugChange = 5u; -static const uint kGiDebugSamples = 256u; - -typedef FullscreenVSOutput VSOutput; - -[shader("vertex")] -VSOutput vertexMain(uint vertexId : SV_VertexID) -{ - return fullscreenTriangle(vertexId); -} - -uint giFind(GiFrame frame, uint cascade, int3 cell, uint lod) -{ - const GiCascadeLayout layout = frame.cascades[cascade]; - const uint key = giKey(cell, lod); - uint slot = giHash(key) & layout.y; - for (uint attempt = 0u; attempt < 32u; ++attempt) - { - const uint stored = gTableKeys[layout.x + slot]; - if (stored == key) - { - return gTableValues[layout.x + slot]; - } - if (stored == kGiEmpty) - { - return kGiEmpty; - } - slot = (slot + 1u) & layout.y; - } - return kGiEmpty; -} - -float3 giCellColour(int3 cell, uint lod) -{ - const uint hash = giHash(giKey(cell, lod) ^ 0x9e3779b9u); - return float3(float(hash & 255u), float((hash >> 8) & 255u), float((hash >> 16) & 255u)) / 255.0 * 0.8 + 0.2; -} - -/// Mean radiance of buckets with history or the share of facing buckets a ray reached this frame or their mean history -float3 giDepositColour(GiFrame frame, uint cascade, uint deposit, float3 normal) -{ - const uint4 layout = frame.deposits[cascade]; - const uint base = gDepositSlots[layout.x + deposit]; - const uint stride = max(layout.w / kGiDebugSamples, 1u); - float3 radiance = float3(0.0, 0.0, 0.0); - float filled = 0.0; - float facing = 0.0; - float covered = 0.0; - float depth = 0.0; - for (uint bucket = 0u; bucket < layout.w; bucket += stride) - { - const uint count = gDeposits[base + bucket].w & 0xffffu; - float rays = 0.0; - const float4 history = giHistoryBucket(gHistory[frame.frame.z * frame.pool.w + base + bucket], rays); - if (rays > 0.0) - { - radiance += history.rgb; - filled += 1.0; - } - if (dot(giDirectionOf(bucket, cascade), normal) > 0.25) - { - facing += 1.0; - covered += count > 0u ? 1.0 : 0.0; - depth += rays; - } - } - if (gPush.mode == kGiDebugDepth) - { - // Red no history yellow about 8 rays green 64 and up - const float share = saturate(log2(1.0 + (facing > 0.0 ? depth / facing : 0.0)) / 6.0); - return share < 0.5 ? lerp(float3(1.0, 0.1, 0.1), float3(1.0, 0.9, 0.1), share * 2.0) - : lerp(float3(1.0, 0.9, 0.1), float3(0.1, 1.0, 0.2), share * 2.0 - 1.0); - } - if (gPush.mode == kGiDebugCoverage) - { - const float share = facing > 0.0 ? covered / facing : 0.0; - return lerp(float3(1.0, 0.1, 0.1), float3(0.1, 1.0, 0.2), share); - } - const float3 mean = filled > 0.0 ? radiance / filled : float3(0.0, 0.0, 0.0); - return mean / (1.0 + mean); -} - -/// Same sparse trilinear c0 lookup lighting does -float3 giIrradianceAt(GiFrame frame, float3 world, float3 normal, uint lod, out bool found) -{ - const float spacing = giSpacing(frame, lod, 0u); - const float3 coord = (world + normal * (kGiSurfaceBias * spacing)) / spacing - 0.5; - const int3 base = int3(floor(coord)); - const float3 upper = coord - float3(base); - float3 irradiance = float3(0.0, 0.0, 0.0); - float total = 0.0; - for (uint corner = 0u; corner < 8u; ++corner) - { - const uint slot = giFind(frame, 0u, base + giNeighbourOffset(corner), lod); - if (slot == kGiEmpty || slot >= frame.cascades[0].w) - { - continue; - } - const GiProbe probe = gPool[frame.frame.z * frame.pool.x + frame.cascades[0].z + slot]; - if (probe.deposit == kGiEmpty) - { - continue; - } - const float weight = giNeighbourWeight(corner, upper); - irradiance += weight * gIrradiance.SampleLevel(giTileUv(probe.deposit, normal), 0.0).rgb; - total += weight; - } - found = total > 0.0; - return found ? irradiance / total : irradiance; -} - -[shader("fragment")] -float4 fragmentMain(VSOutput input) : SV_Target0 -{ - const int2 pixel = int2(input.position.xy); - const float4 scene = gSource.Load(int3(pixel, 0)); - const GiFrame frame = gFrame[0]; - const uint cascade = min(gPush.cascade, frame.frame.y - 1u); - const float depth = gDepth.Load(int3(pixel, 0)).r; - if (giIsSky(depth)) - { - return scene; - } - - const float2 uv = (float2(pixel) + 0.5) / float2(frame.viewport.xy); - const float3 world = giWorldAt(frame, uv, depth); - const float3 normal = giSurfaceNormal(gNormal.Load(int3(pixel, 0)), world, frame.camera.xyz); - bool overlap = false; - const uint lod = giLod(frame, world, overlap); - if (gPush.mode == kGiDebugChange) - { - // Black steady blue 1% yellow 5% red 15% and up of the irradiance changing every frame - const float change = gChange[uint(pixel.y) * frame.viewport.x + uint(pixel.x)].y; - const float3 heat = change < 0.01 ? lerp(float3(0.0, 0.0, 0.0), float3(0.1, 0.2, 1.0), change / 0.01) - : change < 0.05 ? lerp(float3(0.1, 0.2, 1.0), float3(1.0, 0.9, 0.1), (change - 0.01) / 0.04) - : lerp(float3(1.0, 0.9, 0.1), float3(1.0, 0.1, 0.1), saturate((change - 0.05) / 0.1)); - return float4(heat, scene.a); - } - if (gPush.mode == kGiDebugIrradiance) - { - bool found = false; - const float3 irradiance = giIrradianceAt(frame, world, normal, lod, found); - return float4(found ? irradiance / (1.0 + irradiance) : float3(1.0, 0.0, 0.0), scene.a); - } - const float spacing = giSpacing(frame, lod, cascade); - const int3 cell = giSurfaceCell(frame, world, normal, lod, cascade); - - const uint slot = giFind(frame, cascade, cell, lod); - float3 colour = float3(1.0, 0.0, 0.0); - if (slot != kGiEmpty && slot < frame.cascades[cascade].w) - { - const GiProbe probe = gPool[frame.frame.z * frame.pool.x + frame.cascades[cascade].z + slot]; - if (gPush.mode == kGiDebugCells) - { - colour = giCellColour(cell, lod) * (probe.lastSeen == frame.frame.x ? 1.0 : 0.35); - } - else if (probe.deposit != kGiEmpty) - { - colour = giDepositColour(frame, cascade, probe.deposit, normal); - } - else - { - // Carried or out of deposit room so no ray reached it this frame - colour = float3(0.25, 0.0, 0.3); - } - } - - const float3 inside = frac((world + normal * (kGiSurfaceBias * giSpacing(frame, lod, 0u))) / spacing); - const float edge = min(min(min(inside.x, 1.0 - inside.x), min(inside.y, 1.0 - inside.y)), min(inside.z, 1.0 - inside.z)); - colour *= edge < 0.06 ? 0.5 : 1.0; - return float4(lerp(scene.rgb, colour, gPush.mode == kGiDebugCells ? 0.6 : 0.9), scene.a); -} diff --git a/engine/assets/shaders/gi_debug.slang.meta b/engine/assets/shaders/gi_debug.slang.meta deleted file mode 100644 index 4f5bd4ad3..000000000 --- a/engine/assets/shaders/gi_debug.slang.meta +++ /dev/null @@ -1,4 +0,0 @@ -uid = "G1Debu9RC00" -type = "shader" -created_at = "2026-10-22T00:00:00.0000000Z" -modified_at = "2026-10-22T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_merge.slang b/engine/assets/shaders/gi_merge.slang deleted file mode 100644 index 8cc80f9ef..000000000 --- a/engine/assets/shaders/gi_merge.slang +++ /dev/null @@ -1,375 +0,0 @@ -// Set 0 is the engine scene only for the sky above the top cascade -import lighting; -import gi_common; -import gi_sky; - -[[vk::binding(0, 1)]] -StructuredBuffer gFrame; - -[[vk::binding(1, 1)]] -StructuredBuffer gPool; - -[[vk::binding(2, 1)]] -StructuredBuffer gDepositPool; - -[[vk::binding(3, 1)]] -StructuredBuffer gDepositSlots; - -[[vk::binding(4, 1)]] -StructuredBuffer gNeighbours; - -[[vk::binding(5, 1)]] -StructuredBuffer gDeposits; - -/// Merged radiance of every cascade above c0 at first slot / 4 as half rgb -[[vk::binding(6, 1)]] -RWStructuredBuffer gMerged; - -[[vk::binding(7, 1)]] -[[vk::image_format("rgba16f")]] -RWTexture2D gIrradiance; - -[[vk::binding(8, 1)]] -RWStructuredBuffer gCounters; - -/// Two halves by pool parity -[[vk::binding(9, 1)]] -RWStructuredBuffer gHistory; - -[[vk::binding(10, 1)]] -StructuredBuffer gHistorySource; - -/// Mirrors gi_probes.slang gDirty -[[vk::binding(11, 1)]] -StructuredBuffer gDirty; - -struct GiMergePush -{ - uint cascade; -}; - -[[vk::push_constant]] -GiMergePush gPush; - -static const uint kGiGroup = 64u; - -uint giDepositCount(GiFrame frame, uint cascade) -{ - return min(gCounters[kGiCounterSeen + cascade], frame.deposits[cascade].y); -} - -struct GiParents -{ - uint merged[8]; - float weight[8]; - float total; -}; - -GiParents giParents(GiFrame frame, uint cascade, uint deposit, bool top, out int4 probeCell) -{ - const GiProbe probe = gPool[frame.frame.z * frame.pool.x + frame.cascades[cascade].z + gDepositPool[deposit]]; - probeCell = probe.cell; - - GiParents parents; - parents.total = 0.0; - // linkMain never fills top cascade neighbours and the top merges with the sky - if (top) - { - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - parents.merged[corner] = 0u; - parents.weight[corner] = 0.0; - } - return parents; - } - - int3 base = int3(0, 0, 0); - float3 upper = float3(0.0, 0.0, 0.0); - giParentNeighbourhood(probe.cell.xyz, base, upper); - const uint4 low = gNeighbours[deposit * 2u]; - const uint4 high = gNeighbours[deposit * 2u + 1u]; - // Branch free so the eight slot loads overlap - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - const uint neighbour = corner < 4u ? low[corner] : high[corner - 4u]; - const uint slot = gDepositSlots[neighbour == kGiEmpty ? 0u : neighbour]; - const uint first = neighbour == kGiEmpty ? kGiEmpty : slot; - parents.merged[corner] = first == kGiEmpty ? 0u : first / 4u; - parents.weight[corner] = first == kGiEmpty ? 0.0 : giNeighbourWeight(corner, upper); - parents.total += parents.weight[corner]; - } - return parents; -} - -/// Black when no parent got rays since a guess of sky would leak through walls -float3 giUpper(GiParents parents, uint direction) -{ - if (parents.total <= 0.0) - { - return float3(0.0, 0.0, 0.0); - } - // Loads first so the eight overlap and a missing parent weighs 0 - uint2 merged[8]; - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - merged[corner] = gMerged[parents.merged[corner] + direction]; - } - float3 radiance = float3(0.0, 0.0, 0.0); - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - if (parents.weight[corner] > 0.0) - { - radiance += parents.weight[corner] * - float3(giHalfToFloat(merged[corner].x & 0xffffu), giHalfToFloat(merged[corner].x >> 16), giHalfToFloat(merged[corner].y)); - } - } - return radiance / parents.total; -} - -struct GiBucket -{ - uint4 value; - GiHistory old; -}; - -/// Bounded since a capture replay may not restore last frame pool -bool giCarried(GiFrame frame, uint cascade, uint2 source) -{ - return source.x != kGiEmpty && source.x <= frame.pool.w - frame.deposits[cascade].w; -} - -/// Reads the old bucket unconditionally so it loads alongside the deposit -GiBucket giLoadBucket(GiFrame frame, uint first, uint direction, uint2 source, bool carried) -{ - GiBucket bucket; - bucket.value = gDeposits[first + direction]; - bucket.old = gHistory[(1u - frame.frame.z) * frame.pool.w + (carried ? source.x : 0u) + direction]; - return bucket; -} - -bool giBucketTouchesChange(GiFrame frame, uint cascade, int4 cell, uint direction) -{ - const uint count = uint(gDirty[0].x); - if (count == 0u) - { - return false; - } - const uint lod = uint(cell.w); - const float spacing = giSpacing(frame, lod, cascade); - const float3 centre = (float3(cell.xyz) + 0.5) * spacing; - const float start = (cascade == 0u ? 0.0 : giIntervalEnd(frame, lod, cascade - 1u)) - spacing; - const float end = giIntervalEnd(frame, lod, cascade) + spacing; - const float3 axis = giDirectionOf(direction, cascade); - // Half again the bucket half angle since rays jitter across the whole bucket - const float cosine = max(1.0 - 2.0 / float(frame.deposits[cascade].w), 0.05); - const float spread = 1.5 * sqrt(1.0 - cosine * cosine) / cosine; - for (uint i = 0u; i < count; ++i) - { - const float3 low = gDirty[1u + 2u * i].xyz; - const float3 high = gDirty[2u + 2u * i].xyz; - const float radius = 0.5 * length(high - low); - const float3 offset = 0.5 * (low + high) - centre; - const float along = dot(offset, axis); - if (along + radius < start || along - radius > end) - { - continue; - } - if (length(offset - axis * along) <= radius + spacing + max(along, 0.0) * spread) - { - return true; - } - } - return false; -} - -/// keepMain flags whole probes and only buckets looking at the change drop history -float giBucketLimit(GiFrame frame, uint cascade, int4 cell, uint direction, uint2 source) -{ - const float limit = asfloat(source.y); - if (limit >= kGiMaxHistory) - { - return limit; - } - return giBucketTouchesChange(frame, cascade, cell, direction) ? limit : kGiMaxHistory; -} - -/// Unreached buckets decay only to a slower fading floor of limits.y rays -GiHistory giAccumulate(GiFrame frame, GiBucket bucket, uint2 source, bool carried, float limit) -{ - float weight = float(bucket.value.w & 0xffffu); - float3 radiance = float3(bucket.value.xyz) / frame.rays.z; - float transmittance = float(bucket.value.w >> 16) / kGiTransmittanceScale; - float rays = 0.0; - const float4 old = giHistoryBucket(bucket.old, rays); - const float held = min(rays * frame.limits.z, max(frame.limits.y - weight, 0.0)); - const float kept = carried ? min(max(rays * frame.jitter.z, held), limit) : 0.0; - radiance += old.rgb * kept; - transmittance += old.a * kept; - weight += kept; - const float inverse = weight > 0.0 ? 1.0 / weight : 0.0; - return giPackHistory(radiance * inverse, transmittance * inverse, weight); -} - -/// Every 64th @p item feeds the depth counter -void giStoreBucket(GiFrame frame, uint cascade, uint first, uint direction, uint item, GiHistory history) -{ - gHistory[frame.frame.z * frame.pool.w + first + direction] = history; - if ((item & 63u) == 0u) - { - InterlockedAdd(gCounters[kGiCounterDepth + cascade], uint(history.rays * 16.0 + 0.5)); - } -} - -/// L = R + T * L above for one bucket -float3 giMergeBucket(GiFrame frame, uint cascade, uint direction, bool top, GiParents parents, GiHistory history) -{ - float rays = 0.0; - const float4 bucket = giHistoryBucket(history, rays); - const float3 upper = top ? giSky(giDirectionOf(direction, cascade)) : giUpper(parents, direction); - return bucket.rgb + bucket.a * upper; -} - -/// One cascade above c0 per dispatch from the top down accumulating its buckets on the way -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void mergeMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - const uint4 deposits = frame.deposits[cascade]; - const uint outputs = deposits.w / 4u; - const uint total = giDepositCount(frame, cascade) * outputs; - const bool top = cascade + 1u >= frame.frame.y; - for (uint item = id.x; item < total; item += kGiStrideThreads) - { - const uint deposit = deposits.x + item / outputs; - const uint output = item % outputs; - const uint first = gDepositSlots[deposit]; - if (first == kGiEmpty) - { - continue; - } - const uint2 source = gHistorySource[deposit]; - const bool carried = giCarried(frame, cascade, source); - int4 probeCell = int4(0, 0, 0, 0); - const GiParents parents = giParents(frame, cascade, deposit, top, probeCell); - // Stores last since the compiler cannot move a load past a store that may alias it - GiBucket buckets[4]; - [unroll] - for (uint child = 0u; child < 4u; ++child) - { - buckets[child] = giLoadBucket(frame, first, output * 4u + child, source, carried); - } - GiHistory histories[4]; - float3 radiance = float3(0.0, 0.0, 0.0); - [unroll] - for (uint child = 0u; child < 4u; ++child) - { - histories[child] = - giAccumulate(frame, buckets[child], source, carried, giBucketLimit(frame, cascade, probeCell, output * 4u + child, source)); - radiance += giMergeBucket(frame, cascade, output * 4u + child, top, parents, histories[child]); - } - [unroll] - for (uint child = 0u; child < 4u; ++child) - { - const uint direction = output * 4u + child; - giStoreBucket(frame, cascade, first, direction, (item / outputs) * deposits.w + direction, histories[child]); - } - radiance *= 0.25; - gMerged[first / 4u + output] = - uint2(giFloatToHalf(radiance.r) | (giFloatToHalf(radiance.g) << 16), giFloatToHalf(radiance.b)); - } -} - -groupshared float3 gsRadiance[2][kGiC0Directions]; -groupshared bool gsWrite[2]; -groupshared GiParents gsParents[2]; -groupshared int4 gsCell[2]; - -/// Two c0 deposit probes per 8 by 8 group so every thread merges one bucket and then writes one texel of each tile -[shader("compute")] -[numthreads(kGiTileSize, kGiTileSize, 1)] -void irradianceMain(uint3 group : SV_GroupID, uint3 thread : SV_GroupThreadID, uint index : SV_GroupIndex) -{ - const GiFrame frame = gFrame[0]; - const uint count = giDepositCount(frame, 0u); - const uint pair = group.y * kGiAtlasTilesPerRow + group.x * 2u; - // Uniform across the group so the barrier below stays legal - if (pair >= count) - { - return; - } - - const uint side = index / kGiC0Directions; - const uint direction = index % kGiC0Directions; - const uint tile = pair + side; - const uint deposit = frame.deposits[0].x + tile; - const uint first = tile < count ? gDepositSlots[deposit] : kGiEmpty; - const bool top = frame.frame.y == 1u; - if (direction == 0u) - { - const bool willWrite = first != kGiEmpty; - gsWrite[side] = willWrite; - if (willWrite) - { - int4 cell = int4(0, 0, 0, 0); - gsParents[side] = giParents(frame, 0u, deposit, top, cell); - gsCell[side] = cell; - } - } - GroupMemoryBarrierWithGroupSync(); - - if (gsWrite[side]) - { - const uint2 source = gHistorySource[deposit]; - const bool carried = giCarried(frame, 0u, source); - const GiBucket bucket = giLoadBucket(frame, first, direction, source, carried); - const GiParents parents = gsParents[side]; - const GiHistory history = giAccumulate(frame, bucket, source, carried, giBucketLimit(frame, 0u, gsCell[side], direction, source)); - gsRadiance[side][direction] = giMergeBucket(frame, 0u, direction, top, parents, history); - giStoreBucket(frame, 0u, first, direction, tile * kGiC0Directions + direction, history); - } - GroupMemoryBarrierWithGroupSync(); - - // Border texels hold the interior texel mirrored across the octahedral seam so bilinear taps wrap correctly - const uint last = kGiTileSize - 1u; - const bool edgeX = thread.x == 0u || thread.x == last; - const bool edgeY = thread.y == 0u || thread.y == last; - uint2 source = thread.xy; - if (edgeX && edgeY) - { - source = uint2(thread.x == 0u ? kGiTileInterior : 1u, thread.y == 0u ? kGiTileInterior : 1u); - } - else if (edgeY) - { - source = uint2(last - thread.x, thread.y == 0u ? 1u : kGiTileInterior); - } - else if (edgeX) - { - source = uint2(thread.x == 0u ? 1u : kGiTileInterior, last - thread.y); - } - const float3 normal = giOctDecode((float2(source) - 0.5) / float(kGiTileInterior)); - - // Normalized by the discrete cosine sum so uniform radiance comes out exact with only 32 buckets - float3 irradiance[2] = { float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0) }; - float weight = 0.0; - for (uint d = 0u; d < kGiC0Directions; ++d) - { - const float cosine = max(dot(normal, kGiC0DirectionsTable[d]), 0.0); - irradiance[0] += gsRadiance[0][d] * cosine; - irradiance[1] += gsRadiance[1][d] * cosine; - weight += cosine; - } - [unroll] - for (uint s = 0u; s < 2u; ++s) - { - if (gsWrite[s]) - { - gIrradiance[giTileOrigin(pair + s) + thread.xy] = float4(weight > 0.0 ? irradiance[s] / weight : irradiance[s], 1.0); - } - } -} diff --git a/engine/assets/shaders/gi_merge.slang.meta b/engine/assets/shaders/gi_merge.slang.meta deleted file mode 100644 index ed9f1a3fe..000000000 --- a/engine/assets/shaders/gi_merge.slang.meta +++ /dev/null @@ -1,4 +0,0 @@ -uid = "G1Merg3RC00" -type = "shader" -created_at = "2026-10-22T00:00:00.0000000Z" -modified_at = "2026-10-22T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_probes.slang b/engine/assets/shaders/gi_probes.slang deleted file mode 100644 index 41840420f..000000000 --- a/engine/assets/shaders/gi_probes.slang +++ /dev/null @@ -1,601 +0,0 @@ -import gi_common; - -[[vk::binding(0, 0)]] -Sampler2D gDepth; - -[[vk::binding(1, 0)]] -StructuredBuffer gFrame; - -[[vk::binding(9, 0)]] -Sampler2D gNormal; - -/// One open addressing table per cascade rebuilt every frame -[[vk::binding(2, 0)]] -RWStructuredBuffer gTableKeys; -[[vk::binding(3, 0)]] -RWStructuredBuffer gTableFlags; -/// Index in the previous pool of a carried probe -[[vk::binding(4, 0)]] -RWStructuredBuffer gTablePrevious; -/// Index in the pool written this frame -[[vk::binding(5, 0)]] -RWStructuredBuffer gTableValues; -[[vk::binding(6, 0)]] -RWStructuredBuffer gTableCells; - -/// Two pools by parity -[[vk::binding(7, 0)]] -RWStructuredBuffer gPool; - -/// Mirrors renderer::GiPass counters -[[vk::binding(8, 0)]] -RWStructuredBuffer gCounters; - -/// Pool slot of each deposit probe -[[vk::binding(10, 0)]] -RWStructuredBuffer gDepositPool; -/// Deposit probe of the parent or kGiEmpty -[[vk::binding(11, 0)]] -RWStructuredBuffer gParent; -/// x rays y first R2 index z cursor its children take blocks from w cursor its pixels take indices from -[[vk::binding(12, 0)]] -RWStructuredBuffer gRayCounts; -/// Per direction xyz fixed point radiance w transmittance << 16 plus count -[[vk::binding(13, 0)]] -RWStructuredBuffer gDeposits; -/// First direction slot of each deposit probe or kGiEmpty when the slots ran out -[[vk::binding(14, 0)]] -RWStructuredBuffer gDepositSlots; -/// The 8 parent cascade deposit probes around each deposit probe as two uint4 in giNeighbourOffset order -[[vk::binding(15, 0)]] -RWStructuredBuffer gNeighbours; -/// x first history slot of the probe last frame or kGiEmpty y asfloat rays of history it may keep -[[vk::binding(16, 0)]] -RWStructuredBuffer gHistorySource; -/// Mirrors renderer::GiPass dirty boxes with the count in [0].x then world min and max per changed region -[[vk::binding(17, 0)]] -StructuredBuffer gDirty; -/// Two halves by pool parity -[[vk::binding(18, 0)]] -StructuredBuffer gPoints; -/// Pixels with a deposit packed x | y << 16 for the trace -[[vk::binding(19, 0)]] -RWStructuredBuffer gSpawn; - -struct GiPush -{ - uint cascade; - /// slotsMain hands out to probes seen this frame when 0 and to the carried ones after when 1 - uint carried; -}; - -[[vk::push_constant]] -GiPush gPush; - -static const uint kGiGroup = 64u; -/// Carried probes may sit this far past their LOD shell and stay well inside the 512 cell key window -static const float kGiShellSlack = 1.5; -static const uint kGiMaxProbes = 32u; - -void giInsert(GiFrame frame, uint cascade, int3 cell, uint lod, uint flags, uint previous) -{ - const GiCascadeLayout layout = frame.cascades[cascade]; - const uint key = giKey(cell, lod); - uint slot = giHash(key) & layout.y; - for (uint attempt = 0u; attempt < kGiMaxProbes; ++attempt) - { - const uint index = layout.x + slot; - uint original = 0u; - InterlockedCompareExchange(gTableKeys[index], kGiEmpty, key, original); - if (original == kGiEmpty || original == key) - { - if (original == kGiEmpty) - { - gTableCells[index] = int4(cell, int(lod)); - if (previous != kGiEmpty) - { - gTablePrevious[index] = previous; - } - } - if (flags != 0u) - { - InterlockedOr(gTableFlags[index], flags); - } - return; - } - slot = (slot + 1u) & layout.y; - } - InterlockedAdd(gCounters[kGiCounterTableFull], 1u); -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void clearMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint index = id.x; - if (index == 0u) - { - for (uint c = 0u; c < kGiMaxCascades; ++c) - { - gCounters[frame.frame.z * 8u + c] = 0u; - gCounters[kGiCounterSeen + c] = 0u; - } - gCounters[kGiCounterTableFull] = 0u; - gCounters[kGiCounterPoolFull] = 0u; - gCounters[kGiCounterDepositFull] = 0u; - gCounters[kGiCounterRays] = 0u; - gCounters[kGiCounterSlots] = 0u; - gCounters[kGiCounterInvalidated] = 0u; - gCounters[kGiCounterPoints + frame.frame.z] = 0u; - gCounters[kGiCounterPointsDropped] = 0u; - gCounters[kGiCounterFresh] = 0u; - gCounters[kGiCounterSpawn] = 0u; - gCounters[kGiCounterPixelHits] = 0u; - gCounters[kGiCounterPointHits] = 0u; - for (uint d = 0u; d < kGiMaxCascades; ++d) - { - gCounters[kGiCounterDepth + d] = 0u; - } - } - if (index >= frame.pool.y) - { - return; - } - gTableKeys[index] = kGiEmpty; - gTableFlags[index] = 0u; - gTablePrevious[index] = kGiEmpty; - gTableValues[index] = kGiEmpty; -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void carryMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - const GiCascadeLayout layout = frame.cascades[cascade]; - const uint parity = 1u - frame.frame.z; - const uint count = min(gCounters[parity * 8u + cascade], layout.w); - if (frame.frame.w == 0u || id.x >= count) - { - return; - } - const GiProbe probe = gPool[parity * frame.pool.x + layout.z + id.x]; - if (frame.frame.x - probe.lastSeen > uint(frame.lod.z)) - { - return; - } - // Outside its LOD shell around the camera now so the modulo key cannot alias a probe a whole window away - const uint lod = uint(probe.cell.w); - const float3 centre = (float3(probe.cell.xyz) + 0.5) * giSpacing(frame, lod, cascade); - const float3 offset = abs(centre - frame.camera.xyz); - if (max(offset.x, max(offset.y, offset.z)) > kGiShellSlack * frame.lod.x * float(1u << (lod + 1u))) - { - return; - } - giInsert(frame, cascade, probe.cell.xyz, uint(probe.cell.w), 0u, id.x); -} - -[shader("compute")] -[numthreads(8, 8, 1)] -void pixelMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint step = uint(frame.lod.w); - const uint2 pixel = id.xy * step + frame.viewport.zw; - if (any(pixel >= frame.viewport.xy)) - { - return; - } - const float depth = gDepth.Load(int3(pixel, 0)).r; - if (giIsSky(depth)) - { - return; - } - const float2 uv = (float2(pixel) + 0.5) / float2(frame.viewport.xy); - const float3 world = giWorldAt(frame, uv, depth); - const float3 normal = giSurfaceNormal(gNormal.Load(int3(pixel, 0)), world, frame.camera.xyz); - - bool overlap = false; - const uint lod = giLod(frame, world, overlap); - giInsert(frame, 0u, giSurfaceCell(frame, world, normal, lod, 0u), lod, kGiFlagSeen, kGiEmpty); - if (overlap) - { - giInsert(frame, 0u, giSurfaceCell(frame, world, normal, lod + 1u, 0u), lod + 1u, kGiFlagSeen, kGiEmpty); - } -} - -uint giPointCount(GiFrame frame) -{ - return min(gCounters[kGiCounterPoints + 1u - frame.frame.z], frame.secondary.w); -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void pointMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - if (id.x >= giPointCount(frame)) - { - return; - } - const GiPoint point = gPoints[(1u - frame.frame.z) * frame.secondary.x + id.x]; - const float3 normal = giUnpackNormal(point.normal); - const uint lod = giSecondaryLod(frame, point.position); - giInsert(frame, 0u, giSurfaceCell(frame, point.position, normal, lod, 0u), lod, kGiFlagSeen, kGiEmpty); -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void parentMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - const GiCascadeLayout layout = frame.cascades[cascade]; - if (id.x > layout.y) - { - return; - } - const uint index = layout.x + id.x; - if (gTableKeys[index] == kGiEmpty || (gTableFlags[index] & kGiFlagSeen) == 0u) - { - return; - } - const int4 cell = gTableCells[index]; - // Arithmetic shift so negative cells round down like floor - giInsert(frame, cascade + 1u, cell.xyz >> 1, uint(cell.w), kGiFlagSeen, kGiEmpty); -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void compactMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - const GiCascadeLayout layout = frame.cascades[cascade]; - if (id.x > layout.y) - { - return; - } - const uint index = layout.x + id.x; - if (gTableKeys[index] == kGiEmpty) - { - return; - } - - uint slot = 0u; - InterlockedAdd(gCounters[frame.frame.z * 8u + cascade], 1u, slot); - if (slot >= layout.w) - { - InterlockedAdd(gCounters[kGiCounterPoolFull], 1u); - return; - } - - const bool seen = (gTableFlags[index] & kGiFlagSeen) != 0u; - const uint previous = gTablePrevious[index]; - const uint oldBase = (1u - frame.frame.z) * frame.pool.x + layout.z; - const uint lastSeen = seen || previous == kGiEmpty ? frame.frame.x : gPool[oldBase + previous].lastSeen; - - // Probes a pixel touched get deposit storage first - uint deposit = kGiEmpty; - if (seen) - { - InterlockedAdd(gCounters[kGiCounterSeen + cascade], 1u, deposit); - if (deposit >= frame.deposits[cascade].y) - { - InterlockedAdd(gCounters[kGiCounterDepositFull], 1u); - deposit = kGiEmpty; - } - else - { - gDepositPool[frame.deposits[cascade].x + deposit] = slot; - } - } - - GiProbe probe; - probe.cell = gTableCells[index]; - probe.lastSeen = lastSeen; - probe.previous = previous; - probe.deposit = deposit; - probe.slots = kGiEmpty; - gPool[frame.frame.z * frame.pool.x + layout.z + slot] = probe; - gTableValues[index] = slot; -} - -uint giFindSlot(GiFrame frame, uint cascade, int3 cell, uint lod) -{ - const GiCascadeLayout layout = frame.cascades[cascade]; - const uint key = giKey(cell, lod); - uint slot = giHash(key) & layout.y; - for (uint attempt = 0u; attempt < kGiMaxProbes; ++attempt) - { - const uint stored = gTableKeys[layout.x + slot]; - if (stored == key) - { - const uint value = gTableValues[layout.x + slot]; - return value < layout.w ? value : kGiEmpty; - } - if (stored == kGiEmpty) - { - return kGiEmpty; - } - slot = (slot + 1u) & layout.y; - } - return kGiEmpty; -} - -uint giFindDeposit(GiFrame frame, uint cascade, int3 cell, uint lod) -{ - const uint slot = giFindSlot(frame, cascade, cell, lod); - if (slot == kGiEmpty) - { - return kGiEmpty; - } - const uint deposit = gPool[frame.frame.z * frame.pool.x + frame.cascades[cascade].z + slot].deposit; - return deposit == kGiEmpty ? kGiEmpty : frame.deposits[cascade].x + deposit; -} - -uint giDepositCount(GiFrame frame, uint cascade) -{ - return min(gCounters[kGiCounterSeen + cascade], frame.deposits[cascade].y); -} - -/// Padded a cell since the rays start anywhere on the surfaces inside it -bool giTouchesChange(GiFrame frame, uint cascade, int4 cell) -{ - const uint count = uint(gDirty[0].x); - if (count == 0u) - { - return false; - } - const uint lod = uint(cell.w); - const float spacing = giSpacing(frame, lod, cascade); - const float3 centre = (float3(cell.xyz) + 0.5) * spacing; - const float start = (cascade == 0u ? 0.0 : giIntervalEnd(frame, lod, cascade - 1u)) - spacing; - const float end = giIntervalEnd(frame, lod, cascade) + spacing; - for (uint i = 0u; i < count; ++i) - { - const float3 low = gDirty[1u + 2u * i].xyz; - const float3 high = gDirty[2u + 2u * i].xyz; - const float nearest = length(max(max(low - centre, centre - high), 0.0)); - const float farthest = length(max(abs(centre - low), abs(centre - high))); - if (nearest <= end && farthest >= start) - { - return true; - } - } - return false; -} - -/// After compact so running out never costs a visible probe -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void keepMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - const GiCascadeLayout layout = frame.cascades[cascade]; - if (id.x >= min(gCounters[frame.frame.z * 8u + cascade], layout.w)) - { - return; - } - const uint index = frame.frame.z * frame.pool.x + layout.z + id.x; - const GiProbe probe = gPool[index]; - if (probe.deposit != kGiEmpty || frame.frame.x - probe.lastSeen > kGiKeepFrames) - { - return; - } - uint deposit = 0u; - InterlockedAdd(gCounters[kGiCounterSeen + cascade], 1u, deposit); - if (deposit >= frame.deposits[cascade].y) - { - InterlockedAdd(gCounters[kGiCounterDepositFull], 1u); - return; - } - gDepositPool[frame.deposits[cascade].x + deposit] = id.x; - gPool[index].deposit = deposit; -} - -/// Top cascade first on seen probes then again on carried ones so carried probes run out first -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void slotsMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - if (id.x >= giDepositCount(frame, cascade)) - { - return; - } - const uint4 deposits = frame.deposits[cascade]; - const uint deposit = deposits.x + id.x; - const uint index = frame.frame.z * frame.pool.x + frame.cascades[cascade].z + gDepositPool[deposit]; - if ((gPool[index].lastSeen != frame.frame.x) != (gPush.carried != 0u)) - { - return; - } - gRayCounts[deposit] = uint4(0u, 0u, 0u, 0u); - gParent[deposit] = kGiEmpty; - gNeighbours[deposit * 2u] = uint4(kGiEmpty, kGiEmpty, kGiEmpty, kGiEmpty); - gNeighbours[deposit * 2u + 1u] = uint4(kGiEmpty, kGiEmpty, kGiEmpty, kGiEmpty); - - uint first = 0u; - InterlockedAdd(gCounters[kGiCounterSlots], deposits.w, first); - if (first + deposits.w > frame.pool.w) - { - // Every lookup now misses it so it gets no rays and its children merge without it - InterlockedAdd(gCounters[kGiCounterDepositFull], 1u); - gDepositSlots[deposit] = kGiEmpty; - gPool[index].deposit = kGiEmpty; - return; - } - gDepositSlots[deposit] = first; - gPool[index].slots = first; - const GiProbe probe = gPool[index]; - uint history = kGiEmpty; - if (probe.previous != kGiEmpty) - { - history = gPool[(1u - frame.frame.z) * frame.pool.x + frame.cascades[cascade].z + probe.previous].slots; - } - if (history == kGiEmpty) - { - InterlockedAdd(gCounters[kGiCounterFresh], 1u); - } - float kept = kGiMaxHistory; - if (history != kGiEmpty && giTouchesChange(frame, cascade, probe.cell)) - { - kept = frame.jitter.w; - InterlockedAdd(gCounters[kGiCounterInvalidated], 1u); - } - gHistorySource[deposit] = uint2(history, asuint(kept)); -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void depositClearMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint used = min(gCounters[kGiCounterSlots], frame.pool.w); - for (uint slot = id.x; slot < used; slot += kGiStrideThreads) - { - gDeposits[slot] = uint4(0u, 0u, 0u, 0u); - } -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void linkMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - if (id.x >= giDepositCount(frame, cascade)) - { - return; - } - const uint deposit = frame.deposits[cascade].x + id.x; - if (gDepositSlots[deposit] == kGiEmpty) - { - return; - } - const GiProbe probe = gPool[frame.frame.z * frame.pool.x + frame.cascades[cascade].z + gDepositPool[deposit]]; - const uint lod = uint(probe.cell.w); - int3 base = int3(0, 0, 0); - float3 upper = float3(0.0, 0.0, 0.0); - giParentNeighbourhood(probe.cell.xyz, base, upper); - uint neighbours[8]; - for (uint corner = 0u; corner < 8u; ++corner) - { - neighbours[corner] = giFindDeposit(frame, cascade + 1u, base + giNeighbourOffset(corner), lod); - } - gNeighbours[deposit * 2u] = uint4(neighbours[0], neighbours[1], neighbours[2], neighbours[3]); - gNeighbours[deposit * 2u + 1u] = uint4(neighbours[4], neighbours[5], neighbours[6], neighbours[7]); - gParent[deposit] = neighbours[giParentCorner(probe.cell.xyz)]; -} - -uint giPixelDeposit(GiFrame frame, uint2 pixel) -{ - const float depth = gDepth.Load(int3(pixel, 0)).r; - if (giIsSky(depth)) - { - return kGiEmpty; - } - const float2 uv = (float2(pixel) + 0.5) / float2(frame.viewport.xy); - const float3 world = giWorldAt(frame, uv, depth); - const float3 normal = giSurfaceNormal(gNormal.Load(int3(pixel, 0)), world, frame.camera.xyz); - bool overlap = false; - const uint lod = giLod(frame, world, overlap); - return giFindDeposit(frame, 0u, giSurfaceCell(frame, world, normal, lod, 0u), lod); -} - -[shader("compute")] -[numthreads(8, 8, 1)] -void countMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint2 pixel = id.xy * uint(frame.lod.w) + frame.viewport.zw; - if (any(pixel >= frame.viewport.xy)) - { - return; - } - const uint deposit = giPixelDeposit(frame, pixel); - if (deposit == kGiEmpty) - { - return; - } - uint slot = 0u; - InterlockedAdd(gCounters[kGiCounterSpawn], 1u, slot); - // Pixels past the list trace nothing so they must not claim rays - if (slot < frame.queues.x) - { - gSpawn[slot] = pixel.x | (pixel.y << 16u); - InterlockedAdd(gRayCounts[deposit].x, 1u); - } -} - -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void pointCountMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - if (id.x >= giPointCount(frame)) - { - return; - } - const GiPoint point = gPoints[(1u - frame.frame.z) * frame.secondary.x + id.x]; - const float3 normal = giUnpackNormal(point.normal); - const uint lod = giSecondaryLod(frame, point.position); - const uint deposit = giFindDeposit(frame, 0u, giSurfaceCell(frame, point.position, normal, lod, 0u), lod); - if (deposit != kGiEmpty) - { - InterlockedAdd(gRayCounts[deposit].x, 1u); - } -} - -/// Cascade by cascade upward so a parent holds the rays of all its children -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void propagateMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - if (id.x >= giDepositCount(frame, cascade)) - { - return; - } - const uint deposit = frame.deposits[cascade].x + id.x; - const uint parent = gParent[deposit]; - const uint rays = gRayCounts[deposit].x; - if (parent != kGiEmpty && rays > 0u) - { - InterlockedAdd(gRayCounts[parent].x, rays); - } -} - -/// Top down so the rays of every probe are one contiguous R2 run -[shader("compute")] -[numthreads(kGiGroup, 1, 1)] -void offsetMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint cascade = gPush.cascade; - if (id.x >= giDepositCount(frame, cascade)) - { - return; - } - const uint deposit = frame.deposits[cascade].x + id.x; - const uint rays = gRayCounts[deposit].x; - const uint parent = cascade + 1u < frame.frame.y ? gParent[deposit] : kGiEmpty; - uint offset = 0u; - if (parent == kGiEmpty) - { - InterlockedAdd(gCounters[kGiCounterRays], rays, offset); - } - else - { - uint local = 0u; - InterlockedAdd(gRayCounts[parent].z, rays, local); - offset = gRayCounts[parent].y + local; - } - gRayCounts[deposit].y = offset; -} diff --git a/engine/assets/shaders/gi_probes.slang.meta b/engine/assets/shaders/gi_probes.slang.meta deleted file mode 100644 index c0dbd64f6..000000000 --- a/engine/assets/shaders/gi_probes.slang.meta +++ /dev/null @@ -1,4 +0,0 @@ -uid = "G1Pr0besRC0" -type = "shader" -created_at = "2026-10-22T00:00:00.0000000Z" -modified_at = "2026-10-22T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_rays.slang b/engine/assets/shaders/gi_rays.slang deleted file mode 100644 index bf58cb6ab..000000000 --- a/engine/assets/shaders/gi_rays.slang +++ /dev/null @@ -1,608 +0,0 @@ -// Set 0 is the engine scene and set 1 the voxel storage with the scene trace -import voxel_dda; -import lighting; -import scene_trace; -import gi_common; -import gi_sky; -import trace_shading; -import fog_media; - -[[vk::binding(0, 2)]] -Sampler2D gDepth; - -[[vk::binding(1, 2)]] -Sampler2D gNormal; - -[[vk::binding(2, 2)]] -StructuredBuffer gFrame; - -[[vk::binding(3, 2)]] -StructuredBuffer gTableKeys; - -[[vk::binding(4, 2)]] -StructuredBuffer gTableValues; - -[[vk::binding(5, 2)]] -StructuredBuffer gPool; - -/// x rays y first R2 index z child cursor w cursor the pixels of the probe take indices from -[[vk::binding(6, 2)]] -RWStructuredBuffer gRayCounts; - -/// Per direction xyz fixed point radiance w transmittance << 16 plus count -[[vk::binding(7, 2)]] -RWStructuredBuffer gDeposits; - -[[vk::binding(8, 2)]] -StructuredBuffer gParent; - -[[vk::binding(9, 2)]] -StructuredBuffer gDepositSlots; - -/// Lit HDR scene of this frame before any post pass -[[vk::binding(10, 2)]] -Sampler2D gSceneColour; - -[[vk::binding(11, 2)]] -RWStructuredBuffer gCounters; - -/// Read from the half the last trace wrote and appended to the half of this frame -[[vk::binding(12, 2)]] -RWStructuredBuffer gPoints; - -/// c0 tiles of the last merge until this frame merges after the trace -[[vk::binding(13, 2)]] -Sampler2D gIrradiance; - -/// Per pixel x irradiance luminance last frame y smoothed change per frame z camera distance -[[vk::binding(14, 2)]] -RWStructuredBuffer gChange; - -/// Pixels countMain found with a deposit packed x | y << 16 -[[vk::binding(15, 2)]] -StructuredBuffer gSpawn; - -/// Off screen hits of pixel rays then of point rays from giPackHit for shadeMain -[[vk::binding(16, 2)]] -RWStructuredBuffer gHits; - -/// Off the surface in meters so the first voxel the ray leaves is not hit at t 0 -static const float kGiRayOffset = 0.05; -static const float kGiMaxRadiance = 16384.0; -/// Meters off the plane of the hit face the visible surface may sit and still count as the same face -static const float kGiScreenPlane = 0.025; - -/// One corner by trilinear weight skipping probes over half a cell behind the surface so light does not leak under -float3 giSecondaryIrradiance(GiFrame frame, float3 position, float3 normal, inout uint random) -{ - const uint lod = giSecondaryLod(frame, position); - const GiCascadeLayout layout = frame.cascades[0]; - const float spacing = giSpacing(frame, lod, 0u); - const float3 coord = (position + normal * (kGiSurfaceBias * spacing)) / spacing - 0.5; - const int3 base = int3(floor(coord)); - const float3 upper = coord - float3(base); - const float pick = giRandom(random); - float cumulative = 0.0; - uint first = 7u; - for (uint corner = 0u; corner < 7u; ++corner) - { - cumulative += giNeighbourWeight(corner, upper); - if (pick < cumulative) - { - first = corner; - break; - } - } - for (uint step = 0u; step < 8u; ++step) - { - const uint corner = (first + step) & 7u; - const int3 cell = base + giNeighbourOffset(corner); - if (giNeighbourWeight(corner, upper) <= 0.0 || dot((float3(cell) + 0.5) * spacing - position, normal) < -0.5 * spacing) - { - continue; - } - const uint key = giKey(cell, lod); - uint slot = giHash(key) & layout.y; - uint value = kGiEmpty; - for (uint attempt = 0u; attempt < 32u; ++attempt) - { - const uint stored = gTableKeys[layout.x + slot]; - if (stored == key || stored == kGiEmpty) - { - value = stored == key ? gTableValues[layout.x + slot] : kGiEmpty; - break; - } - slot = (slot + 1u) & layout.y; - } - if (value >= layout.w) - { - continue; - } - const uint previous = gPool[frame.frame.z * frame.pool.x + layout.z + value].previous; - if (previous == kGiEmpty) - { - continue; - } - const uint tile = gPool[(1u - frame.frame.z) * frame.pool.x + layout.z + previous].deposit; - if (tile == kGiEmpty) - { - continue; - } - return gIrradiance.SampleLevel(giTileUv(tile, normal), 0.0).rgb; - } - return float3(0.0, 0.0, 0.0); -} - -/// Rare rays onto small bright emitters flicker their bucket without a ceiling -float3 giClampRay(GiFrame frame, float3 radiance) -{ - const float luminance = dot(radiance, float3(0.2126, 0.7152, 0.0722)); - return luminance > frame.limits.x ? radiance * (frame.limits.x / luminance) : radiance; -} - -uint giFindDeposit(GiFrame frame, uint cascade, int3 cell, uint lod) -{ - const GiCascadeLayout layout = frame.cascades[cascade]; - const uint key = giKey(cell, lod); - uint slot = giHash(key) & layout.y; - for (uint attempt = 0u; attempt < 32u; ++attempt) - { - const uint stored = gTableKeys[layout.x + slot]; - if (stored == key) - { - const uint value = gTableValues[layout.x + slot]; - if (value >= layout.w) - { - return kGiEmpty; - } - const uint deposit = gPool[frame.frame.z * frame.pool.x + layout.z + value].deposit; - return deposit == kGiEmpty ? kGiEmpty : frame.deposits[cascade].x + deposit; - } - if (stored == kGiEmpty) - { - return kGiEmpty; - } - slot = (slot + 1u) & layout.y; - } - return kGiEmpty; -} - -/// False unless the pixel the hit projects to shows the same face -bool giScreenRadiance(GiFrame frame, float3 position, float3 normal, out float3 radiance) -{ - radiance = float3(0.0, 0.0, 0.0); - const float3 toCamera = gCamera.position - position; - if (dot(normal, toCamera) <= 0.0) - { - return false; - } - const float4 clip = mul(gCamera.jitteredViewProjection, float4(position, 1.0)); - if (clip.w <= 0.0) - { - return false; - } - const float2 ndc = clip.xy / clip.w; - if (any(abs(ndc) >= 1.0)) - { - return false; - } - const int2 pixel = int2((ndc * 0.5 + 0.5) * float2(frame.viewport.xy)); - const float depth = gDepth.Load(int3(pixel, 0)).r; - if (giIsSky(depth)) - { - return false; - } - // Same plane within a quarter voxel and close along it so an occluder in front or a parallel face behind fails - const float distance = length(toCamera); - const float3 visible = giWorldAt(frame, (float2(pixel) + 0.5) / float2(frame.viewport.xy), depth); - const float3 offset = visible - position; - if (abs(dot(offset, normal)) > kGiScreenPlane + 0.002 * distance || length(offset) > 0.2 + 0.02 * distance) - { - return false; - } - radiance = gSceneColour.Load(int3(pixel, 0)).rgb; - return true; -} - -/// Radiance of a ray hit that is not on screen -float3 giOffscreenRadiance(GiFrame frame, SceneHit hit, float3 position, float3 normal, uint2 pixel, inout uint random) -{ - const PaletteSample palette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); - // Shadow rays take the cone floor of the GI rays since their light is averaged over a whole bucket - float3 radiance = palette.albedo * palette.emissive + traceLocalLight(position, normal, palette.albedo, frame.rays.w, random); - if (frame.secondary.y != 0u) - { - radiance += palette.albedo * giSecondaryIrradiance(frame, position, normal, random); - } - return radiance + traceSunLight(position, normal, palette.albedo, frame.rays.w, frame.rays.y, float2(pixel)); -} - -/// x source y R2 index z asuint(t) w volume | axisCode << 22 | material << 24 with axisCode 3 for no axis -uint4 giPackHit(uint source, uint rayPoint, SceneHit hit) -{ - const uint axisCode = hit.axis < 0 ? 3u : uint(hit.axis); - const uint packed = (hit.volume & kTraceInstanceVolume) | (axisCode << 22) | ((hit.material & 0xFFu) << 24); - return uint4(source, rayPoint, asuint(hit.t), packed); -} - -/// Drops the voxel since shading reads only the volume axis and material -SceneHit giUnpackHit(uint4 packed) -{ - const uint axisCode = (packed.w >> 22) & 3u; - SceneHit hit; - hit.hit = true; - hit.t = asfloat(packed.z); - hit.volume = packed.w & kTraceInstanceVolume; - hit.voxel = int3(0, 0, 0); - hit.axis = axisCode == 3u ? -1 : int(axisCode); - hit.material = packed.w >> 24; - return hit; -} - -void giDeposit(GiFrame frame, uint cascade, uint deposit, float2 uv, float3 radiance, float transmittance) -{ - const uint first = gDepositSlots[deposit]; - if (first == kGiEmpty) - { - return; - } - const uint slot = first + giDirectionIndex(uv, cascade); - if (any(radiance > 0.0)) - { - const uint3 fixedPoint = uint3(clamp(radiance, 0.0, kGiMaxRadiance) * frame.rays.z + 0.5); - InterlockedAdd(gDeposits[slot].x, fixedPoint.x); - InterlockedAdd(gDeposits[slot].y, fixedPoint.y); - InterlockedAdd(gDeposits[slot].z, fixedPoint.z); - } - InterlockedAdd(gDeposits[slot].w, (uint(saturate(transmittance) * kGiTransmittanceScale + 0.5) << 16) | 1u); -} - -/// Fog dims each interval and the top cascade takes the sky -void giSplitRay(GiFrame frame, uint deposit, uint lod, float3 origin, float3 direction, bool hit, float distance, float3 radiance) -{ - const uint top = frame.frame.y - 1u; - const float2 uv = giEncodeDirection(direction); - float start = 0.0; - const bool hasFog = gCamera.fogMedium.x > 0.0 || fogVolumeCount() > 0u; - for (uint cascade = 0u; cascade <= top && deposit != kGiEmpty; ++cascade) - { - const float end = giIntervalEnd(frame, lod, cascade); - if (hit && distance <= end) - { - const float through = hasFog ? fogTransmittance(origin, direction, start, distance) : 1.0; - giDeposit(frame, cascade, deposit, uv, radiance * through, 0.0); - return; - } - const float through = hasFog ? fogTransmittance(origin, direction, start, end) : 1.0; - if (cascade == top) - { - giDeposit(frame, cascade, deposit, uv, giSky(direction) * through, 0.0); - return; - } - giDeposit(frame, cascade, deposit, uv, float3(0.0, 0.0, 0.0), through); - deposit = gParent[deposit]; - start = end; - } -} - -/// One probe ray of a pixel or a secondary point before its direction is picked -struct GiRay -{ - float3 origin; - float3 direction; - float3 surfaceNormal; - /// End of the traceScene interval - float reach; - uint deposit; - uint lod; - /// kGiEmpty when the pixel has no overlap or no deposit in the next lod - uint overlapDeposit; - uint rayPoint; - uint2 pixel; - uint random; -}; - -/// False for sky or a pixel without a deposit with direction and rayPoint left unset -bool giPixelRayAt(GiFrame frame, uint2 pixel, out GiRay ray) -{ - ray.origin = float3(0.0, 0.0, 0.0); - ray.direction = float3(0.0, 0.0, 0.0); - ray.surfaceNormal = float3(0.0, 0.0, 0.0); - ray.reach = 0.0; - ray.deposit = kGiEmpty; - ray.lod = 0u; - ray.overlapDeposit = kGiEmpty; - ray.rayPoint = 0u; - ray.pixel = pixel; - ray.random = 0u; - const float depth = gDepth.Load(int3(pixel, 0)).r; - if (giIsSky(depth)) - { - return false; - } - const float2 uv = (float2(pixel) + 0.5) / float2(frame.viewport.xy); - const float3 world = giWorldAt(frame, uv, depth); - const float3 normal = giSurfaceNormal(gNormal.Load(int3(pixel, 0)), world, frame.camera.xyz); - bool overlap = false; - const uint lod = giLod(frame, world, overlap); - const uint deposit = giFindDeposit(frame, 0u, giSurfaceCell(frame, world, normal, lod, 0u), lod); - if (deposit == kGiEmpty) - { - return false; - } - ray.surfaceNormal = normal; - ray.lod = lod; - ray.deposit = deposit; - ray.overlapDeposit = overlap ? giFindDeposit(frame, 0u, giSurfaceCell(frame, world, normal, lod + 1u, 0u), lod + 1u) : kGiEmpty; - ray.reach = giIntervalEnd(frame, overlap ? lod + 1u : lod, frame.frame.y - 1u); - ray.origin = world + normal * kGiRayOffset; - ray.random = giHash(pixel.x ^ giHash(pixel.y ^ giHash(frame.frame.x))); - return true; -} - -/// False for a point without a deposit with direction and rayPoint left unset -bool giPointRayAt(GiFrame frame, uint index, out GiRay ray) -{ - ray.origin = float3(0.0, 0.0, 0.0); - ray.direction = float3(0.0, 0.0, 0.0); - ray.surfaceNormal = float3(0.0, 0.0, 0.0); - ray.reach = 0.0; - ray.deposit = kGiEmpty; - ray.lod = 0u; - ray.overlapDeposit = kGiEmpty; - ray.rayPoint = 0u; - ray.pixel = uint2(index & 63u, index >> 6); - ray.random = 0u; - const GiPoint point = gPoints[(1u - frame.frame.z) * frame.secondary.x + index]; - const float3 normal = giUnpackNormal(point.normal); - const uint lod = giSecondaryLod(frame, point.position); - const uint deposit = giFindDeposit(frame, 0u, giSurfaceCell(frame, point.position, normal, lod, 0u), lod); - if (deposit == kGiEmpty) - { - return false; - } - ray.surfaceNormal = normal; - ray.lod = lod; - ray.deposit = deposit; - ray.reach = giIntervalEnd(frame, lod, frame.frame.y - 1u); - ray.origin = point.position + normal * kGiRayOffset; - ray.random = giHash(index ^ giHash(frame.frame.x ^ 0x5bd1e995u)); - return true; -} - -/// Directions flipped into the surface -void giAimRay(GiFrame frame, uint rayPoint, inout GiRay ray) -{ - ray.rayPoint = rayPoint; - const float3 direction = giDecodeDirection(giRayPoint(frame, rayPoint)); - ray.direction = dot(direction, ray.surfaceNormal) < 0.0 ? -direction : direction; -} - -[shader("compute")] -[numthreads(64, 1, 1)] -void traceMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - if (id.x >= min(gCounters[kGiCounterSpawn], frame.queues.x)) - { - return; - } - const uint packed = gSpawn[id.x]; - const uint2 pixel = uint2(packed & 0xFFFFu, packed >> 16u); - GiRay ray; - if (!giPixelRayAt(frame, pixel, ray)) - { - return; - } - - uint rayIndex = 0u; - InterlockedAdd(gRayCounts[ray.deposit].w, 1u, rayIndex); - giAimRay(frame, gRayCounts[ray.deposit].y + rayIndex, ray); - - const uint top = frame.frame.y - 1u; - const SceneHit hit = traceScene(ray.origin, ray.direction, 0.0, ray.reach, frame.rays.w); - float3 radiance = float3(0.0, 0.0, 0.0); - if (hit.hit) - { - const float3 position = ray.origin + ray.direction * hit.t; - const float3 normal = sceneHitNormal(hit, ray.direction); - if (!giScreenRadiance(frame, position, normal, radiance)) - { - // A uniform share so every region seeds instead of dispatch order filling the buffer - if (frame.secondary.y != 0u && giRandom(ray.random) < asfloat(frame.secondary.z)) - { - uint index = 0u; - InterlockedAdd(gCounters[kGiCounterPoints + frame.frame.z], 1u, index); - if (index < frame.secondary.w) - { - GiPoint point; - point.position = position; - point.normal = giPackNormal(normal); - gPoints[frame.frame.z * frame.secondary.x + index] = point; - } - else - { - InterlockedAdd(gCounters[kGiCounterPointsDropped], 1u); - } - } - // shadeMain deposits it - uint slot = 0u; - InterlockedAdd(gCounters[kGiCounterPixelHits], 1u, slot); - if (slot < frame.queues.y) - { - gHits[slot] = giPackHit(pixel.x | (pixel.y << 16u), ray.rayPoint, hit); - } - return; - } - radiance = giClampRay(frame, radiance); - } - - const bool primaryHit = hit.hit && hit.t <= giIntervalEnd(frame, ray.lod, top); - giSplitRay(frame, ray.deposit, ray.lod, ray.origin, ray.direction, primaryHit, hit.t, radiance); - if (ray.overlapDeposit != kGiEmpty) - { - giSplitRay(frame, ray.overlapDeposit, ray.lod + 1u, ray.origin, ray.direction, hit.hit, hit.t, radiance); - } -} - -[shader("compute")] -[numthreads(64, 1, 1)] -void pointTraceMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - if (id.x >= min(gCounters[kGiCounterPoints + 1u - frame.frame.z], frame.secondary.w)) - { - return; - } - GiRay ray; - if (!giPointRayAt(frame, id.x, ray)) - { - return; - } - - uint rayIndex = 0u; - InterlockedAdd(gRayCounts[ray.deposit].w, 1u, rayIndex); - giAimRay(frame, gRayCounts[ray.deposit].y + rayIndex, ray); - - const SceneHit hit = traceScene(ray.origin, ray.direction, 0.0, ray.reach, frame.rays.w); - float3 radiance = float3(0.0, 0.0, 0.0); - if (hit.hit) - { - const float3 position = ray.origin + ray.direction * hit.t; - if (!giScreenRadiance(frame, position, sceneHitNormal(hit, ray.direction), radiance)) - { - // shadeMain deposits it - uint slot = 0u; - InterlockedAdd(gCounters[kGiCounterPointHits], 1u, slot); - if (slot < frame.queues.z - frame.queues.y) - { - gHits[frame.queues.y + slot] = giPackHit(id.x, ray.rayPoint, hit); - } - return; - } - radiance = giClampRay(frame, radiance); - } - giSplitRay(frame, ray.deposit, ray.lod, ray.origin, ray.direction, hit.hit, hit.t, radiance); -} - -/// Off screen hits of both trace kernels in full warps -[shader("compute")] -[numthreads(64, 1, 1)] -void shadeMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - const uint pixelHits = min(gCounters[kGiCounterPixelHits], frame.queues.y); - const bool pixelRay = id.x < pixelHits; - const uint pointIndex = id.x - pixelHits; - if (!pixelRay && pointIndex >= min(gCounters[kGiCounterPointHits], frame.queues.z - frame.queues.y)) - { - return; - } - const uint4 packed = gHits[pixelRay ? id.x : frame.queues.y + pointIndex]; - GiRay ray; - const bool found = - pixelRay ? giPixelRayAt(frame, uint2(packed.x & 0xFFFFu, packed.x >> 16u), ray) : giPointRayAt(frame, packed.x, ray); - if (!found) - { - return; - } - giAimRay(frame, packed.y, ray); - const SceneHit hit = giUnpackHit(packed); - const float3 position = ray.origin + ray.direction * hit.t; - const float3 normal = sceneHitNormal(hit, ray.direction); - // Salted so the light pick is independent of the seeding draw of traceMain - uint random = giHash(ray.random ^ 0x68bc21ebu); - const uint top = frame.frame.y - 1u; - const bool primaryHit = !pixelRay || hit.t <= giIntervalEnd(frame, ray.lod, top); - const float3 radiance = giOffscreenRadiance(frame, hit, position, normal, ray.pixel, random); - - // Reread so the frame is not live across the traces - const GiFrame after = gFrame[0]; - const float3 clamped = giClampRay(after, radiance); - giSplitRay(after, ray.deposit, ray.lod, ray.origin, ray.direction, primaryHit, hit.t, clamped); - if (ray.overlapDeposit != kGiEmpty) - { - giSplitRay(after, ray.overlapDeposit, ray.lod + 1u, ray.origin, ray.direction, true, hit.t, clamped); - } -} - -float3 giTileIrradiance(GiFrame frame, float3 world, float3 normal, uint lod, out float total) -{ - const GiCascadeLayout layout = frame.cascades[0]; - const float spacing = giSpacing(frame, lod, 0u); - const float3 coord = (world + normal * (kGiSurfaceBias * spacing)) / spacing - 0.5; - const int3 base = int3(floor(coord)); - const float3 upper = coord - float3(base); - float3 irradiance = float3(0.0, 0.0, 0.0); - total = 0.0; - for (uint corner = 0u; corner < 8u; ++corner) - { - const float weight = giNeighbourWeight(corner, upper); - if (weight <= 0.0) - { - continue; - } - const uint key = giKey(base + giNeighbourOffset(corner), lod); - uint slot = giHash(key) & layout.y; - uint value = kGiEmpty; - for (uint attempt = 0u; attempt < 32u; ++attempt) - { - const uint stored = gTableKeys[layout.x + slot]; - if (stored == key || stored == kGiEmpty) - { - value = stored == key ? gTableValues[layout.x + slot] : kGiEmpty; - break; - } - slot = (slot + 1u) & layout.y; - } - if (value >= layout.w) - { - continue; - } - const uint tile = gPool[frame.frame.z * frame.pool.x + layout.z + value].deposit; - if (tile == kGiEmpty) - { - continue; - } - irradiance += weight * gIrradiance.SampleLevel(giTileUv(tile, normal), 0.0).rgb; - total += weight; - } - return total > 0.0 ? irradiance / total : irradiance; -} - -/// For the change debug view -[shader("compute")] -[numthreads(8, 8, 1)] -void changeMain(uint3 id : SV_DispatchThreadID) -{ - const GiFrame frame = gFrame[0]; - if (any(id.xy >= frame.viewport.xy)) - { - return; - } - const uint index = id.y * frame.viewport.x + id.x; - const float depth = gDepth.Load(int3(id.xy, 0)).r; - if (giIsSky(depth)) - { - gChange[index] = float4(0.0, 0.0, 0.0, 0.0); - return; - } - const float2 uv = (float2(id.xy) + 0.5) / float2(frame.viewport.xy); - const float3 world = giWorldAt(frame, uv, depth); - const float3 normal = giSurfaceNormal(gNormal.Load(int3(id.xy, 0)), world, frame.camera.xyz); - bool overlap = false; - const uint lod = giLod(frame, world, overlap); - float total = 0.0; - const float3 irradiance = giTileIrradiance(frame, world, normal, lod, total); - const float luminance = dot(irradiance, float3(0.2126, 0.7152, 0.0722)); - const float4 last = gChange[index]; - // A silhouette pixel lands on a different surface each jittered frame so it only counts while its surface holds - const float distance = length(world - frame.camera.xyz); - if (abs(distance - last.z) > 0.01 * distance) - { - gChange[index] = float4(luminance, last.y, distance, 0.0); - return; - } - const float change = total > 0.0 ? abs(luminance - last.x) / max(max(luminance, last.x), 1e-4) : 0.0; - gChange[index] = float4(luminance, lerp(last.y, change, 0.1), distance, 0.0); -} diff --git a/engine/assets/shaders/gi_rays.slang.meta b/engine/assets/shaders/gi_rays.slang.meta deleted file mode 100644 index 780571d7a..000000000 --- a/engine/assets/shaders/gi_rays.slang.meta +++ /dev/null @@ -1,4 +0,0 @@ -uid = "G1Rays0RC00" -type = "shader" -created_at = "2026-10-22T00:00:00.0000000Z" -modified_at = "2026-10-22T00:00:00.0000000Z" diff --git a/engine/assets/shaders/gi_sample.slang b/engine/assets/shaders/gi_sample.slang index 85b8b2c0f..7c1f1a482 100644 --- a/engine/assets/shaders/gi_sample.slang +++ b/engine/assets/shaders/gi_sample.slang @@ -1,24 +1,7 @@ -// Set 0 written by SceneDescriptorSets from GiPass +// Set 0 written by SceneDescriptorSets from GiClipmapPass import gi_common; import gi_clip_common; -/// Copied by GiPass after its merge so this is the frame the tables belong to and frame.x 0 means no GI yet -[[vk::binding(17, 0)]] -StructuredBuffer gGiFrame; - -[[vk::binding(18, 0)]] -StructuredBuffer gGiTableKeys; - -[[vk::binding(19, 0)]] -StructuredBuffer gGiTableValues; - -[[vk::binding(20, 0)]] -StructuredBuffer gGiPool; - -/// c0 octahedral tiles holding E / pi -[[vk::binding(21, 0)]] -Sampler2D gGiIrradiance; - /// Published by GiClipmapPass after its inject and size.z 0 means no clipmap GI [[vk::binding(24, 0)]] StructuredBuffer gGiClipFrame; @@ -35,149 +18,6 @@ Sampler3D gGiClipOpacity[kGiClipMaxLevels]; [[vk::binding(27, 0)]] Sampler3D gGiClipAmbient[kGiClipMaxLevels * kGiClipFaces]; -static const uint kRcMaxProbes = 32u; - -/// c0 tile per corner around @p base or kGiEmpty with each stage batched over all eight -void rcFindTiles(GiFrame frame, int3 base, uint lod, out uint tiles[8]) -{ - const GiCascadeLayout layout = frame.cascades[0]; - uint keys[8]; - uint slots[8]; - uint stored[8]; - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - keys[corner] = giKey(base + giNeighbourOffset(corner), lod); - slots[corner] = giHash(keys[corner]) & layout.y; - stored[corner] = gGiTableKeys[layout.x + slots[corner]]; - } - // Probing past the first slot is rare with the tables at most half full - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - for (uint attempt = 1u; attempt < kRcMaxProbes && stored[corner] != keys[corner] && stored[corner] != kGiEmpty; ++attempt) - { - slots[corner] = (slots[corner] + 1u) & layout.y; - stored[corner] = gGiTableKeys[layout.x + slots[corner]]; - } - } - uint values[8]; - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - values[corner] = gGiTableValues[layout.x + slots[corner]]; - } - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - const bool found = stored[corner] == keys[corner] && values[corner] < layout.w; - const uint tile = gGiPool[frame.frame.z * frame.pool.x + layout.z + (found ? values[corner] : 0u)].deposit; - tiles[corner] = found ? tile : kGiEmpty; - } -} - -/// Corner tiles around the biased point and its position between them -void rcCornersAtLod(GiFrame frame, float3 worldPosition, float3 normal, uint lod, out float3 upper, out uint tiles[8]) -{ - const float spacing = giSpacing(frame, lod, 0u); - const float3 coord = (worldPosition + normal * (kGiSurfaceBias * spacing)) / spacing - 0.5; - const int3 base = int3(floor(coord)); - upper = coord - float3(base); - rcFindTiles(frame, base, lod, tiles); -} - -/// Weight rcIrradianceAtLod would sum without its irradiance fetches -float rcCoverageAtLod(GiFrame frame, float3 worldPosition, float3 normal, uint lod) -{ - float3 upper; - uint tiles[8]; - rcCornersAtLod(frame, worldPosition, normal, lod, upper, tiles); - float total = 0.0; - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - total += tiles[corner] != kGiEmpty ? giNeighbourWeight(corner, upper) : 0.0; - } - return total; -} - -float3 rcIrradianceAtLod(GiFrame frame, float3 worldPosition, float3 normal, uint lod, out float total) -{ - float3 upper; - uint tiles[8]; - rcCornersAtLod(frame, worldPosition, normal, lod, upper, tiles); - - // Every tile is read at the same normal so the octahedral texel is shared - const float2 texel = 1.0 + giOctEncode(normal) * float(kGiTileInterior); - float3 irradiance = float3(0.0, 0.0, 0.0); - total = 0.0; - [unroll] - for (uint corner = 0u; corner < 8u; ++corner) - { - // A missing probe samples tile 0 at no weight so the eight fetches issue together - const bool found = tiles[corner] != kGiEmpty; - const float weight = found ? giNeighbourWeight(corner, upper) : 0.0; - const float2 uv = (float2(giTileOrigin(found ? tiles[corner] : 0u)) + texel) / kGiAtlasSize; - irradiance += weight * gGiIrradiance.SampleLevel(uv, 0.0).rgb; - total += weight; - } - return total > 0.0 ? irradiance / total : irradiance; -} - -/// Over pi like gIrradianceMap and false where no probe covers the point -bool sampleRadianceCascades(float3 worldPosition, float3 normal, out float3 irradiance) -{ - irradiance = float3(0.0, 0.0, 0.0); - const GiFrame frame = gGiFrame[0]; - if (frame.frame.x == 0u) - { - return false; - } - bool overlap = false; - const uint lod = giLod(frame, worldPosition, overlap); - float nearTotal = 0.0; - const float3 near = rcIrradianceAtLod(frame, worldPosition, normal, lod, nearTotal); - - float blend = 0.0; - float farTotal = 0.0; - float3 far = float3(0.0, 0.0, 0.0); - if (overlap) - { - const float3 offset = abs(worldPosition - frame.camera.xyz); - const float edge = frame.lod.x * float(1u << min(lod + 1u, 30u)); - blend = saturate((max(offset.x, max(offset.y, offset.z)) - frame.lod.y * edge) / ((1.0 - frame.lod.y) * edge)); - far = rcIrradianceAtLod(frame, worldPosition, normal, lod + 1u, farTotal); - } - if (nearTotal <= 0.0 && farTotal <= 0.0) - { - return false; - } - irradiance = nearTotal <= 0.0 ? far : (farTotal <= 0.0 ? near : lerp(near, far, blend)); - return true; -} - -/// Whether sampleRadianceCascades finds a probe at the point -bool radianceCascadesCover(float3 worldPosition, float3 normal) -{ - const GiFrame frame = gGiFrame[0]; - if (frame.frame.x == 0u) - { - return false; - } - bool overlap = false; - const uint lod = giLod(frame, worldPosition, overlap); - return rcCoverageAtLod(frame, worldPosition, normal, lod) > 0.0 || - (overlap && rcCoverageAtLod(frame, worldPosition, normal, lod + 1u) > 0.0); -} - -/// End of the c0 interval at a point so short contact rays can add what the probe spacing blurs -float radianceCascadesContactReach(float3 worldPosition) -{ - const GiFrame frame = gGiFrame[0]; - bool overlap = false; - return frame.rays.x * giSpacing(frame, giLod(frame, worldPosition, overlap), 0u); -} - /// Diameter per meter of a 60 degree cone static const float kGiClipConeSpread = 1.1547; static const uint kGiClipConeSteps = 10u; @@ -438,29 +278,15 @@ bool sampleGiClipmapCheap(float3 worldPosition, float3 normal, out float3 irradi return true; } -/// Sky share the cascades report since they hold the sky in their irradiance so no open share is left to add -/// and specular cannot tell how much of the sky map they see -static const float kGiSkyHeld = 2.0; - bool giIrradianceCheap(float3 worldPosition, float3 normal, out float3 irradiance, out float sky) { - if (sampleGiClipmapCheap(worldPosition, normal, irradiance, sky)) - { - return true; - } - sky = kGiSkyHeld; - return sampleRadianceCascades(worldPosition, normal, irradiance); + return sampleGiClipmapCheap(worldPosition, normal, irradiance, sky); } -/// The clipmap when it is published else the cascades whose @p sky is kGiSkyHeld since they hold the sky +/// False until the clipmap is published or off its outermost level bool giIrradiance(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky) { - if (sampleGiClipmap(worldPosition, normal, turn, irradiance, sky)) - { - return true; - } - sky = kGiSkyHeld; - return sampleRadianceCascades(worldPosition, normal, irradiance); + return sampleGiClipmap(worldPosition, normal, turn, irradiance, sky); } /// Irradiance over pi the clipmap already gathered at the faces around a surface point and 0 share off any surface @@ -513,28 +339,19 @@ bool sampleGiClipAmbient(float3 worldPosition, float3 normal, bool blendLevels, bool giHitIrradiance(float3 worldPosition, float3 normal, out float3 irradiance) { - if (sampleGiClipAmbient(worldPosition, normal, true, irradiance)) - { - return true; - } - return sampleRadianceCascades(worldPosition, normal, irradiance); + return sampleGiClipAmbient(worldPosition, normal, true, irradiance); } /// For reflected hits off screen where the blur of the lobe hides the step between levels bool giHitIrradianceNearest(float3 worldPosition, float3 normal, out float3 irradiance) { - if (sampleGiClipAmbient(worldPosition, normal, false, irradiance)) - { - return true; - } - return sampleRadianceCascades(worldPosition, normal, irradiance); + return sampleGiClipAmbient(worldPosition, normal, false, irradiance); } /// Bounce intensity for lit surfaces only since gi_clip_bounce feeds sampleGiClipmap back into itself float giIntensity() { - const GiClipFrame clip = gGiClipFrame[0]; - return clip.size.z != 0u ? clip.camera.w : gGiFrame[0].limits.w; + return gGiClipFrame[0].camera.w; } bool giClipCovers(float3 worldPosition) @@ -543,18 +360,10 @@ bool giClipCovers(float3 worldPosition) return frame.size.z != 0u && giClipLevelSoft(frame, worldPosition) < float(kGiClipMaxLevels); } -bool giCover(float3 worldPosition, float3 normal) -{ - return giClipCovers(worldPosition) || radianceCascadesCover(worldPosition, normal); -} - +/// Meters of contact a short ray adds below the cell the clipmap blurs at the point, valid where giClipCovers float giContactReach(float3 worldPosition) { - if (giClipCovers(worldPosition)) - { - return kGiClipConeLift * giClipCellAt(gGiClipFrame[0], worldPosition); - } - return radianceCascadesContactReach(worldPosition); + return kGiClipConeLift * giClipCellAt(gGiClipFrame[0], worldPosition); } /// Each shader calls the one it needs so it compiles only that path @@ -572,9 +381,3 @@ float4 giCheap(float3 worldPosition, float3 normal) float sky; return giIrradianceCheap(worldPosition, normal, irradiance, sky) ? float4(irradiance, sky) : float4(0.0, 0.0, 0.0, -1.0); } - -float4 giCascades(float3 worldPosition, float3 normal) -{ - float3 irradiance; - return sampleRadianceCascades(worldPosition, normal, irradiance) ? float4(irradiance, kGiSkyHeld) : float4(0.0, 0.0, 0.0, -1.0); -} diff --git a/engine/assets/shaders/gi_sky.slang b/engine/assets/shaders/gi_sky.slang deleted file mode 100644 index 854b26a8b..000000000 --- a/engine/assets/shaders/gi_sky.slang +++ /dev/null @@ -1,9 +0,0 @@ -// What a GI ray sees past the last cascade so the trace and the merge agree on it -import lighting; - -/// Matches the lighting ambient term so turning GI on keeps the sky as bright -float3 giSky(float3 direction) -{ - const float3 ambient = gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a; - return gCamera.environmentParams.x >= 0.5 ? ambient + gPrefilteredEnv.SampleLevel(direction, 0.0).rgb : ambient; -} diff --git a/engine/assets/shaders/gi_sky.slang.meta b/engine/assets/shaders/gi_sky.slang.meta deleted file mode 100644 index 72a25e6d6..000000000 --- a/engine/assets/shaders/gi_sky.slang.meta +++ /dev/null @@ -1,4 +0,0 @@ -uid = "G1Sky0RC000" -type = "shader" -created_at = "2026-10-22T00:00:00.0000000Z" -modified_at = "2026-10-22T00:00:00.0000000Z" diff --git a/engine/assets/shaders/lighting.slang b/engine/assets/shaders/lighting.slang index 3fc47855a..c52889404 100644 --- a/engine/assets/shaders/lighting.slang +++ b/engine/assets/shaders/lighting.slang @@ -565,48 +565,71 @@ float emitterExtent(float4 shapeParams) } static const float kOctagonRadiusScale = 1.0540925; -static const uint kMaxEmitterVertices = 8u; -/// Vector irradiance of a Lambert polygon relative to the receiver whose dot with N is the cosine weighted solid angle -float3 clippedPolygonVectorIrradiance(float3 vertices[kMaxEmitterVertices], uint count, float3 N) +/// Corner @p i of a quad centre plus or minus u and v, or of an octagon centre plus u cos plus v sin +float3 emitterVertex(float3 centre, float3 u, float3 v, uint count, uint i) { - float3 clipped[kMaxEmitterVertices + 2]; - float heights[kMaxEmitterVertices]; - uint kept = 0u; - for (uint i = 0u; i < count; ++i) + if (count == 4u) { - heights[i] = dot(vertices[i], N); + return centre + u * ((i == 1u || i == 2u) ? 1.0 : -1.0) + v * (i >= 2u ? 1.0 : -1.0); } - for (uint i = 0u; i < count; ++i) - { - const uint j = (i + 1u == count) ? 0u : i + 1u; - const bool inside = heights[i] >= 0.0; - if (inside) + float s, c; + sincos(0.78539816 * float(i), s, c); + return centre + u * c + v * s; +} + +float3 edgeVectorIrradiance(float3 a, float3 b) +{ + const float3 na = a / max(length(a), 1e-6); + const float3 nb = b / max(length(b), 1e-6); + const float3 edge = cross(na, nb); + const float edgeLength = length(edge); + return edgeLength > 1e-7 ? atan2(edgeLength, dot(na, nb)) * (edge / edgeLength) : float3(0.0, 0.0, 0.0); +} + +/// Vector irradiance of a Lambert polygon relative to the receiver whose dot with N is the cosine weighted solid angle +/// Clipped to the horizon one edge at a time since vertex arrays held every cluster light shader at 128 registers +float3 clippedPolygonVectorIrradiance(float3 centre, float3 u, float3 v, uint count, float3 N) +{ + float3 sum = float3(0.0, 0.0, 0.0); + // A convex polygon leaves the horizon once and comes back once, joined by one edge along it + float3 exitPoint = float3(0.0, 0.0, 0.0); + float3 entryPoint = float3(0.0, 0.0, 0.0); + bool exited = false; + bool entered = false; + const float3 first = emitterVertex(centre, u, v, count, 0u); + float3 a = first; + float heightA = dot(a, N); + for (uint i = 1u; i <= count; ++i) + { + const float3 b = i == count ? first : emitterVertex(centre, u, v, count, i); + const float heightB = dot(b, N); + if ((heightA >= 0.0) != (heightB >= 0.0)) { - clipped[kept++] = vertices[i]; + const float3 crossing = lerp(a, b, heightA / (heightA - heightB)); + if (heightA >= 0.0) + { + sum += edgeVectorIrradiance(a, crossing); + exitPoint = crossing; + exited = true; + } + else + { + sum += edgeVectorIrradiance(crossing, b); + entryPoint = crossing; + entered = true; + } } - if (inside != (heights[j] >= 0.0)) + else if (heightA >= 0.0) { - clipped[kept++] = lerp(vertices[i], vertices[j], heights[i] / (heights[i] - heights[j])); + sum += edgeVectorIrradiance(a, b); } + a = b; + heightA = heightB; } - float3 sum = float3(0.0, 0.0, 0.0); - if (kept < 3u) + if (exited && entered) { - return sum; - } - for (uint i = 0u; i < kept; ++i) - { - const float3 a = clipped[i]; - const float3 b = clipped[(i + 1u == kept) ? 0u : i + 1u]; - const float3 na = a / max(length(a), 1e-6); - const float3 nb = b / max(length(b), 1e-6); - const float3 edge = cross(na, nb); - const float edgeLength = length(edge); - if (edgeLength > 1e-7) - { - sum += atan2(edgeLength, dot(na, nb)) * (edge / edgeLength); - } + sum += edgeVectorIrradiance(exitPoint, entryPoint); } return 0.5 * sum; } @@ -648,18 +671,15 @@ AreaEmitter evaluateAreaEmitter(GpuLight light, float3 position, float3 N) const float distance = max(length(toCenter), 1e-4); const float3 centerDirection = toCenter / distance; - float3 vertices[kMaxEmitterVertices]; + // The polygon as its centre and two half axes, see emitterVertex + float3 u = float3(0.0, 0.0, 0.0); + float3 v = float3(0.0, 0.0, 0.0); uint count = 0u; if (shape == kLightShapeRect && oriented) { const float3 tangent = light.shapeTangent.xyz; - const float3 bitangent = cross(axis, tangent); - const float3 w = tangent * light.shape.y; - const float3 h = bitangent * light.shape.z; - vertices[0] = toCenter - w - h; - vertices[1] = toCenter + w - h; - vertices[2] = toCenter + w + h; - vertices[3] = toCenter - w + h; + u = tangent * light.shape.y; + v = cross(axis, tangent) * light.shape.z; count = 4u; emitter.area = 4.0 * light.shape.y * light.shape.z; } @@ -669,12 +689,8 @@ AreaEmitter evaluateAreaEmitter(GpuLight light, float3 position, float3 N) float3 bitangent; perpendicularBasis(axis, tangent, bitangent); const float radius = light.shape.y * kOctagonRadiusScale; - for (uint i = 0u; i < 8u; ++i) - { - float s, c; - sincos(0.78539816 * float(i), s, c); - vertices[i] = toCenter + (tangent * c + bitangent * s) * radius; - } + u = tangent * radius; + v = bitangent * radius; count = 8u; emitter.area = kPi * light.shape.y * light.shape.y; } @@ -688,19 +704,15 @@ AreaEmitter evaluateAreaEmitter(GpuLight light, float3 position, float3 N) float3 unused; perpendicularBasis(axis, facing, unused); } - const float3 across = cross(axis, facing) * light.shape.y; - const float3 along = axis * (light.shape.z + 0.25 * kPi * light.shape.y); - vertices[0] = toCenter - along - across; - vertices[1] = toCenter + along - across; - vertices[2] = toCenter + along + across; - vertices[3] = toCenter - along + across; + u = axis * (light.shape.z + 0.25 * kPi * light.shape.y); + v = cross(axis, facing) * light.shape.y; count = 4u; emitter.area = 4.0 * light.shape.y * light.shape.z + kPi * light.shape.y * light.shape.y; } if (count > 0u) { - float3 vector = clippedPolygonVectorIrradiance(vertices, count, N); + float3 vector = clippedPolygonVectorIrradiance(toCenter, u, v, count, N); // Either winding is accepted and the emitter lies on the side of its centre vector *= dot(vector, centerDirection) < 0.0 ? -1.0 : 1.0; emitter.irradiance = max(dot(N, vector), 0.0); @@ -826,20 +838,20 @@ static const float kWidePenumbraTexels = 6.0; static const uint kWidePenumbraTaps = 16u; -/// xyz irradiance over pi w open sky share or kGiSkyHeld from the cascades and below 0 for none since lighting never gathers on its own +/// xyz irradiance over pi w open sky share and below 0 for none since lighting never gathers on its own static float4 gGiGathered = float4(0.0, 0.0, 0.0, -1.0); bool giSurfaceIrradiance(out float3 irradiance, out float sky) { irradiance = gGiGathered.rgb; - sky = gGiGathered.w >= kGiSkyHeld ? 0.0 : gGiGathered.w; + sky = gGiGathered.w; return gGiGathered.w >= 0.0; } -/// Share of the sky map a surface reflects where the cascades hold the sky and say nothing so all of it +/// Share of the hemisphere the clipmap cones left open, which reflects the sky map float giSpecularOpen() { - return gGiGathered.w >= kGiSkyHeld ? 1.0 : saturate(gGiGathered.w); + return saturate(gGiGathered.w); } float interleavedGradientNoise(float2 pixel) @@ -1395,7 +1407,7 @@ struct ShadingResult /// Environment and probe share of specular which traced specular replaces on voxels float3 ambientSpecular; - /// Meters below which the radiance cascades blur occlusion and 0 where they did not light the point + /// Meters below which the clipmap blurs occlusion and 0 where it did not light the point float contactReach; bool isDebugView; @@ -1945,10 +1957,10 @@ ShadingResult evaluateLighting(Surface surface, ClusterC irradiance = volumeIrradiance; } - // The cascades already hold the sky and what it bounces off so they replace ambient and baked volumes + // The clipmap gather replaces baked volumes if (hasCascades) { - // The clipmap leaves the open share of the hemisphere to the ambient above and the cascades leave none + // The clipmap leaves the open share of the hemisphere to the ambient above irradiance = cascadeIrradiance * giIntensity() + cascadeSky * irradiance; // The environment map is the sky so only the open share reflects it and the closed share reflects the bounce GI found // shortcut: the bounce is cosine weighted irradiance so smooth indoor surfaces reflect it too flat, upgrade with a specular cone diff --git a/engine/assets/shaders/volumetrics.slang b/engine/assets/shaders/volumetrics.slang index f4dab83de..f98a712e5 100644 --- a/engine/assets/shaders/volumetrics.slang +++ b/engine/assets/shaders/volumetrics.slang @@ -70,7 +70,6 @@ static const float kTemporalBlend = 0.1; static const float kFogStepMeters = 0.5; static const uint kFogMinSteps = 4u; /// Marched light shadows trace on one step in this many, rotated over 2 by 2 texels and frames -static const uint kMarchedInterleave = 4u; typedef FullscreenVSOutput VSOutput; @@ -304,16 +303,19 @@ void ambientMain(uint3 group : SV_GroupID, uint index : SV_GroupIndex) } } -/// One marched light per step traces a ray since none has a shadow map +/// One marched light at one step of the whole ray traces a shadow ray since none has a shadow map, picked by contribution +/// so the single trace stays unbiased over every step and light, and the trace sits after the march loop struct MarchedPick { float total; float weight; + /// Already scaled by the step weight and scattering float3 light; + float3 origin; float3 segment; }; -void offerMarched(inout MarchedPick pick, float3 light, float3 segment, inout uint random) +void offerMarched(inout MarchedPick pick, float3 light, float3 origin, float3 segment, inout uint random) { const float weight = dot(light, float3(0.2126, 0.7152, 0.0722)); if (weight <= 0.0) @@ -325,19 +327,16 @@ void offerMarched(inout MarchedPick pick, float3 light, float3 segment, inout ui { pick.weight = weight; pick.light = light; + pick.origin = origin; pick.segment = segment; } } -/// Sun and froxel lights toward the camera with marched ones only when @p traceMarched -float3 directInScatter(float3 position, float3 toCamera, float2 pixel, float g, bool traceMarched, inout uint random) +/// Sun and froxel lights toward the camera, marched ones offered to @p pick times @p marchedWeight instead of added +float3 directInScatter(float3 position, float3 toCamera, float2 pixel, float g, float3 marchedWeight, inout MarchedPick pick, + inout uint random) { const bool shadowed = gParams.quality.z > 0.5; - MarchedPick pick; - pick.total = 0.0; - pick.weight = 0.0; - pick.light = float3(0.0, 0.0, 0.0); - pick.segment = float3(0.0, 0.0, 0.0); float3 light = float3(0.0, 0.0, 0.0); const uint casterIndex = uint(gCamera.shadowParams.x) - 1u; @@ -352,10 +351,7 @@ float3 directInScatter(float3 position, float3 toCamera, float2 pixel, float g, } else if (shadowed && sun.direction.w > 0.0) { - if (traceMarched) - { - offerMarched(pick, sunLight, L * gCamera.fogReach.z, random); - } + offerMarched(pick, sunLight * marchedWeight, position, L * gCamera.fogReach.z, random); } else { @@ -390,19 +386,12 @@ float3 directInScatter(float3 position, float3 toCamera, float2 pixel, float g, { light += localLight * volumeLocalShadow(local, position); } - else if (traceMarched) + else { - offerMarched(pick, localLight, samplePoint - position, random); + offerMarched(pick, localLight * marchedWeight, position, samplePoint - position, random); } } } - - // Scaled up since only one step in kMarchedInterleave traces - if (pick.weight > 0.0) - { - const float3 picked = pick.light * (pick.total / pick.weight) * float(kMarchedInterleave); - light += picked * traceVisibility(position, pick.segment, kFogShadowCone, false).x; - } return light; } @@ -432,12 +421,15 @@ float4 scatterMain(VSOutput input) : SV_Target0 // Short indoor rays take fewer steps const uint maxSteps = max(uint(gParams.marching.y), 1u); const uint steps = clamp(uint(ceil(span / kFogStepMeters)), min(kFogMinSteps, maxSteps), maxSteps); - const uint2 texel = uint2(input.position.xy); - const uint phase = (texel.x & 1u) + ((texel.y & 1u) << 1u) + uint(gCamera.noiseParams.z); - uint random = giHash(uint(pixel.x) ^ giHash(uint(pixel.y) ^ giHash(uint(gCamera.noiseParams.z)))); float3 scattered = float3(0.0, 0.0, 0.0); float transmittance = 1.0; + MarchedPick pick; + pick.total = 0.0; + pick.weight = 0.0; + pick.light = float3(0.0, 0.0, 0.0); + pick.origin = float3(0.0, 0.0, 0.0); + pick.segment = float3(0.0, 0.0, 0.0); for (uint i = 0u; i < steps; ++i) { // Squared so steps crowd near the camera where a shaft spans the most pixels @@ -450,19 +442,22 @@ float4 scatterMain(VSOutput input) : SV_Target0 { continue; } - // Before the shadow trace so less is live across it const float stepExtinction = exp(-medium.extinction * (far - near)); const float stepWeight = transmittance * (1.0 - stepExtinction) / medium.extinction; scattered += (medium.ambientScatter + medium.emission) * stepWeight; const float3 directWeight = medium.scattering * stepWeight; transmittance *= stepExtinction; - scattered += directWeight * - directInScatter(position, toCamera, float2(pixel), medium.anisotropy, (i + phase) % kMarchedInterleave == 0u, random); + scattered += directWeight * directInScatter(position, toCamera, float2(pixel), medium.anisotropy, directWeight, pick, random); if (transmittance < 1e-3) { break; } } + // One shadow ray for the whole ray, weighted back up by the share of every offer its pick stood for + if (pick.weight > 0.0) + { + scattered += pick.light * (pick.total / pick.weight) * traceVisibility(pick.origin, pick.segment, kFogShadowCone, false).x; + } return float4(scattered, transmittance); } diff --git a/engine/assets/shaders/voxel_denoise.slang b/engine/assets/shaders/voxel_denoise.slang index b74286158..692dc76aa 100644 --- a/engine/assets/shaders/voxel_denoise.slang +++ b/engine/assets/shaders/voxel_denoise.slang @@ -1,4 +1,4 @@ -// Temporal per term then spatial diffuse and composite of the voxel_lighting.slang noisy terms +// Temporal over both terms in one draw then spatial diffuse and composite of the voxel_lighting.slang noisy terms // Specular is temporal only since a spatial filter erases highlights import fullscreen; import depth_convention; @@ -10,7 +10,7 @@ struct DenoisePush /// Jittered since depth was rasterized with it float4x4 inverseViewProjection; float4x4 previousViewProjection; - /// x term 0 diffuse 1 specular y 1 with a valid history z spiral rotation in turns w spiral radius in pixels + /// x unused y 1 with a valid history z spiral rotation in turns w spiral radius in pixels float4 params; float4 viewport; }; @@ -54,6 +54,10 @@ Sampler2D gSpecularCurrent; [[vk::binding(10, 0)]] Sampler2D gSceneIndirect; +/// x luminance of gSceneIndirect y luminance of albedo times noisy diffuse, from temporalMain so each composite tap reads one texel +[[vk::binding(11, 0)]] +Sampler2D gLuma; + struct CompositeOutput { /// Additive into the scene colour @@ -200,20 +204,39 @@ bool reprojectHistory(float2 previousUv, float expectedDepth, out float4 diffuse return found; } +/// Both terms in one draw since they share the neighbourhood, the reprojection and the history reads +struct TemporalOutput +{ + /// rgb term a linear depth + float4 diffuse : SV_Target0; + /// rgb term a frames accumulated + float4 specular : SV_Target1; + /// See gLuma + float2 luma : SV_Target2; +}; + [shader("fragment")] -float4 temporalMain(VSOutput input) : SV_Target0 +TemporalOutput temporalMain(VSOutput input) { + TemporalOutput output; + output.diffuse = float4(0.0, 0.0, 0.0, 0.0); + output.specular = float4(0.0, 0.0, 0.0, 0.0); + output.luma = float2(0.0, 0.0); const int2 pixel = int2(input.position.xy); if (!litVoxelAt(pixel)) { - return float4(0.0, 0.0, 0.0, 0.0); + return output; } - const bool specular = gPush.params.x > 0.5; - const float3 current = noisyAt(pixel, specular); + const float3 currentDiffuse = noisyAt(pixel, false); + output.luma = float2(luminance(gSceneIndirect.Load(int3(pixel, 0)).rgb), + luminance(gAlbedo.Load(int3(pixel, 0)).rgb * currentDiffuse)); + const float3 currentSpecular = noisyAt(pixel, true); - float3 mean = float3(0.0, 0.0, 0.0); - float3 meanSquared = float3(0.0, 0.0, 0.0); + float3 meanDiffuse = float3(0.0, 0.0, 0.0); + float3 meanSquaredDiffuse = float3(0.0, 0.0, 0.0); + float3 meanSpecular = float3(0.0, 0.0, 0.0); + float3 meanSquaredSpecular = float3(0.0, 0.0, 0.0); float count = 0.0; const int2 size = int2(gPush.viewport.xy); [unroll] @@ -225,19 +248,25 @@ float4 temporalMain(VSOutput input) : SV_Target0 const int2 wanted = pixel + int2(x, y); const int2 tap = clamp(wanted, int2(0, 0), size - 1); const float weight = all(tap == wanted) && litVoxelAt(tap) ? 1.0 : 0.0; - const float3 value = noisyAt(tap, specular); - mean += value * weight; - meanSquared += value * value * weight; + const float3 diffuse = noisyAt(tap, false); + const float3 specular = noisyAt(tap, true); + meanDiffuse += diffuse * weight; + meanSquaredDiffuse += diffuse * diffuse * weight; + meanSpecular += specular * weight; + meanSquaredSpecular += specular * specular * weight; count += weight; } } - mean /= count; - const float3 sigma = sqrt(max(meanSquared / count - mean * mean, float3(0.0, 0.0, 0.0))); + meanDiffuse /= count; + meanSpecular /= count; + const float3 sigmaDiffuse = sqrt(max(meanSquaredDiffuse / count - meanDiffuse * meanDiffuse, float3(0.0, 0.0, 0.0))); + const float3 sigmaSpecular = sqrt(max(meanSquaredSpecular / count - meanSpecular * meanSpecular, float3(0.0, 0.0, 0.0))); const float depth = gDepth.Load(int3(pixel, 0)).r; const float2 uv = (float2(pixel) + 0.5) / gPush.viewport.xy; const float linearDepth = linearDepthAt(uv, depth); - const float4 reset = float4(current, specular ? 1.0 : linearDepth); + output.diffuse = float4(currentDiffuse, linearDepth); + output.specular = float4(currentSpecular, 1.0); // Camera reprojection when voxel motion is missing const float4 motion = gMotion.Load(int3(pixel, 0)); @@ -254,7 +283,7 @@ float4 temporalMain(VSOutput input) : SV_Target0 const float4 previousClip = mul(gPush.previousViewProjection, float4(world, 1.0)); if (previousClip.w <= 0.0) { - return reset; + return output; } previousUv = previousClip.xy / previousClip.w * 0.5 + 0.5; expectedDepth = previousClip.w; @@ -265,7 +294,7 @@ float4 temporalMain(VSOutput input) : SV_Target0 // Reactive pixels drop their history if (gPush.params.y < 0.5 || !inside || motion.z > 0.5) { - return reset; + return output; } // Depth lives in the diffuse history @@ -273,15 +302,17 @@ float4 temporalMain(VSOutput input) : SV_Target0 float4 specularHistory; if (!reprojectHistory(previousUv, expectedDepth, diffuseHistory, specularHistory)) { - return reset; + return output; } const float historyLength = min(max(specularHistory.a, 1.0) + 1.0, kMaxHistoryLength); - const float4 history = specular ? specularHistory : diffuseHistory; - const float clip = specular ? kSpecularClip : kDiffuseClip; - const float3 clipped = clamp(history.rgb, mean - clip * sigma, mean + clip * sigma); - const float blend = max(1.0 / historyLength, specular ? kSpecularBlend : kDiffuseBlend); - return float4(lerp(clipped, current, blend), specular ? historyLength : linearDepth); + const float3 clippedDiffuse = + clamp(diffuseHistory.rgb, meanDiffuse - kDiffuseClip * sigmaDiffuse, meanDiffuse + kDiffuseClip * sigmaDiffuse); + const float3 clippedSpecular = + clamp(specularHistory.rgb, meanSpecular - kSpecularClip * sigmaSpecular, meanSpecular + kSpecularClip * sigmaSpecular); + output.diffuse = float4(lerp(clippedDiffuse, currentDiffuse, max(1.0 / historyLength, kDiffuseBlend)), linearDepth); + output.specular = float4(lerp(clippedSpecular, currentSpecular, max(1.0 / historyLength, kSpecularBlend)), historyLength); + return output; } // Interleaved gradient noise @@ -317,8 +348,9 @@ CompositeOutput compositeMain(VSOutput input) float3 diffuse = gDiffuseCurrent.Load(int3(pixel, 0)).rgb; float weightSum = 1.0; // GI and everything noisy over the same taps since a ratio of single noisy pixels flickers - float giSum = luminance(gSceneIndirect.Load(int3(pixel, 0)).rgb); - float noisySum = luminance(albedo.rgb * gNoisyDiffuse.Load(int3(pixel, 0)).rgb); + const float2 centreLuma = gLuma.Load(int3(pixel, 0)).xy; + float giSum = centreLuma.x; + float noisySum = centreLuma.y; float s, c; sincos(rotation, s, c); const float2 turn = float2(c, s) * radius; @@ -344,8 +376,9 @@ CompositeOutput compositeMain(VSOutput input) weightSum += weight; if (weight > 0.0) { - giSum += weight * luminance(gSceneIndirect.Load(int3(tap, 0)).rgb); - noisySum += weight * luminance(gAlbedo.Load(int3(tap, 0)).rgb * gNoisyDiffuse.Load(int3(tap, 0)).rgb); + const float2 tapLuma = gLuma.Load(int3(tap, 0)).xy; + giSum += weight * tapLuma.x; + noisySum += weight * tapLuma.y; } } diffuse /= weightSum; diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index dcc634332..3664a7178 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -121,30 +121,16 @@ struct VSOutput [[vk::location(0)]] float3 worldPosition : TEXCOORD0; + // Few interpolants since attribute storage, not registers alone, limited how many glass warps launched [[vk::location(1)]] nointerpolation uint instanceIndex : TEXCOORD1; + /// Brick grid index in its volume [[vk::location(2)]] - nointerpolation int3 brick : TEXCOORD2; + nointerpolation uint brickIndex : TEXCOORD2; - // Flat per draw or linear in position so fragments skip the instance fetch [[vk::location(3)]] - nointerpolation uint volume : TEXCOORD3; - - [[vk::location(4)]] - nointerpolation uint brickEntry : TEXCOORD4; - - [[vk::location(5)]] - nointerpolation float3 voxelCamera : TEXCOORD5; - - [[vk::location(6)]] - float3 voxelPosition : TEXCOORD6; - - [[vk::location(7)]] - nointerpolation float nearOrigin : TEXCOORD7; - - [[vk::location(8)]] - float nearStep : TEXCOORD8; + nointerpolation uint brickEntry : TEXCOORD3; }; /// Back faces so a camera inside the brick still covers it @@ -178,13 +164,8 @@ VSOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID output.worldPosition = world.xyz; output.position = mul(gCamera.jitteredViewProjection, world); output.instanceIndex = entry.x; - output.brick = int3(brick); - output.volume = instance.recordIndex; + output.brickIndex = entry.y; output.brickEntry = gridEntry(record, brick); - output.voxelCamera = mul(instance.worldToVoxel, float4(gCamera.position, 1.0)).xyz; - output.voxelPosition = local; - output.nearOrigin = clipNearDistance(mul(gCamera.viewProjection, float4(gCamera.position, 1.0))); - output.nearStep = clipNearDistance(mul(gCamera.viewProjection, float4(world.xyz - gCamera.position, 0.0))); return output; } @@ -213,7 +194,7 @@ struct GlassComposite bool reflected; }; -/// Radiance a voxel ray hits shaded as voxel_specular hitRadiance shades it +/// Radiance a voxel ray hits, from the backdrop when it shows the hit and otherwise shaded as voxel_specular hitRadiance shades it bool tracedReflection(float3 position, float3 normal, float3 direction, float2 pixel, out float3 radiance) { radiance = float3(0.0, 0.0, 0.0); @@ -225,7 +206,9 @@ bool tracedReflection(float3 position, float3 normal, float3 direction, float2 p const SceneHit hit = traceScene(origin, direction, 0.0, gGlassPush.reflectionReach, pixelSlope); if (!hit.hit) { - return false; + // Grazing rays mostly run past every voxel or into meshes, which the backdrop still shows, so the environment is the last resort + return gGlassPush.depthTest != 0u && glassScreenReflection(gBackdrop, gBackdropDepth, origin, direction, gGlassPush.reflectionReach, + gGlassPush.reflectionSteps, gGlassPush.reflectionThickness, radiance); } const float3 hitPosition = origin + direction * hit.t; const float3 hitNormal = sceneHitNormal(hit, direction); @@ -234,6 +217,7 @@ bool tracedReflection(float3 position, float3 normal, float3 direction, float2 p { return true; } + // Lit per hit like voxel_specular hitRadiance since clipmap cells span several voxels and read as a blur beside the backdrop hits const PaletteSample hitPalette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); float3 irradiance; if (!giHitIrradiance(hitPosition, hitNormal, irradiance)) @@ -270,8 +254,9 @@ bool glassReflection(float3 position, float3 normal, float3 view, float roughnes } /// @p reflects swaps the environment specular for glassReflection where it hits +/// @p clustered false leaves out the cluster lights so a pane behind the nearest one only takes the suns and ambient float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, PaletteSample palette, bool reflects, - out float fresnel, out bool debugView) + bool clustered, out float fresnel, out bool debugView) { Surface surface; surface.marchedShadows = false; @@ -304,7 +289,12 @@ float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, else { NoShadowFilter none; - lit = evaluateLighting(surface, clusterCellAt(surface.viewSpaceZ, surface.pixel), none); + ClusterCell cluster = clusterCellAt(surface.viewSpaceZ, surface.pixel); + if (!clustered) + { + cluster.lightCount = 0u; + } + lit = evaluateLighting(surface, cluster, none); } debugView = lit.isDebugView; if (debugView) @@ -324,10 +314,11 @@ float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, } -/// Every glass layer front to back or with @p surfaceOnly the nearest entered surface unlit +/// Every glass layer front to back, or with SurfaceOnly 1 the nearest entered surface unlit +/// SurfaceOnly is a template so the attachment-writing passes never reference the nearest mask and depth samplers /// Surfaces reflect by Fresnel and scatter by glassScatter and the path filters by glassPathFilter /// Never shortened per voxel or the grid shows -bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) +bool compositeGlass(VSOutput input, out GlassComposite result) { result.color = float3(0.0, 0.0, 0.0); result.transmittance = float3(1.0, 1.0, 1.0); @@ -346,21 +337,24 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) return false; } - const uint volume = input.volume; - const VolumeRecord record = gVolumeRecords[volume]; - // Only surface normals read it - const float4x4 worldToVoxel = gVoxelInstances[input.instanceIndex].worldToVoxel; + const VoxelInstance instance = gVoxelInstances[input.instanceIndex]; + const VolumeRecord record = gVolumeRecords[instance.recordIndex]; + const float4x4 worldToVoxel = instance.worldToVoxel; const float3 camera = gCamera.position; - // t = 1 is the back face + // t = 1 is the rasterized face const float3 worldDirection = input.worldPosition - camera; - const float3 origin = input.voxelCamera; - const float3 direction = input.voxelPosition - input.voxelCamera; + const float3 origin = mul(worldToVoxel, float4(camera, 1.0)).xyz; + const float3 direction = mul(worldToVoxel, float4(worldDirection, 0.0)).xyz; const float3 view = -normalize(worldDirection); - const float tMin = input.nearStep > 0.0 ? max(0.0, -input.nearOrigin / input.nearStep) : 0.0; + const float nearOrigin = clipNearDistance(mul(gCamera.viewProjection, float4(camera, 1.0))); + const float nearStep = clipNearDistance(mul(gCamera.viewProjection, float4(worldDirection, 0.0))); + const float tMin = nearStep > 0.0 ? max(0.0, -nearOrigin / nearStep) : 0.0; - const int3 boxMin = input.brick * int(kBrickDim); + const uint3 brick = uint3(input.brickIndex % record.brickDimsX, (input.brickIndex / record.brickDimsX) % record.brickDimsY, + input.brickIndex / (record.brickDimsX * record.brickDimsY)); + const int3 boxMin = int3(brick) * int(kBrickDim); const int3 boxMax = boxMin + int(kBrickDim); float t = tMin; @@ -529,7 +523,7 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) } } // Behind a front pane that reflects nearly everything nothing of this brick shows, so its lit layers would only add light - if (!surfaceOnly && gGlassPush.nearestValid != 0u) + if (SurfaceOnly == 0 && gGlassPush.nearestValid != 0u) { const int3 texel = int3(int2(input.position.xy), 0); const float2 mask = gGlassMask.Load(texel).rg; @@ -561,7 +555,7 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) result.roughness = clamp(palette.roughness, 0.045, 1.0); result.f0 = iorF0(palette.ior); result.voxelPosition = origin + direction * t; - if (surfaceOnly) + if (SurfaceOnly != 0) { firstT = t; break; @@ -591,7 +585,7 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) // What the surface reflects or scatters does not pass through result.transmittance *= (1.0 - fresnel) * (1.0 - glassScatter(palette.alpha, palette.roughness)); } - else if (surfaceOnly) + else if (SurfaceOnly != 0) { // Glass continuing from a nearer brick whose own surface pass writes the surface break; @@ -622,21 +616,36 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) } } - if (!touched || (surfaceOnly && !result.entered)) + if (!touched || (SurfaceOnly != 0 && !result.entered)) { return false; } const float4 clip = mul(gCamera.viewProjection, float4(camera + worldDirection * firstT, 1.0)); result.depth = clip.z / clip.w; + // Only the nearest glass surface of the pixel takes the cluster lights and the reflection, the panes behind it are seen through + // it so they keep the suns and ambient alone. Without the pre-pass the first surface of each brick stands in. Debug views keep + // every surface on one path so the first one still shows + const float3 nearWeight = slotWeight[0]; + bool nearFirst = kSpecDebugViews == 0u && litInterfaces > 0u && max(nearWeight.x, max(nearWeight.y, nearWeight.z)) >= kContributionCutoff; + if (SurfaceOnly == 0 && nearFirst && gGlassPush.nearestValid != 0u) + { + const float slotW = mul(gCamera.viewProjection, float4(camera + worldDirection * slotT[0], 1.0)).w; + const float nearestW = glassViewDepth(gNearestGlassDepth.Load(int3(int2(input.position.xy), 0)).r); + nearFirst = slotW <= nearestW + (0.01 + 0.002 * slotW); + } + const float nearT = slotT[0]; + const uint nearKey = slotKey[0]; + // Layers behind the first in a brick that face the same way with the same palette entry lie under a brick apart so they share one lighting bool lightCached = false; int lightAxis = -1; uint lightMaterial = 0u; float3 cachedLight = float3(0.0, 0.0, 0.0); - // A real loop so the lighting is inlined once + // A real loop so the lighting is inlined once, and the nearest surface after it once the slot arrays are dead so the cluster + // lights never share registers with them [loop] - for (uint k = 0u; k < kMaxLitSurfaces; ++k) + for (uint k = nearFirst ? 1u : 0u; k < kMaxLitSurfaces; ++k) { // Picked by constant index since a slot array read at k would move the arrays to local memory float slotTk = 0.0; @@ -668,13 +677,10 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) float3 voxelNormal = float3(0.0, 0.0, 0.0); voxelNormal[slotAxisK] = direction[slotAxisK] > 0.0 ? -1.0 : 1.0; const float3 normal = normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); - // The first surface of each brick reflects so glass seen through glass shows the scene and not the bare sky, unless what - // it reflects is too dim to show past the glass in front - const bool reflects = k == 0u && max(slotWeightK.x, max(slotWeightK.y, slotWeightK.z)) * firstFresnel >= kReflectionCutoff; float fresnel; bool debugView = false; const float3 light = shadeInterface(camera + worldDirection * slotTk, normal, view, input.position.xy, - samplePalette(record, slotMaterialK), reflects, fresnel, debugView); + samplePalette(record, slotMaterialK), false, false, fresnel, debugView); if (debugView) { result.color = light; @@ -684,13 +690,27 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) } result.color += slotWeightK * light; ++result.shaded; - result.reflected = result.reflected || (reflects && kSpecReflection != kReflectionNone); - // Never a reflecting surface whose reflection belongs to it alone - lightCached = !reflects; + lightCached = true; lightAxis = slotAxisK; lightMaterial = slotMaterialK; cachedLight = light; } + + if (nearFirst) + { + const int nearAxis = int(nearKey >> 30u); + float3 voxelNormal = float3(0.0, 0.0, 0.0); + voxelNormal[nearAxis] = direction[nearAxis] > 0.0 ? -1.0 : 1.0; + const float3 normal = normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); + // What it reflects is too dim to show past the glass in front of it + const bool reflects = max(nearWeight.x, max(nearWeight.y, nearWeight.z)) * firstFresnel >= kReflectionCutoff; + float fresnel; + bool debugView = false; + result.color += nearWeight * shadeInterface(camera + worldDirection * nearT, normal, view, input.position.xy, + samplePalette(record, nearKey & 0x3FFFFFFFu), reflects, true, fresnel, debugView); + ++result.shaded; + result.reflected = result.reflected || (reflects && kSpecReflection != kReflectionNone); + } return true; } @@ -710,7 +730,7 @@ bool blendGlass(VSOutput input, out DualSourceOutput output, out float depth) { output = (DualSourceOutput)0; GlassComposite glass; - if (!compositeGlass(input, false, glass)) + if (!compositeGlass<0>(input, glass)) { depth = input.position.z; return false; @@ -822,7 +842,7 @@ bool surfaceGlass(VSOutput input, out SurfaceOutput output, out float depth, out output = (SurfaceOutput)0; frontTransmittance = 1.0; GlassComposite glass; - if (!compositeGlass(input, true, glass)) + if (!compositeGlass<1>(input, glass)) { depth = input.position.z; return false; diff --git a/engine/assets/shaders/voxel_lighting.slang b/engine/assets/shaders/voxel_lighting.slang index 414a2112a..ba662fb00 100644 --- a/engine/assets/shaders/voxel_lighting.slang +++ b/engine/assets/shaders/voxel_lighting.slang @@ -11,7 +11,7 @@ struct LightingPushConstants { // Must be jittered since depth was rasterized with it float4x4 inverseViewProjection; - // xy viewport size + // xy viewport size z 1 when gGiGather holds only the checkerboard pixels packed two to a texel, see giGatherHalf float4 viewport; // x instances with bounds y light candidates z nonzero when fragmentMarched shades w sun reach in meters uint4 lighting; @@ -87,6 +87,10 @@ Sampler2D gDetailNormal; [[vk::binding(11, 2)]] Sampler2D gGiGather; +/// Half resolution fragmentAmbientTrace occlusion at giGatherPixel and below 0 for none +[[vk::binding(12, 2)]] +Sampler2D gAmbientOcclusion; + typedef FullscreenVSOutput VSOutput; struct FSOutput @@ -808,20 +812,45 @@ SpatialOutput fragmentSpatialOpaque(VSOutput input) return spatialReuse(input, false); } +/// Kept out of line since the NVIDIA compiler gave fragmentMain 128 registers instead of 96 with the cone inlined, measured +/// with tools/shader_registers once the radiance cascades fallback that used to sit beside it was deleted +[noinline] +float4 giCheapCall(float3 position, float3 normal) +{ + return giCheap(position, normal); +} + /// Pixel of each 2x2 block the gather shades which never changes so the result holds still int2 giGatherPixel(int2 half) { return min(half * 2, int2(gPush.viewport.xy) - 1); } +bool giGatherPacked() +{ + return gPush.viewport.z > 0.5; +} + +/// Checkerboard flipping each frame since every 2 by 2 upsample still finds a diagonal pair and the history fills the rest +bool giGatherShaded(int2 half) +{ + return ((uint(half.x + half.y) + uint(gCamera.noiseParams.z)) & 1u) == 0u; +} + +/// Half resolution pixel a packed texel shades: the row keeps only its checkerboard pixels side by side +/// Packed since early outs in a fragment shader keep their warp slot, so a checkerboard over the full target saves nothing +int2 giGatherHalf(int2 packed) +{ + return int2(2 * packed.x + int((uint(packed.y) + uint(gCamera.noiseParams.z)) & 1u), packed.y); +} + [shader("fragment")] float4 fragmentGiGather(VSOutput input) : SV_Target0 { const float4 none = float4(0.0, 0.0, 0.0, -1.0); const bool denoised = (gPush.reuse.x & kGiDenoise) != 0u; - const int2 half = int2(input.position.xy); - // Checkerboard flipping each frame since every 2 by 2 upsample still finds a diagonal pair and the history fills the rest - if (denoised && ((uint(half.x + half.y) + uint(gCamera.noiseParams.z)) & 1u) != 0u) + const int2 half = giGatherPacked() ? giGatherHalf(int2(input.position.xy)) : int2(input.position.xy); + if (!giGatherPacked() && denoised && !giGatherShaded(half)) { return none; } @@ -860,7 +889,12 @@ float4 giGatherAt(int2 pixel, float3 position, float3 normal) { const int2 half = clamp(base + int2(tap & 1, tap >> 1), int2(0, 0), size - 1); source[tap] = giGatherPixel(half); - gathered[tap] = gGiGather.Load(int3(half, 0)); + gathered[tap] = gGiGather.Load(int3(giGatherPacked() ? int2(half.x >> 1, half.y) : half, 0)); + // A packed target holds no texel for the other checkerboard colour + if (giGatherPacked() && !giGatherShaded(half)) + { + gathered[tap].a = -1.0; + } sourceEncoded[tap] = gFaceNormal.Load(int3(source[tap], 0)); sourceDepth[tap] = gDepth.Load(int3(source[tap], 0)).r; } @@ -943,17 +977,13 @@ FSOutput fragmentMain(VSOutput input) surface.viewSpaceZ = mul(gCamera.view, float4(position, 1.0)).z; surface.pixel = input.position.xy; - if ((gPush.reuse.x & kGiClipmap) == 0u) - { - gGiGathered = giCascades(position, normal); - } - else + if ((gPush.reuse.x & kGiClipmap) != 0u) { gGiGathered = (gPush.reuse.x & kGiGather) != 0u ? giGatherAt(pixel, position, faceNormal) : float4(0.0, 0.0, 0.0, -1.0); // One cone for pixels with no gather pixel on their surface since a full gather here stalls the neighbourhood if (gGiGathered.w < 0.0) { - gGiGathered = giCheap(position, faceNormal); + gGiGathered = giCheapCall(position, faceNormal); } } @@ -1072,27 +1102,83 @@ MarchedOutput fragmentMarched(VSOutput input) return output; } -/// Ambient rays alone so fragmentMarched keeps fewer live registers -[shader("fragment")] -float4 fragmentAmbient(VSOutput input) : SV_Target0 +/// Occlusion of the lit voxel at @p pixel with @p noisePixel picking the ray, shared by the half resolution trace and its fallback +float ambientAt(int2 pixel, float2 noisePixel) { - const int2 pixel = int2(input.position.xy); const int3 texel = int3(pixel, 0); - if (!isLitVoxel(gAlbedo.Load(texel).a) || isShadowDebugMode(gCamera.renderModePad.x) || isSurfaceDebugMode(gCamera.renderModePad.x)) - { - discard; - } - const float3 position = positionAt(pixel); const float3 faceNormal = decodeFaceNormal(gFaceNormal.Load(texel)); const float3 sceneNormal = gSceneNormal.Load(texel).xyz; const float3 normal = dot(sceneNormal, sceneNormal) > 1e-4 ? normalize(sceneNormal) : faceNormal; - // Under the cascades the rays only add the contact detail their probe spacing blurs + // Under the clipmap the rays only add the contact detail its cells blur const float reach = float(gPush.reuse.w) * 0.01; - const float contactReach = giCover(position, normal) ? giContactReach(position) : 0.0; + const float contactReach = giClipCovers(position) ? giContactReach(position) : 0.0; const float3 shadowOrigin = position + faceNormal * (kShadowOriginOffset * kVoxelSize); - const float occlusion = ambientOcclusion(normal, input.position.xy, shadowOrigin, contactReach > 0.0 ? min(reach, contactReach) : reach); + return ambientOcclusion(normal, noisePixel, shadowOrigin, contactReach > 0.0 ? min(reach, contactReach) : reach); +} + +bool ambientSkipped(int2 pixel) +{ + return !isLitVoxel(gAlbedo.Load(int3(pixel, 0)).a) || isShadowDebugMode(gCamera.renderModePad.x) || + isSurfaceDebugMode(gCamera.renderModePad.x); +} + +/// One ray per 2x2 block at the pixel the GI gather also shades, the blue noise indexed at half resolution so it stays blue +[shader("fragment")] +float fragmentAmbientTrace(VSOutput input) : SV_Target0 +{ + const int2 pixel = giGatherPixel(int2(input.position.xy)); + return ambientSkipped(pixel) ? -1.0 : ambientAt(pixel, input.position.xy); +} + +/// Half resolution occlusion carried to every pixel on the same surface, w below 0 where no neighbour shares it +float ambientUpsampled(int2 pixel, float3 position, float3 normal) +{ + const int2 size = (int2(gPush.viewport.xy) + 1) / 2; + const float2 at = float2(pixel) * 0.5; + const int2 base = int2(floor(at)); + const float2 blend = at - float2(base); + float sum = 0.0; + float total = 0.0; + [unroll] + for (int tap = 0; tap < 4; ++tap) + { + const int2 corner = int2(tap & 1, tap >> 1); + const int2 half = clamp(base + corner, int2(0, 0), size - 1); + const int2 source = giGatherPixel(half); + const float occlusion = gAmbientOcclusion.Load(int3(half, 0)).r; + const float4 sourceEncoded = gFaceNormal.Load(int3(source, 0)); + if (occlusion < 0.0 || sourceEncoded.a <= 0.5) + { + continue; + } + const float2 side = lerp(1.0 - blend, blend, float2(corner)); + const float facing = saturate(dot(normal, decodeFaceNormal(sourceEncoded))); + const float plane = saturate(1.0 - abs(dot(positionAt(source) - position, normal)) / kGiGatherPlane); + const float weight = (side.x * side.y + 0.01) * facing * facing * facing * facing * plane; + sum += occlusion * weight; + total += weight; + } + return total > 1e-4 ? sum / total : -1.0; +} + +/// Ambient rays alone so fragmentMarched keeps fewer live registers, traced at half resolution and upsampled here +/// A pixel with no neighbour on its surface traces its own ray so thin edges keep their contact shadow +[shader("fragment")] +float4 fragmentAmbient(VSOutput input) : SV_Target0 +{ + const int2 pixel = int2(input.position.xy); + if (ambientSkipped(pixel)) + { + discard; + } + const float3 faceNormal = decodeFaceNormal(gFaceNormal.Load(int3(pixel, 0))); + float occlusion = ambientUpsampled(pixel, positionAt(pixel), faceNormal); + if (occlusion < 0.0) + { + occlusion = ambientAt(pixel, input.position.xy); + } // Premultiplied so the indirect fragmentMain left in noisy diffuse scales by occlusion return float4(0.0, 0.0, 0.0, 1.0 - occlusion); } diff --git a/engine/assets/shaders/voxel_specular.slang b/engine/assets/shaders/voxel_specular.slang index 9a489633f..f7fab9162 100644 --- a/engine/assets/shaders/voxel_specular.slang +++ b/engine/assets/shaders/voxel_specular.slang @@ -84,6 +84,14 @@ Sampler2D gHiz; [[vk::binding(15, 2)]] Sampler2D gFiltered; +/// x asuint(t) y kHitShade where traceMain left a voxel hit for shadeMain +[[vk::binding(16, 2)]] +Sampler2D gHit; + +static const uint kHitShade = 1u; +/// Meters either side of the stored hit shadeMain traces again to find its voxel +static const float kHitRefind = 0.25; + /// Mirrors voxel_lighting.slang static const float kTracedMark = 2.0; static const float kVoxelSize = 0.1; @@ -431,33 +439,75 @@ uint4 surfaceMain(VSOutput input) : SV_Target0 return packSurface(surface, stratum); } +/// The ray of a half resolution texel, shared so shadeMain rebuilds exactly the ray traceMain cast instead of storing it +struct SpecularRay +{ + float3 origin; + float3 direction; + /// Rough lobes blur what they hit so their marches take a cone floor + float coneSlope; + /// Each stratum ray covers its share of the lobe so its screen hit reads a matching blur + float rayTan; +}; + +SpecularRay specularRay(TracedPixel surface, int2 texel) +{ + // Quantized like the resolve regenerates it + const uint4 packed = gSurface.Load(int3(texel, 0)); + float pdf; + SpecularRay ray; + ray.direction = rayDirection(unpackSurface(packed, surface.face), lobeStratumSample(packedStratum(packed)), pdf); + ray.coneSlope = 0.25 * surface.roughness * surface.roughness; + ray.origin = surface.position + surface.face * (kOriginOffset * kVoxelSize); + ray.rayTan = surface.roughness > kMirrorRoughness ? lobeTanHalf(surface.roughness) / sqrt(float(kLobeStrata)) : 0.0; + return ray; +} + +/// Frame in the seed so history averages the light pick instead of freezing it +uint hitRandom(int2 texel) +{ + return giHash((uint(texel.x) | (uint(texel.y) << 16)) ^ giHash(uint(gCamera.noiseParams.z))); +} + +struct TraceOutput +{ + float4 trace : SV_Target0; + /// See gHit, zero unless shadeMain lights this texel + uint4 hit : SV_Target1; +}; + +TraceOutput traceResult(float4 trace) +{ + TraceOutput output; + output.trace = trace; + output.hit = uint4(0u, 0u, 0u, 0u); + return output; +} + /// A miss returns the environment term lighting would have added +/// A voxel hit is left to shadeMain so the trace never holds the hit lighting registers [shader("fragment")] -float4 traceMain(VSOutput input) : SV_Target0 +TraceOutput traceMain(VSOutput input) { const int2 pixel = int2(input.position.xy) * 2; const TracedPixel surface = tracedPixelAt(pixel); if (!surface.traced) { - return float4(0.0, 0.0, 0.0, kNoTrace); + return traceResult(float4(0.0, 0.0, 0.0, kNoTrace)); } const int2 texel = int2(input.position.xy); - // Quantized like the resolve regenerates it - const uint4 packed = gSurface.Load(int3(texel, 0)); - float pdf; - const float3 L = rayDirection(unpackSurface(packed, surface.face), lobeStratumSample(packedStratum(packed)), pdf); + const SpecularRay ray = specularRay(surface, texel); + const float3 L = ray.direction; const float3 mirror = reflect(-normalize(gCamera.position - surface.position), surface.normal); if (dot(L, surface.face) <= 0.0) { - return float4(ambientSpecularRadiance(surface.position, mirror, surface.roughness), kMissDistance); + return traceResult(float4(ambientSpecularRadiance(surface.position, mirror, surface.roughness), kMissDistance)); } - // Rough lobes blur what they hit so their marches take a cone floor - const float coneSlope = 0.25 * surface.roughness * surface.roughness; - const float3 origin = surface.position + surface.face * (kOriginOffset * kVoxelSize); - // Each stratum ray covers its share of the lobe so its screen hit reads a matching blur - const float rayTan = surface.roughness > kMirrorRoughness ? lobeTanHalf(surface.roughness) / sqrt(float(kLobeStrata)) : 0.0; + const float coneSlope = ray.coneSlope; + const float3 origin = ray.origin; + const float rayTan = ray.rayTan; // Screen first so a hit the depth buffer shows skips the voxel trace and the hit lighting if (gParams.march.y > 0.5) @@ -484,7 +534,7 @@ float4 traceMain(VSOutput input) : SV_Target0 if (dot(gSceneNormal.Load(int3(hitPixel, 0)).xyz, L) < 0.0) { const float t = length(hitPosition - origin); - return float4(screenColour(hitPixel, length(gCamera.position - hitPosition), 2.0 * rayTan * t), t); + return traceResult(float4(screenColour(hitPixel, length(gCamera.position - hitPosition), 2.0 * rayTan * t), t)); } } } @@ -492,11 +542,37 @@ float4 traceMain(VSOutput input) : SV_Target0 const SceneHit hit = traceScene(origin, L, 0.0, gParams.tracing.x, coneSlope); if (!hit.hit) { + return traceResult(float4(ambientSpecularRadiance(surface.position, mirror, surface.roughness), kMissDistance)); + } + // The distance alone since carrying the volume, material and axis through the walk cost 16 registers + TraceOutput output = traceResult(float4(0.0, 0.0, 0.0, hit.t)); + output.hit = uint4(asuint(hit.t), kHitShade, 0u, 0u); + return output; +} + +/// Lights the voxel hits traceMain left over the trace it wrote, a pass of its own so neither holds the other's registers +[shader("fragment")] +float4 shadeMain(VSOutput input) : SV_Target0 +{ + const int2 texel = int2(input.position.xy); + const uint2 record = gHit.Load(int3(texel, 0)).xy; + if ((record.y & kHitShade) == 0u) + { + discard; + } + const int2 pixel = texel * 2; + const TracedPixel surface = tracedPixelAt(pixel); + const SpecularRay ray = specularRay(surface, texel); + // Everything before the stored distance is empty and the cone floor grows from t 0, so the short walk lands on the same voxel + const float t = asfloat(record.x); + const SceneHit hit = traceScene(ray.origin, ray.direction, max(t - kHitRefind, 0.0), t + kHitRefind, ray.coneSlope); + if (!hit.hit) + { + const float3 mirror = reflect(-normalize(gCamera.position - surface.position), surface.normal); return float4(ambientSpecularRadiance(surface.position, mirror, surface.roughness), kMissDistance); } - // Frame in the seed so history averages the light pick instead of freezing it - uint random = giHash((uint(texel.x) | (uint(texel.y) << 16)) ^ giHash(uint(gCamera.noiseParams.z))); - return float4(hitRadiance(hit, origin, L, coneSlope, rayTan, float2(pixel), random), hit.t); + uint random = hitRandom(texel); + return float4(hitRadiance(hit, ray.origin, ray.direction, ray.coneSlope, ray.rayTan, float2(pixel), random), hit.t); } float specularLuma(float3 colour) diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 0d5c7119b..411308916 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -35,7 +35,6 @@ #include "toast/renderer/passes/geometry/voxel_pass.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" #include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" -#include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/passes/lighting/reflection_probe_pass.hpp" #include "toast/renderer/passes/lighting/shadow_pass.hpp" #include "toast/renderer/passes/lighting/ssao_pass.hpp" @@ -126,9 +125,7 @@ auto addScenePasses( // World-stage passes render into the HDR scene target const auto scene_format = renderer.getSceneColorFormat(); - // Before the passes whose scene sets bind its cascades - auto gi_pass = std::make_unique(core, scene_format, extent); - renderer.setGiPass(gi_pass.get()); + // Before the passes whose scene sets bind its clipmap auto gi_clipmap_pass = std::make_unique(core, scene_format, extent); renderer.setGiClipmapPass(gi_clipmap_pass.get()); @@ -142,7 +139,6 @@ auto addScenePasses( renderer.addRenderPass(std::make_unique(core, scene_format, depth_format, extent)); // First in the chain so the probes read depth before any post pass - renderer.addPostProcessPass(std::move(gi_pass)); renderer.addPostProcessPass(std::move(gi_clipmap_pass)); if (core.isRayTracingSupported()) { @@ -232,6 +228,8 @@ Engine::Engine() noexcept { * Initialize in Engine::init() instead, unless it genuinely cannot wait. * This runs before the working directory is set and before the project exists, * so only the logger and the thread pool it depends on belong here. + * toasty tosted is tost + * all toasters tost toast * - xein <3 */ } @@ -706,7 +704,7 @@ void Engine::createSDLWindow(const char* w_name) { // Compile every stale shader up front renderer::ShaderCompiler::setFullOptimization(true); - renderer::ShaderCompiler::setMaxParallelCompiles(std::clamp(std::thread::hardware_concurrency(), 2, 8)); + renderer::ShaderCompiler::setMaxParallelCompiles(std::clamp(std::thread::hardware_concurrency(), 2, 16)); { StartupSplash splash; renderer::ShaderCache::get().compileAllAtStartup([&splash](const renderer::ShaderCache::StartupProgress& progress) { @@ -778,7 +776,18 @@ void Engine::createAvaloniaWindow() { m->vulkan_core = std::make_unique(std::span {}, std::span {}); - renderer::ShaderCache::get().compileAllAtStartup(); + // Compile every stale shader up front + renderer::ShaderCompiler::setFullOptimization(false); + renderer::ShaderCompiler::setMaxParallelCompiles(std::clamp(std::thread::hardware_concurrency(), 2, 16)); + { + StartupSplash splash; + renderer::ShaderCache::get().compileAllAtStartup([&splash](const renderer::ShaderCache::StartupProgress& progress) { + splash.update(progress.finished, progress.total, progress.compiling); + }); + if (splash.closeRequested()) { + event::send(); + } + } auto output_target = std::make_unique(*m->vulkan_core, vk::Extent2D(1080, 720)); auto color_format = output_target->getColorFormat(); diff --git a/engine/src/toast/renderer/core/gpu_timer.hpp b/engine/src/toast/renderer/core/gpu_timer.hpp index 8e865534d..557cbef3a 100644 --- a/engine/src/toast/renderer/core/gpu_timer.hpp +++ b/engine/src/toast/renderer/core/gpu_timer.hpp @@ -17,7 +17,7 @@ class VulkanCore; /// @note Render thread only class GpuTimer { public: - static constexpr uint32_t k_max_scopes = 64; + static constexpr uint32_t k_max_scopes = 96; static constexpr uint32_t k_no_scope = ~uint32_t {0}; /// Copied since a pass can be destroyed before its frame is read back diff --git a/engine/src/toast/renderer/core/vulkan_common.hpp b/engine/src/toast/renderer/core/vulkan_common.hpp index 0d58997b1..4da9d1885 100644 --- a/engine/src/toast/renderer/core/vulkan_common.hpp +++ b/engine/src/toast/renderer/core/vulkan_common.hpp @@ -50,6 +50,8 @@ inline constexpr vk::Format k_voxel_noisy_format = vk::Format::eB10G11R11UfloatP inline constexpr vk::Format k_voxel_denoised_indirect_format = vk::Format::eR16G16B16A16Sfloat; /// Half resolution clipmap gather with a signed alpha marking pixels that gathered nothing inline constexpr vk::Format k_voxel_gi_format = vk::Format::eR16G16B16A16Sfloat; +/// voxel_lighting.slang gAmbientOcclusion, half resolution with below 0 for none +inline constexpr vk::Format k_voxel_ao_format = vk::Format::eR16Sfloat; /// voxel_lighting.slang packReservoir inline constexpr vk::Format k_voxel_reservoir_format = vk::Format::eR32G32B32A32Uint; diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index 35f1f3aaa..2e52a1d0b 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -449,10 +449,28 @@ void VulkanCore::createInstance(std::span required_instance_e std::vector layers; #ifdef DEBUG if (m_validation_enabled) { - // layers.push_back("VK_LAYER_KHRONOS_validation"); + layers.push_back("VK_LAYER_KHRONOS_validation"); } #endif + // TOAST_CRASH_DIAGNOSTIC=1 loads the LunarG crash diagnostic layer in any build to dump in-flight work after a device lost + if (const char* crash_env = std::getenv("TOAST_CRASH_DIAGNOSTIC"); + crash_env != nullptr && crash_env[0] != '\0' && crash_env[0] != '0') { + constexpr const char* k_crash_layer = "VK_LAYER_LUNARG_crash_diagnostic"; + const auto available = m_context.enumerateInstanceLayerProperties(); + const bool found = std::ranges::any_of(available, [&](const vk::LayerProperties& layer) { + return std::string_view(layer.layerName) == k_crash_layer; + }); + if (!found) { + TOAST_WARN("Render", "TOAST_CRASH_DIAGNOSTIC is set but {} is not installed (needs the Vulkan SDK)", k_crash_layer); + } else if (const auto debugger = vulkanCoreAttachedGraphicsDebugger(); debugger.has_value()) { + TOAST_WARN("Render", "{} is attached so the crash diagnostic layer stays off", *debugger); + } else { + layers.push_back(k_crash_layer); + TOAST_INFO("Render", "Crash diagnostic layer: enabled"); + } + } + std::vector extensions(required_instance_extensions.begin(), required_instance_extensions.end()); m_debug_utils_enabled = checkInstanceExtensionSupport(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); if (m_debug_utils_enabled) { @@ -495,6 +513,10 @@ void VulkanCore::createInstance(std::span required_instance_e // GPU assisted validation with only the ray query checks on since the rest instruments every shader constexpr VkBool32 k_on = VK_TRUE; constexpr VkBool32 k_off = VK_FALSE; + // TOAST_GPUAV_FULL=1 turns on the out-of-bounds checks behind most device lost crashes, at a large shader cost + const char* gpuav_full_env = std::getenv("TOAST_GPUAV_FULL"); + const bool gpuav_full = gpuav_full_env != nullptr && gpuav_full_env[0] != '\0' && gpuav_full_env[0] != '0'; + const VkBool32 k_full = gpuav_full ? VK_TRUE : VK_FALSE; const auto setting = [](const char* name, const VkBool32& value) { return vk::LayerSettingEXT("VK_LAYER_KHRONOS_validation", name, vk::LayerSettingTypeEXT::eBool32, 1, &value); }; @@ -503,17 +525,19 @@ void VulkanCore::createInstance(std::span required_instance_e setting("gpuav_shader_instrumentation", k_on), setting("gpuav_validate_ray_query", k_on), setting("gpuav_descriptor_checks", k_on), - setting("gpuav_post_process_descriptor_indexing", k_off), - setting("gpuav_buffer_address_oob", k_off), + setting("gpuav_post_process_descriptor_indexing", k_full), + setting("gpuav_buffer_address_oob", k_full), setting("gpuav_mesh_shading", k_on), setting("gpuav_validate_trace_ray", k_on), - setting("gpuav_vertex_attribute_fetch_oob", k_off), - setting("gpuav_shader_sanitizer", k_off), + setting("gpuav_vertex_attribute_fetch_oob", k_full), + setting("gpuav_shader_sanitizer", k_full), setting("gpuav_shared_memory_data_race", k_off), - setting("gpuav_buffers_validation", k_off), + setting("gpuav_buffers_validation", k_full), + // Skips the per-access storage and uniform bounds checks the layer warns make shaders very slow, robust accesses cannot fault + setting("gpuav_force_on_robustness", k_on), }; vk::LayerSettingsCreateInfoEXT layer_settings(gpuav_settings); - if (m_validation_enabled && validate_ray_query) { + if (m_validation_enabled && (validate_ray_query || gpuav_full)) { layer_settings.pNext = instance_ci.pNext; instance_ci.pNext = &layer_settings; } @@ -591,7 +615,7 @@ void VulkanCore::activateNsightGpuTraceIfNeeded() const { if (m_nsight_mode != NsightMode::gpu_trace || m_nsight_gputrace_activated) { return; } - NGFX_GPUTrace_ActivateTrace_Vulkan_Params params {NGFX_GPUTrace_ActivateTrace_Vulkan_Params_VER}; + NGFX_GPUTrace_ActivateTrace_Vulkan_Params params {.version = NGFX_GPUTrace_ActivateTrace_Vulkan_Params_VER}; params.queue = m_graphics_queue; if (NGFX_GPUTrace_ActivateTrace_Vulkan(¶ms) == NGFX_Result_Success) { @@ -980,6 +1004,27 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re } } + // Opt in since capturing statistics slows every pipeline compile + if (/*const char* stats = std::getenv("TOAST_PIPELINE_STATS"); stats != nullptr && stats[0] == '1'*/ true) { + const auto available = m_physical_device.enumerateDeviceExtensionProperties(); + const bool extension_present = std::ranges::any_of(available, [](const vk::ExtensionProperties& ext) { + return std::string_view(ext.extensionName.data()) == VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME; + }); + if (extension_present) { + vk::PhysicalDeviceFeatures2 probe {}; + vk::PhysicalDevicePipelineExecutablePropertiesFeaturesKHR stats_probe {}; + probe.pNext = &stats_probe; + (*m_physical_device).getFeatures2(&probe); + m_pipeline_stats_enabled = stats_probe.pipelineExecutableInfo == VK_TRUE; + } + if (m_pipeline_stats_enabled) { + device_extensions.push_back(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME); + TOAST_INFO("Render", "TOAST_PIPELINE_STATS: every pipeline logs its driver statistics"); + } else { + TOAST_WARN("Render", "TOAST_PIPELINE_STATS set but the driver lacks pipelineExecutableInfo"); + } + } + if (m_dlss_reason.empty()) { constexpr uint32_t k_vendor_nvidia = 0x10DE; const auto props = m_physical_device.getProperties(); @@ -1021,6 +1066,8 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re vk::PhysicalDeviceFrameBoundaryFeaturesEXT frame_boundary_features {}; frame_boundary_features.frameBoundary = VK_TRUE; + vk::PhysicalDevicePipelineExecutablePropertiesFeaturesKHR pipeline_stats_features {}; + pipeline_stats_features.pipelineExecutableInfo = VK_TRUE; vk::PhysicalDeviceVulkan12Features vulkan12_features {}; vk::PhysicalDeviceVulkan13Features vulkan13_features {}; vk::PhysicalDeviceVulkan11Features vulkan11_features {}; @@ -1055,6 +1102,10 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re *chain_tail = &shading_rate_features; chain_tail = &shading_rate_features.pNext; } + if (m_pipeline_stats_enabled) { + *chain_tail = &pipeline_stats_features; + chain_tail = &pipeline_stats_features.pNext; + } if (m_ray_tracing_supported) { *chain_tail = &acceleration_structure_features; acceleration_structure_features.pNext = &ray_query_features; diff --git a/engine/src/toast/renderer/core/vulkan_core.hpp b/engine/src/toast/renderer/core/vulkan_core.hpp index 11d6e9efc..28328f258 100644 --- a/engine/src/toast/renderer/core/vulkan_core.hpp +++ b/engine/src/toast/renderer/core/vulkan_core.hpp @@ -140,6 +140,13 @@ class VulkanCore { return m_fragment_shading_rate_supported; } + /// TOAST_PIPELINE_STATS=1 and VK_KHR_pipeline_executable_properties: every pipeline logs its driver statistics such as + /// registers + [[nodiscard]] + auto isPipelineStatsEnabled() const noexcept -> bool { + return m_pipeline_stats_enabled; + } + /// Every instance and device extension NGX asked for is enabled, DlssUpscaler still has to initialise NGX [[nodiscard]] auto dlssExtensionsEnabled() const noexcept -> bool { @@ -329,6 +336,7 @@ class VulkanCore { RayTracingMode m_ray_tracing_startup_mode {}; bool m_mesh_shader_supported = false; bool m_fragment_shading_rate_supported = false; + bool m_pipeline_stats_enabled = false; std::string_view m_ray_tracing_reason = "not probed"; uint32_t m_mesh_multiview_views = 0; diff --git a/engine/src/toast/renderer/passes/debug/perf_window.cpp b/engine/src/toast/renderer/passes/debug/perf_window.cpp index b7cd9ebad..8c9cf10e3 100644 --- a/engine/src/toast/renderer/passes/debug/perf_window.cpp +++ b/engine/src/toast/renderer/passes/debug/perf_window.cpp @@ -10,7 +10,6 @@ #include "toast/renderer/core/vulkan_core.hpp" #include "toast/renderer/lighting/shadow_constants.hpp" #include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" -#include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/settings/renderer_settings.hpp" #include "toast/renderer/shaders/shader_compiler.hpp" @@ -1005,89 +1004,6 @@ void PerfWindow::drawSceneTab() { ImGui::EndTable(); } } - - const GiPass* gi = VulkanRenderer::instance->giPass(); - if (gi == nullptr || !gi->isEnabled()) { - return; - } - ImGui::SeparatorText("Radiance cascades"); - const GiPass::Stats stats = gi->stats(); - constexpr std::array k_quality_names {"Low", "Medium", "High", "Epic", "Custom"}; - const char* quality_name = k_quality_names[std::min(stats.quality, k_quality_names.size() - 1)]; - if (stats.point_budget > 0) { - ImGui::Text( - "Quality %s, ray step %u, update every %u frames, %u multibounce points", - quality_name, - stats.ray_step, - stats.update_interval, - stats.point_budget - ); - } else { - ImGui::Text( - "Quality %s, ray step %u, update every %u frames, multibounce off", quality_name, stats.ray_step, stats.update_interval - ); - } - if (ImGui::BeginTable("##perf_gi", 6, ImGuiTableFlags_SizingFixedFit)) { - ImGui::TableSetupColumn("Cascade"); - ImGui::TableSetupColumn("Probes"); - ImGui::TableSetupColumn("Active"); - ImGui::TableSetupColumn("Pool"); - ImGui::TableSetupColumn("Deposits"); - ImGui::TableSetupColumn("Depth"); - ImGui::TableHeadersRow(); - for (uint32_t i = 0; i < stats.cascades && i < GiPass::k_max_cascades; ++i) { - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::Text("c%u", i); - ImGui::TableNextColumn(); - ImGui::Text("%u", stats.probes[i]); - ImGui::TableNextColumn(); - ImGui::Text("%u", stats.seen[i]); - ImGui::TableNextColumn(); - ImGui::Text( - "%.0f%%", - stats.capacity[i] > 0 ? 100.0f * static_cast(stats.probes[i]) / static_cast(stats.capacity[i]) : 0.0f - ); - ImGui::TableNextColumn(); - ImGui::Text("%u of %u", stats.deposits[i], stats.deposit_capacity[i]); - ImGui::TableNextColumn(); - ImGui::Text("%.1f rays", stats.depth[i]); - } - ImGui::EndTable(); - } - ImGui::Text( - "%u rays, %u of %u direction slots (%.0f%%)", - stats.rays, - stats.slots, - GiPass::k_deposit_slots, - 100.0f * static_cast(stats.slots) / static_cast(GiPass::k_deposit_slots) - ); - ImGui::Text( - "Changes: %u moved, %u new, %u edits reset %u probes. Largest motion %.2f mm", - stats.moved, - stats.appeared, - stats.edits, - stats.invalidated, - stats.largest_motion * 1000.0f - ); - ImGui::Text("History: %.1f%% new light a frame, %u probes started without any this frame", stats.blend * 100.0f, stats.fresh); - ImGui::Text( - "Multibounce: %u off screen hits seeded the secondary cache, %.0f%% offered (%u dropped)", - stats.points, - stats.point_share * 100.0f, - stats.points_dropped - ); - if (stats.deposit_full > 0) { - ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%u seen probes got no deposit room and no rays", stats.deposit_full); - } - if (stats.table_full > 0 || stats.pool_full > 0) { - ImGui::TextColored( - ImVec4(1.0f, 0.5f, 0.3f, 1.0f), - "Dropped %u insertions on full tables and %u on full pools", - stats.table_full, - stats.pool_full - ); - } } void PerfWindow::drawShadowsTab() { diff --git a/engine/src/toast/renderer/passes/debug/selection_outline.cpp b/engine/src/toast/renderer/passes/debug/selection_outline.cpp index bef24518a..0c495d068 100644 --- a/engine/src/toast/renderer/passes/debug/selection_outline.cpp +++ b/engine/src/toast/renderer/passes/debug/selection_outline.cpp @@ -222,8 +222,8 @@ void SelectionOutline::createMaskPipelines(vk::Extent2D extent) { mesh.vertex_entry = "meshVertex"; mesh.fragment_entry = "meshFragment"; mesh.vertex_bindings = {vertexBindingDescription()}; - const auto vertex_attributes = vertexAttributeDescriptions(); - mesh.vertex_attributes.assign(vertex_attributes.begin(), vertex_attributes.end()); + // Position only, the mask shader reads nothing else + mesh.vertex_attributes = {vertexAttributeDescriptions()[0]}; // Mirrored and single sided meshes still cover their silhouette mesh.cull_mode = vk::CullModeFlagBits::eNone; m_mesh_pipeline.rebuild(*m_core, mesh); diff --git a/engine/src/toast/renderer/passes/geometry/depth_prepass.cpp b/engine/src/toast/renderer/passes/geometry/depth_prepass.cpp index 948b562fe..9fc0fca2a 100644 --- a/engine/src/toast/renderer/passes/geometry/depth_prepass.cpp +++ b/engine/src/toast/renderer/passes/geometry/depth_prepass.cpp @@ -33,8 +33,8 @@ DepthPrepass::DepthPrepass(const VulkanCore& core, vk::Format depth_format, vk:: config.shader_spirv = shader->spirv; config.pipeline_layout = *m_shader_layout.getPipelineLayout(); config.vertex_bindings = {vertexBindingDescription()}; - const auto vertex_attributes = vertexAttributeDescriptions(); - config.vertex_attributes.assign(vertex_attributes.begin(), vertex_attributes.end()); + // Position only, the shader reads nothing else + config.vertex_attributes = {vertexAttributeDescriptions()[0]}; config.cull_mode = vk::CullModeFlagBits::eBack; config.depth_test = true; config.depth_write = true; diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index 8ae6852fb..4e1f94b2b 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -527,6 +527,14 @@ void VoxelPass::createLighting(const VulkanCore& core, vk::Format scene_format, config.extra_color_formats = {}; config.extra_blend_mask = 0u; m_ambient_pipeline.rebuild(core, config); + { + VulkanPipeline::Config trace = config; + trace.debug_name = "VoxelAmbientTrace"; + trace.fragment_entry = "fragmentAmbientTrace"; + trace.color_format = k_voxel_ao_format; + trace.blend_preset = VulkanPipeline::BlendPreset::none; + m_ambient_trace_pipeline.rebuild(core, trace); + } config.debug_name = "VoxelMarchedComposite"; config.fragment_entry = "fragmentMarchedComposite"; @@ -985,8 +993,7 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { // Debug views and probe captures skip the denoiser const bool capture = frame->probe_capture_index >= 0 || frame->irradiance_capture_index >= 0; const GiSettings& gi = VulkanRenderer::instance->giSettings(); - m_gi_clipmap = - gi.enabled.load(std::memory_order_relaxed) && gi.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_clipmap; + m_gi_clipmap = gi.enabled.load(std::memory_order_relaxed); // The gather target is sized for the main view so captures take the one cone path m_gi_gather = m_gi_clipmap && !capture && m_gi_gather_pipeline.isReady(); // Clipmap GI goes through it too since its rotating cones only settle over frames @@ -1529,7 +1536,7 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: if (m_denoise_active) { push = LightingPushConstants { .inverse_view_projection = glm::inverse(frame->frame_data.jittered_view_projection), - .viewport = glm::vec4(static_cast(viewport.width), height, 0.0f, 0.0f), + .viewport = glm::vec4(static_cast(viewport.width), height, giGatherPacked() ? 1.0f : 0.0f, 0.0f), .lighting = glm::uvec4( std::min(m_shadow_instance_count, instance->voxelShadowInstances()), instance->voxelLightCandidates(), @@ -1888,6 +1895,10 @@ void VoxelPass::createDenoise(const VulkanCore& core, vk::Format scene_format, v config.cull_mode = vk::CullModeFlagBits::eNone; config.depth_test = false; config.depth_write = false; + // Diffuse into the colour attachment and specular and the composite lumas into the extra ones in a single draw + config.extra_color_formats = {k_denoise_history_format, k_denoise_luma_format}; + config.write_extra_color = true; + config.extra_blend_mask = 0u; m_denoise_temporal_pipeline.rebuild(core, config); config.debug_name = "VoxelDenoise Composite"; @@ -1923,6 +1934,7 @@ void VoxelPass::createDenoiseTargets(vk::Extent2D extent) { ); } } + m_denoise_luma.create(*m_core, extent, k_denoise_luma_format, "VoxelDenoise Luma"); m_denoise_bound.resize(m_denoise_sets.size()); m_denoise_valid = false; } @@ -1946,6 +1958,7 @@ void VoxelPass::bindDenoise(vk::CommandBuffer cmd, uint32_t frame_index, const V m_denoise_history[0][m_denoise_parity].view(), m_denoise_history[1][m_denoise_parity].view(), renderer->getSceneIndirectView(), + m_denoise_luma.view(), }; // Safe since the fence of this slot was waited on @@ -1995,13 +2008,45 @@ void VoxelPass::recordDenoiseTemporal(vk::CommandBuffer cmd, uint32_t frame_inde m_denoise_history[1][read].makeSampleable(cmd); } - for (uint32_t term = 0; term < 2; ++term) { - const PostProcessTarget& target = m_denoise_history[term][m_denoise_parity]; - target.beginScope(cmd); - bindDenoise(cmd, frame_index, m_denoise_temporal_pipeline, static_cast(term)); - cmd.draw(3, 1, 0, 0); - target.endScope(cmd); + const PostProcessTarget& diffuse = m_denoise_history[0][m_denoise_parity]; + const PostProcessTarget& specular = m_denoise_history[1][m_denoise_parity]; + if (!diffuse.isReady() || !specular.isReady() || !m_denoise_luma.isReady()) { + return; } + sync::BarrierBatch to_attachment; + to_attachment.image(diffuse.state(), sync::Usage::color_attachment); + to_attachment.image(specular.state(), sync::Usage::color_attachment); + to_attachment.image(m_denoise_luma.state(), sync::Usage::color_attachment); + to_attachment.flush(cmd); + + const std::array views {diffuse.view(), specular.view(), m_denoise_luma.view()}; + std::array attachments {}; + for (uint32_t term = 0; term < attachments.size(); ++term) { + attachments[term].imageView = views[term]; + attachments[term].imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + attachments[term].loadOp = vk::AttachmentLoadOp::eDontCare; + attachments[term].storeOp = vk::AttachmentStoreOp::eStore; + } + const vk::Extent2D extent = diffuse.extent(); + vk::RenderingInfo rendering_info {}; + rendering_info.renderArea = vk::Rect2D({0, 0}, extent); + rendering_info.layerCount = 1; + rendering_info.colorAttachmentCount = static_cast(attachments.size()); + rendering_info.pColorAttachments = attachments.data(); + cmd.beginRendering(rendering_info); + cmd.setViewport( + 0, std::array {vk::Viewport(0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f)} + ); + cmd.setScissor(0, std::array {vk::Rect2D({0, 0}, extent)}); + bindDenoise(cmd, frame_index, m_denoise_temporal_pipeline, 0.0f); + cmd.draw(3, 1, 0, 0); + cmd.endRendering(); + + sync::BarrierBatch to_sampled; + to_sampled.image(diffuse.state(), sync::Usage::shader_sampled); + to_sampled.image(specular.state(), sync::Usage::shader_sampled); + to_sampled.image(m_denoise_luma.state(), sync::Usage::shader_sampled); + to_sampled.flush(cmd); } void VoxelPass::recordDenoiseComposite(vk::CommandBuffer cmd, uint32_t frame_index) { @@ -2069,7 +2114,7 @@ void VoxelPass::recordMarched(vk::CommandBuffer cmd, uint32_t frame_index) { auto VoxelPass::updateGbufferSet(uint32_t frame_index) -> bool { const auto* instance = VulkanRenderer::instance; - const std::array views { + const std::array views { instance->getVoxelAlbedoView(), instance->getVoxelFaceNormalView(), instance->getVoxelMaterialView(), @@ -2082,6 +2127,7 @@ auto VoxelPass::updateGbufferSet(uint32_t frame_index) -> bool { instance->getVoxelNoisySpecularView(), instance->getVoxelDetailNormalView(), instance->getVoxelGiView(), + instance->getVoxelAmbientOcclusionView(), }; if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { return false; @@ -2116,7 +2162,8 @@ void VoxelPass::recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk:: const LightingPushConstants push { .inverse_view_projection = glm::inverse(frame->frame_data.jittered_view_projection), - .viewport = glm::vec4(static_cast(viewport.width), static_cast(viewport.height), 0.0f, 0.0f), + .viewport = + glm::vec4(static_cast(viewport.width), static_cast(viewport.height), giGatherPacked() ? 1.0f : 0.0f, 0.0f), .reuse = glm::uvec4(m_denoise_active ? k_gi_denoise : 0u, 0u, 0u, 0u), }; const vk::PipelineLayout layout = *m_lighting_layout.getPipelineLayout(); @@ -2134,12 +2181,24 @@ void VoxelPass::recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk:: cmd.draw(3, 1, 0, 0); } -void VoxelPass::recordAmbient(vk::CommandBuffer cmd, uint32_t frame_index) { +void VoxelPass::recordAmbientTrace(vk::CommandBuffer cmd, uint32_t frame_index) { ZoneScoped; - if (!m_ambient_rays || !m_ambient_pipeline.isReady() || frame_index >= m_gbuffer_sets.size() || + if (!m_ambient_rays || !m_ambient_trace_pipeline.isReady() || frame_index >= m_gbuffer_sets.size() || frame_index >= m_lighting_storage_sets.size() || !m_lighting_scene_sets.get(frame_index)) { return; } + bindMarched(cmd, frame_index, m_ambient_trace_pipeline); + cmd.draw(3, 1, 0, 0); +} + +void VoxelPass::recordAmbient(vk::CommandBuffer cmd, uint32_t frame_index) { + ZoneScoped; + // The upsample reads what recordAmbientTrace wrote this frame + if (!m_ambient_rays || !m_ambient_pipeline.isReady() || !m_ambient_trace_pipeline.isReady() || + frame_index >= m_gbuffer_sets.size() || frame_index >= m_lighting_storage_sets.size() || + !m_lighting_scene_sets.get(frame_index)) { + return; + } bindMarched(cmd, frame_index, m_ambient_pipeline); cmd.draw(3, 1, 0, 0); } diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp index ba9ab0e21..31f3c0f7a 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp @@ -78,6 +78,12 @@ class VoxelPass : public IRenderPass { return m_gi_gather; } + /// The denoised gather shades a checkerboard packed into the left half of the GI target, see voxel_lighting giGatherHalf + [[nodiscard]] + auto giGatherPacked() const noexcept -> bool { + return m_gi_gather && m_denoise_active; + } + /// Inside a scope over the half resolution GI target and before recordLighting() which upsamples it void recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk::Extent2D viewport); @@ -87,6 +93,9 @@ class VoxelPass : public IRenderPass { return m_ambient_rays; } + /// Inside a half resolution scope over the ambient occlusion target before recordAmbient() upsamples it + void recordAmbientTrace(vk::CommandBuffer cmd, uint32_t frame_index); + /// Inside a scope over noisy diffuse alone with the scene normal sampleable and before recordMarched() void recordAmbient(vk::CommandBuffer cmd, uint32_t frame_index); @@ -390,7 +399,7 @@ class VoxelPass : public IRenderPass { uint32_t m_shadow_instance_count = 0; /// Albedo face normal material and depth last written into each set - DescriptorCache> m_bound_gbuffer; + DescriptorCache> m_bound_gbuffer; auto updateGbufferSet(uint32_t frame_index) -> bool; VulkanPipeline m_gi_gather_pipeline; bool m_gi_gather = false; @@ -399,6 +408,7 @@ class VoxelPass : public IRenderPass { VulkanPipeline m_spatial_opaque_pipeline; VulkanPipeline m_marched_pipeline; VulkanPipeline m_ambient_pipeline; + VulkanPipeline m_ambient_trace_pipeline; VulkanPipeline m_marched_composite_pipeline; bool m_spatial_active = false; bool m_scene_glass = false; @@ -427,8 +437,10 @@ class VoxelPass : public IRenderPass { /// rgb filtered term a linear depth it was written at static constexpr vk::Format k_denoise_history_format = vk::Format::eR16G16B16A16Sfloat; + /// voxel_denoise.slang gLuma + static constexpr vk::Format k_denoise_luma_format = vk::Format::eR16G16Sfloat; /// Bindings of voxel_denoise.slang in order - static constexpr size_t k_denoise_bindings = 11; + static constexpr size_t k_denoise_bindings = 12; /// Change regions of a newly published storage that voxel.slang marks reactive void writeFreshRegions(uint32_t frame_index, const VoxelGpuStorage& storage); @@ -446,6 +458,8 @@ class VoxelPass : public IRenderPass { DescriptorCache> m_denoise_bound; /// [term][parity] where the temporal pass writes the parity and reads the other std::array, 2> m_denoise_history; + /// This frame only, written beside the histories + PostProcessTarget m_denoise_luma; uint32_t m_denoise_parity = 0; /// Histories hold the previous frame bool m_denoise_valid = false; diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp index 81da155a7..a739b9f75 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp @@ -819,8 +819,7 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag const auto* frame = renderer->renderingFrame(); const GiSettings& settings = renderer->giSettings(); constexpr auto relaxed = std::memory_order_relaxed; - if (!settings.enabled.load(relaxed) || settings.backend.load(relaxed) != GiSettings::k_backend_clipmap || frame == nullptr || - frame_index >= m_storage_sets.size() || !m_fill_pipeline.isReady()) { + if (!settings.enabled.load(relaxed) || frame == nullptr || frame_index >= m_storage_sets.size() || !m_fill_pipeline.isReady()) { markFull(); unpublish(cmd); return source_view; @@ -965,29 +964,40 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag const float level_cell = cell * static_cast(1u << i); const glm::ivec3 origin = gi_clip::origin(camera, level_cell, side); data.levels[i] = glm::vec4(glm::vec3(origin), level_cell); - if (level.needs_full || !known) { + if (level.needs_full) { boxes[i].push_back({.min = origin, .max = origin + side}); whole[i] = true; scrolled_boxes[i] = 1; level.pending.clear(); + level.sweep.clear(); + level.resweep = false; } else { std::array slabs; const uint32_t count = gi_clip::scrolled(level.origin, origin, side, slabs); boxes[i].assign(slabs.begin(), slabs.begin() + count); scrolled_boxes[i] = count; // Queued cells that scrolled out are gone and the ones that scrolled in come with the slabs - std::erase_if(level.pending, [&](gi_clip::Box& box) { + const auto outside = [&](gi_clip::Box& box) { box.min = glm::max(box.min, origin); box.max = glm::min(box.max, origin + side); return gi_clip::empty(box); - }); + }; + std::erase_if(level.pending, outside); + std::erase_if(level.sweep, outside); for (size_t b = 0; b + 1 < dirty.size(); b += 2) { const gi_clip::Box box = gi_clip::cells(dirty[b], dirty[b + 1], level_cell, origin, side); if (!gi_clip::empty(box)) { mergeInto(level.pending, box); } } + // Edits past the history could be anywhere so the whole level refreshes, a budget a frame + level.resweep = level.resweep || !known; + if (level.resweep && level.sweep.empty()) { + level.sweep.push_back({.min = origin, .max = origin + side}); + level.resweep = false; + } takeBudget(level.pending, k_fill_budget_cells, boxes[i]); + takeBudget(level.sweep, k_sweep_budget_cells, boxes[i]); } level.origin = origin; level.needs_full = false; diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp index a615e6cd6..051119aec 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp @@ -129,10 +129,16 @@ class GiClipmapPass : public IPostProcessPass { bool needs_full = true; /// Dirty cells past the fill budget that later frames refill first std::vector pending; + /// Whole level refill after the edit history was lost, spread over frames since the old cells are still close + std::vector sweep; + /// History was lost again during a sweep so another follows it + bool resweep = false; }; /// Dirty cells refilled per level each frame on top of the scroll so a blast spreads over frames static constexpr int64_t k_fill_budget_cells = 16384; + /// A 128 cell level in about 32 frames instead of all at once, which spiked fill and inject to 15 ms a frame + static constexpr int64_t k_sweep_budget_cells = 65536; auto createPipelines(const VulkanCore& core) -> bool; /// Waits for the device so no frame in flight still reads the old images diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp deleted file mode 100644 index 09a54d6d3..000000000 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp +++ /dev/null @@ -1,1276 +0,0 @@ -/// @file gi_pass.cpp -/// @author dario -/// @date 22/10/2026 - -#include "toast/renderer/passes/lighting/gi_pass.hpp" - -#include "toast/renderer/core/descriptor_writer.hpp" -#include "toast/renderer/core/gpu_sync.hpp" -#include "toast/renderer/core/gpu_timer.hpp" -#include "toast/renderer/shaders/shader_cache.hpp" -#include "toast/renderer/shaders/shader_compiler.hpp" -#include "toast/renderer/voxel/voxel_blas_cache.hpp" -#include "toast/renderer/voxel/voxel_gpu_storage.hpp" -#include "toast/renderer/voxel/voxel_trace_scene.hpp" -#include "toast/renderer/vulkan_renderer.hpp" - -#include -#include - -namespace renderer { - -namespace { - -constexpr uint32_t k_group = 64; -constexpr uint32_t k_pixel_group = 8; -/// Mirrors gi_common GiProbe -constexpr vk::DeviceSize k_probe_bytes = 32; -/// LOD start shortened by this share so neighbouring LODs overlap and blend -constexpr float k_lod_overlap = 0.9f; -/// LOD distance over probe spacing keeping a carried shell inside the 512 cell key window -constexpr float k_max_cells_to_lod = 80.0f; - -constexpr uint32_t k_gi_depth_binding = 0; -constexpr uint32_t k_frame_binding = 1; -constexpr uint32_t k_keys_binding = 2; -constexpr uint32_t k_flags_binding = 3; -constexpr uint32_t k_previous_binding = 4; -constexpr uint32_t k_values_binding = 5; -constexpr uint32_t k_gi_cells_binding = 6; -constexpr uint32_t k_pool_binding = 7; -constexpr uint32_t k_counters_binding = 8; -constexpr uint32_t k_normal_binding = 9; -constexpr uint32_t k_deposit_pool_binding = 10; -constexpr uint32_t k_parent_binding = 11; -constexpr uint32_t k_ray_counts_binding = 12; -constexpr uint32_t k_deposits_binding = 13; -constexpr uint32_t k_deposit_slots_binding = 14; -constexpr uint32_t k_neighbours_binding = 15; -constexpr uint32_t k_history_source_binding = 16; -constexpr uint32_t k_dirty_binding = 17; -constexpr uint32_t k_points_binding = 18; -constexpr uint32_t k_spawn_binding = 19; - -/// gi_debug -constexpr uint32_t k_debug_source_binding = 0; -constexpr uint32_t k_debug_depth_binding = 1; -constexpr uint32_t k_debug_frame_binding = 2; -constexpr uint32_t k_debug_keys_binding = 3; -constexpr uint32_t k_debug_values_binding = 4; -constexpr uint32_t k_debug_pool_binding = 5; -constexpr uint32_t k_debug_normal_binding = 6; -constexpr uint32_t k_debug_deposits_binding = 7; -constexpr uint32_t k_debug_deposit_slots_binding = 8; -constexpr uint32_t k_debug_irradiance_binding = 9; -constexpr uint32_t k_debug_history_binding = 10; -constexpr uint32_t k_debug_change_binding = 11; - -/// gi_rays -constexpr uint32_t k_ray_scene_set = 0; -constexpr uint32_t k_ray_storage_set = 1; -constexpr uint32_t k_ray_gi_set = 2; -constexpr uint32_t k_ray_instances_binding = 6; -constexpr uint32_t k_ray_trace_volumes_binding = 10; -constexpr uint32_t k_ray_trace_bounds_binding = 11; -constexpr uint32_t k_ray_trace_grid_binding = 12; -constexpr uint32_t k_ray_trace_brick_bases_binding = 14; -constexpr uint32_t k_ray_trace_bricks_binding = 15; -constexpr uint32_t k_ray_depth_binding = 0; -constexpr uint32_t k_ray_normal_binding = 1; -constexpr uint32_t k_ray_frame_binding = 2; -constexpr uint32_t k_ray_keys_binding = 3; -constexpr uint32_t k_ray_values_binding = 4; -constexpr uint32_t k_ray_pool_binding = 5; -constexpr uint32_t k_ray_ray_counts_binding = 6; -constexpr uint32_t k_ray_deposits_binding = 7; -constexpr uint32_t k_ray_parent_binding = 8; -constexpr uint32_t k_ray_deposit_slots_binding = 9; -constexpr uint32_t k_ray_scene_colour_binding = 10; -constexpr uint32_t k_ray_counters_binding = 11; -constexpr uint32_t k_ray_points_binding = 12; -constexpr uint32_t k_ray_irradiance_binding = 13; -constexpr uint32_t k_ray_change_binding = 14; -constexpr uint32_t k_ray_spawn_binding = 15; -constexpr uint32_t k_ray_hits_binding = 16; -/// Mirrors gi_common GiPoint -constexpr vk::DeviceSize k_point_bytes = 16; -/// Mirrors gi_common GiHistory -constexpr vk::DeviceSize k_history_bytes = 12; - -/// gi_merge -constexpr uint32_t k_merge_scene_set = 0; -constexpr uint32_t k_merge_set = 1; -constexpr uint32_t k_merge_frame_binding = 0; -constexpr uint32_t k_merge_pool_binding = 1; -constexpr uint32_t k_merge_deposit_pool_binding = 2; -constexpr uint32_t k_merge_deposit_slots_binding = 3; -constexpr uint32_t k_merge_neighbours_binding = 4; -constexpr uint32_t k_merge_deposits_binding = 5; -constexpr uint32_t k_merge_merged_binding = 6; -constexpr uint32_t k_merge_irradiance_binding = 7; -constexpr uint32_t k_merge_counters_binding = 8; -constexpr uint32_t k_merge_history_binding = 9; -constexpr uint32_t k_merge_history_source_binding = 10; -constexpr uint32_t k_merge_dirty_binding = 11; - -/// Rays of history a probe keeps after a change crosses its interval -constexpr float k_reset_history = 0.25f; - -/// Mirrors gi_common kGiBaseDirections -constexpr uint32_t k_base_directions = 4; -/// Mirrors gi_common kGiStrideThreads -constexpr uint32_t k_stride_groups = 4096; -constexpr vk::Format k_atlas_format = vk::Format::eR16G16B16A16Sfloat; -/// First interval length t0 in c0 probe spacings -constexpr float k_interval_scale = 1.6f; -/// 1/256 steps so a bucket holds about a thousand rays at gi_rays kGiMaxRadiance -constexpr float k_deposit_fixed_scale = 256.0f; - -auto groups(uint32_t count, uint32_t size) -> uint32_t { - return (count + size - 1) / size; -} - -auto deviceBuffer(const VulkanCore& core, vk::DeviceSize size, vk::BufferUsageFlags usage, std::string_view name) - -> vma::raii::Buffer { - vk::BufferCreateInfo buffer_ci {}; - buffer_ci.size = size; - buffer_ci.usage = usage; - vma::AllocationCreateInfo alloc_ci {}; - alloc_ci.usage = vma::MemoryUsage::eAutoPreferDevice; - vma::raii::Buffer buffer = core.getAllocator().createBuffer(buffer_ci, alloc_ci); - setDebugName(core, *buffer, name); - return buffer; -} - -auto hostBuffer(const VulkanCore& core, vk::DeviceSize size, vk::BufferUsageFlags usage, bool read, std::string_view name) - -> vma::raii::Buffer { - vk::BufferCreateInfo buffer_ci {}; - buffer_ci.size = size; - buffer_ci.usage = usage; - vma::AllocationCreateInfo alloc_ci {}; - alloc_ci.usage = read ? vma::MemoryUsage::eAutoPreferHost : vma::MemoryUsage::eAuto; - alloc_ci.flags = vma::AllocationCreateFlagBits::eMapped | (read ? vma::AllocationCreateFlagBits::eHostAccessRandom - : vma::AllocationCreateFlagBits::eHostAccessSequentialWrite); - vma::raii::Buffer buffer = core.getAllocator().createBuffer(buffer_ci, alloc_ci); - setDebugName(core, *buffer, name); - return buffer; -} - -void computeBarrier(vk::CommandBuffer cmd) { - sync::BarrierBatch barriers; - barriers.memory(sync::Usage::compute_storage_write, sync::Usage::compute_storage_write); - barriers.flush(cmd); -} - -/// Mirrors gi_common giRayPoint fixed point R2 -auto r2Jitter(uint32_t frame) -> glm::vec2 { - const uint32_t x = 0x80000000u + (frame * 3242174889u); - const uint32_t y = 0x80000000u + (frame * 2447445414u); - return glm::vec2(static_cast(x >> 8), static_cast(y >> 8)) / 16777216.0f; -} - -struct QualityLevel { - uint32_t ray_budget = 0; - uint32_t cascades = 0; - float spacing = 0.0f; - float lod_distance = 0.0f; - bool multibounce = false; - uint32_t points = 0; - uint32_t interval = 1; -}; - -/// Scalability -constexpr std::array k_quality_levels { - { - // Cheapest since the Low preset without ray tracing runs it on software traces - {.ray_budget = 100'000, - .cascades = 4, - .spacing = 0.25f, - .lod_distance = 4.0f, - .multibounce = false, - .points = 8192, - .interval = 2}, - {.ray_budget = 300'000, - .cascades = 4, - .spacing = 0.15f, - .lod_distance = 4.0f, - .multibounce = true, - .points = 32768, - .interval = 1}, - {.ray_budget = 600'000, - .cascades = 5, - .spacing = 0.1f, - .lod_distance = 4.0f, - .multibounce = true, - .points = 65536, - .interval = 1}, - {.ray_budget = 2'200'000, - .cascades = 5, - .spacing = 0.1f, - .lod_distance = 4.0f, - .multibounce = true, - .points = 65536, - .interval = 1}, - } -}; - -auto stepForBudget(vk::Extent2D extent, uint32_t budget) -> uint32_t { - for (uint32_t step = 1; step < 4; ++step) { - const uint64_t rays = static_cast(groups(extent.width, step)) * groups(extent.height, step); - if (rays <= budget) { - return step; - } - } - return 4; -} - -/// Most pixels any quality preset spawns at this extent -auto spawnCapacity(vk::Extent2D extent) -> uint32_t { - uint32_t capacity = 1; - for (const QualityLevel& preset : k_quality_levels) { - const uint32_t step = stepForBudget(extent, preset.ray_budget); - capacity = std::max(capacity, groups(extent.width, step) * groups(extent.height, step)); - } - return capacity; -} - -} - -auto GiPass::resolveQuality() const -> Quality { - const GiSettings& settings = VulkanRenderer::instance->giSettings(); - constexpr auto relaxed = std::memory_order_relaxed; - const uint32_t level = std::min(settings.quality.load(relaxed), GiSettings::k_quality_custom); - if (level == GiSettings::k_quality_custom) { - uint32_t step = std::clamp(settings.ray_step.load(relaxed), 1u, 4u); - // A step whose pixels overflow the spawn list would starve the screen tail - while (m_spawn_capacity > 0 && step < 4 && groups(m_extent.width, step) * groups(m_extent.height, step) > m_spawn_capacity) { - ++step; - } - return Quality { - .level = level, - .step = step, - .cascades = std::clamp(settings.cascades.load(relaxed), 1u, k_max_cascades), - .spacing = settings.probe_spacing.load(relaxed), - .lod_distance = settings.lod_distance.load(relaxed), - .multibounce = settings.multibounce.load(relaxed), - .points = std::clamp(settings.secondary_points.load(relaxed), 1u, k_max_points), - .interval = std::clamp(settings.update_interval.load(relaxed), 1u, 4u), - }; - } - const QualityLevel& preset = k_quality_levels[level]; - return Quality { - .level = level, - .step = stepForBudget(m_extent, preset.ray_budget), - .cascades = std::min(preset.cascades, k_max_cascades), - .spacing = preset.spacing, - .lod_distance = preset.lod_distance, - .multibounce = preset.multibounce, - .points = std::min(preset.points, k_max_points), - .interval = preset.interval, - }; -} - -GiPass::GiPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent) - : m_core(&core), - m_scene_format(scene_format), - m_extent(extent) { - ZoneScoped; - static_assert(sizeof(FrameData) == 416, "FrameData is mirrored by gi_common GiFrame"); - - createLayout(); - createBuffers(core); - if (!createPipelines(core)) { - setEnabled(false); - return; - } - m_debug_target.create(core, extent, scene_format, "GiPass Debug"); - TOAST_INFO( - "Render", - "GiPass ready ({} table entries, {} probes per pool, {} deposit probes, {} MB of deposits history and merged radiance)", - m_table_total, - m_pool_total, - m_deposit_total, - ((sizeof(glm::uvec4) + (2 * k_history_bytes) + (sizeof(glm::uvec2) / 4)) * k_deposit_slots) >> 20 - ); -} - -void GiPass::createLayout() { - uint32_t table = 0; - uint32_t pool = 0; - uint32_t deposit = 0; - for (uint32_t i = 0; i < k_max_cascades; ++i) { - const uint32_t capacity = std::max(k_base_capacity >> (2 * i), k_min_capacity); - // Half full at most so linear probing stays short - const uint32_t size = std::bit_ceil(capacity * 2); - const uint32_t side = k_base_directions << i; - const uint32_t directions = 2 * side * side; - // c0 deposit probes double as irradiance tiles - const uint32_t deposit_capacity = i == 0 ? std::min(capacity, k_atlas_tiles) : capacity; - m_cascades[i] = Cascade { - .table_offset = table, - .table_size = size, - .pool_offset = pool, - .capacity = capacity, - .deposit_offset = deposit, - .deposit_capacity = deposit_capacity, - .directions = directions, - }; - table += size; - pool += capacity; - deposit += deposit_capacity; - } - m_table_total = table; - m_pool_total = pool; - m_deposit_total = deposit; -} - -void GiPass::createBuffers(const VulkanCore& core) { - ZoneScoped; - constexpr auto storage = vk::BufferUsageFlagBits::eStorageBuffer; - m_table_keys.emplace(deviceBuffer(core, sizeof(uint32_t) * m_table_total, storage, "GiPass TableKeys")); - m_table_flags.emplace(deviceBuffer(core, sizeof(uint32_t) * m_table_total, storage, "GiPass TableFlags")); - m_table_previous.emplace(deviceBuffer(core, sizeof(uint32_t) * m_table_total, storage, "GiPass TablePrevious")); - m_table_values.emplace(deviceBuffer(core, sizeof(uint32_t) * m_table_total, storage, "GiPass TableValues")); - m_table_cells.emplace(deviceBuffer(core, sizeof(glm::ivec4) * m_table_total, storage, "GiPass TableCells")); - m_pool.emplace(deviceBuffer(core, k_probe_bytes * 2 * m_pool_total, storage, "GiPass Pool")); - m_counters.emplace(deviceBuffer( - core, - sizeof(uint32_t) * k_counter_words, - storage | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst, - "GiPass Counters" - )); - m_deposit_pool.emplace(deviceBuffer(core, sizeof(uint32_t) * m_deposit_total, storage, "GiPass DepositPool")); - m_parent.emplace(deviceBuffer(core, sizeof(uint32_t) * m_deposit_total, storage, "GiPass Parent")); - m_ray_counts.emplace(deviceBuffer(core, sizeof(glm::uvec4) * m_deposit_total, storage, "GiPass RayCounts")); - m_deposits.emplace(deviceBuffer(core, sizeof(glm::uvec4) * k_deposit_slots, storage, "GiPass Deposits")); - m_deposit_slots.emplace(deviceBuffer(core, sizeof(uint32_t) * m_deposit_total, storage, "GiPass DepositSlots")); - m_neighbours.emplace(deviceBuffer(core, sizeof(glm::uvec4) * 2 * m_deposit_total, storage, "GiPass Neighbours")); - // Every probe direction count is a multiple of four so slot / 4 indexes the averaged directions - m_merged.emplace(deviceBuffer(core, sizeof(glm::uvec2) * (k_deposit_slots / 4), storage, "GiPass Merged")); - - constexpr uint32_t atlas_width = k_atlas_tiles_per_row * 8; - constexpr uint32_t atlas_height = k_atlas_rows * 8; - vk::ImageCreateInfo image_ci {}; - image_ci.imageType = vk::ImageType::e2D; - image_ci.format = k_atlas_format; - image_ci.extent = vk::Extent3D {atlas_width, atlas_height, 1}; - image_ci.mipLevels = 1; - image_ci.arrayLayers = 1; - image_ci.samples = vk::SampleCountFlagBits::e1; - image_ci.tiling = vk::ImageTiling::eOptimal; - image_ci.usage = vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst; - image_ci.sharingMode = vk::SharingMode::eExclusive; - image_ci.initialLayout = vk::ImageLayout::eUndefined; - vma::AllocationCreateInfo image_alloc {}; - image_alloc.usage = vma::MemoryUsage::eAutoPreferDevice; - m_atlas.emplace(core.getAllocator().createImage(image_ci, image_alloc)); - setDebugName(core, **m_atlas, "GiPass IrradianceAtlas"); - const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; - m_atlas_state.reset(**m_atlas, range); - - vk::ImageViewCreateInfo view_ci {}; - view_ci.image = **m_atlas; - view_ci.viewType = vk::ImageViewType::e2D; - view_ci.format = k_atlas_format; - view_ci.subresourceRange = range; - m_atlas_view.emplace(core.getDevice(), view_ci); - setDebugName(core, **m_atlas_view, "GiPass IrradianceAtlas View"); - - m_published.emplace( - deviceBuffer(core, sizeof(FrameData), storage | vk::BufferUsageFlagBits::eTransferDst, "GiPass PublishedFrame") - ); - m_history.emplace(deviceBuffer(core, k_history_bytes * 2 * k_deposit_slots, storage, "GiPass History")); - m_history_source.emplace(deviceBuffer(core, sizeof(glm::uvec2) * m_deposit_total, storage, "GiPass HistorySource")); - m_points.emplace(deviceBuffer(core, k_point_bytes * 2 * k_max_points, storage, "GiPass Points")); - - // Lighting binds the atlas and the published frame before the first GI frame so both start readable and empty - const auto& device = core.getDevice(); - const vk::raii::CommandPool one_shot_pool( - device, vk::CommandPoolCreateInfo(vk::CommandPoolCreateFlagBits::eTransient, core.getGraphicsQueueFamilyIndex()) - ); - auto cmd_buffers = - device.allocateCommandBuffers(vk::CommandBufferAllocateInfo(*one_shot_pool, vk::CommandBufferLevel::ePrimary, 1)); - const vk::raii::CommandBuffer cmd = std::move(cmd_buffers[0]); - cmd.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); - cmd.fillBuffer(**m_counters, 0, vk::WholeSize, 0u); - cmd.fillBuffer(**m_published, 0, vk::WholeSize, 0u); - recordUndefinedToTransferDst(cmd, **m_atlas, range); - cmd.clearColorImage(**m_atlas, vk::ImageLayout::eTransferDstOptimal, vk::ClearColorValue(0.0f, 0.0f, 0.0f, 0.0f), range); - recordTransferDstToShaderRead(cmd, **m_atlas, range); - sync::BarrierBatch barriers; - barriers.memory(sync::Usage::transfer_dst, sync::Usage::general); - barriers.flush(*cmd); - cmd.end(); - submitAndWait(device, core.getGraphicsQueue(), core.graphicsSubmitMutex(), *cmd); - m_atlas_state.usage = sync::Usage::shader_sampled; - - m_frame_data.clear(); - m_readback.clear(); - m_dirty.clear(); - for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { - m_dirty.push_back(hostBuffer( - core, sizeof(glm::vec4) * (1 + (2 * GiDirtyBoxes::k_max_boxes)), storage, false, std::format("GiPass Dirty[{}]", i) - )); - const auto& dirty_allocation = m_dirty.back().getAllocation(); - std::memset(dirty_allocation.getInfo().pMappedData, 0, sizeof(glm::vec4)); - dirty_allocation.flush(0, sizeof(glm::vec4)); - m_frame_data.push_back(hostBuffer( - core, sizeof(FrameData), storage | vk::BufferUsageFlagBits::eTransferSrc, false, std::format("GiPass Frame[{}]", i) - )); - m_readback.push_back(hostBuffer( - core, - sizeof(uint32_t) * k_counter_words, - vk::BufferUsageFlagBits::eTransferDst, - true, - std::format("GiPass Readback[{}]", i) - )); - } - m_dirty_stats.assign(VulkanRenderer::k_frames_in_flight, Stats {}); - m_readback_valid.assign(VulkanRenderer::k_frames_in_flight, false); - m_readback_parity.assign(VulkanRenderer::k_frames_in_flight, 0u); - m_readback_point_share.assign(VulkanRenderer::k_frames_in_flight, m_point_share); - m_readback_point_budget.assign(VulkanRenderer::k_frames_in_flight, k_max_points); - m_readback_spawn_capacity.assign(VulkanRenderer::k_frames_in_flight, 0u); - - m_point_sampler = vk::raii::Sampler(core.getDevice(), nearestClampSamplerInfo()); - setDebugName(core, *m_point_sampler, "GiPass PointSampler"); - m_linear_sampler = vk::raii::Sampler(core.getDevice(), linearClampSamplerInfo()); - setDebugName(core, *m_linear_sampler, "GiPass LinearSampler"); -} - -auto GiPass::createPipelines(const VulkanCore& core) -> bool { - ZoneScoped; - const auto probe_uid = assets::resolveURI("core://shaders/gi_probes.slang"); - const auto probe_shader = probe_uid.has_value() ? ShaderCache::get().acquire(*probe_uid) : nullptr; - const auto debug_uid = assets::resolveURI("core://shaders/gi_debug.slang"); - const auto debug_shader = debug_uid.has_value() ? ShaderCache::get().acquire(*debug_uid) : nullptr; - const auto ray_uid = assets::resolveURI("core://shaders/gi_rays.slang"); - const auto ray_shader = ray_uid.has_value() ? ShaderCache::get().acquire(*ray_uid) : nullptr; - const auto merge_uid = assets::resolveURI("core://shaders/gi_merge.slang"); - const auto merge_shader = merge_uid.has_value() ? ShaderCache::get().acquire(*merge_uid) : nullptr; - if (!probe_shader || !debug_shader || !ray_shader || !merge_shader) { - TOAST_ERROR("Render", "GiPass shaders unavailable, radiance cascades are disabled"); - return false; - } - - m_probe_layout.rebuild(core, probe_shader->reflection, "GiPass Probes"); - const auto compute = [&](VulkanPipeline& pipeline, const char* entry) { - VulkanPipeline::Config config; - config.pipeline_type = VulkanPipeline::PipelineType::compute; - config.debug_name = std::format("GiPass {}", entry); - config.shader_spirv = probe_shader->spirv; - config.pipeline_layout = *m_probe_layout.getPipelineLayout(); - config.compute_entry = entry; - pipeline.rebuild(core, config); - }; - compute(m_clear_pipeline, "clearMain"); - compute(m_carry_pipeline, "carryMain"); - compute(m_pixel_pipeline, "pixelMain"); - compute(m_point_pipeline, "pointMain"); - compute(m_parent_pipeline, "parentMain"); - compute(m_compact_pipeline, "compactMain"); - compute(m_keep_pipeline, "keepMain"); - compute(m_slots_pipeline, "slotsMain"); - compute(m_deposit_clear_pipeline, "depositClearMain"); - compute(m_link_pipeline, "linkMain"); - compute(m_count_pipeline, "countMain"); - compute(m_point_count_pipeline, "pointCountMain"); - compute(m_propagate_pipeline, "propagateMain"); - compute(m_offset_pipeline, "offsetMain"); - - m_ray_layout.rebuild(core, ray_shader->reflection, "GiPass Rays"); - VulkanPipeline::Config ray_config; - ray_config.pipeline_type = VulkanPipeline::PipelineType::compute; - ray_config.debug_name = "GiPass traceMain"; - ray_config.shader_spirv = ray_shader->spirv; - ray_config.pipeline_layout = *m_ray_layout.getPipelineLayout(); - ray_config.compute_entry = "traceMain"; - m_ray_pipeline.rebuild(core, ray_config); - ray_config.debug_name = "GiPass pointTraceMain"; - ray_config.compute_entry = "pointTraceMain"; - m_point_trace_pipeline.rebuild(core, ray_config); - ray_config.debug_name = "GiPass shadeMain"; - ray_config.compute_entry = "shadeMain"; - m_shade_pipeline.rebuild(core, ray_config); - ray_config.debug_name = "GiPass changeMain"; - ray_config.compute_entry = "changeMain"; - m_change_pipeline.rebuild(core, ray_config); - - m_merge_layout.rebuild(core, merge_shader->reflection, "GiPass Merge"); - VulkanPipeline::Config merge_config; - merge_config.pipeline_type = VulkanPipeline::PipelineType::compute; - merge_config.shader_spirv = merge_shader->spirv; - merge_config.pipeline_layout = *m_merge_layout.getPipelineLayout(); - merge_config.debug_name = "GiPass mergeMain"; - merge_config.compute_entry = "mergeMain"; - m_merge_pipeline.rebuild(core, merge_config); - merge_config.debug_name = "GiPass irradianceMain"; - merge_config.compute_entry = "irradianceMain"; - m_irradiance_pipeline.rebuild(core, merge_config); - - m_debug_layout.rebuild(core, debug_shader->reflection, "GiPass Debug"); - VulkanPipeline::Config config; - config.pipeline_type = VulkanPipeline::PipelineType::graphics; - config.debug_name = "GiPass Debug"; - config.color_format = m_scene_format; - config.write_color_alpha = true; - config.extent = m_extent; - config.shader_spirv = debug_shader->spirv; - config.pipeline_layout = *m_debug_layout.getPipelineLayout(); - config.vertex_bindings = {}; - config.vertex_attributes = {}; - config.cull_mode = vk::CullModeFlagBits::eNone; - config.depth_test = false; - config.depth_write = false; - m_debug_pipeline.rebuild(core, config); - - const auto& probe_layouts = m_probe_layout.getDescriptorSetLayouts(); - const auto& debug_layouts = m_debug_layout.getDescriptorSetLayouts(); - const auto& ray_layouts = m_ray_layout.getDescriptorSetLayouts(); - const auto& merge_layouts = m_merge_layout.getDescriptorSetLayouts(); - if (probe_layouts.empty() || debug_layouts.empty() || ray_layouts.size() <= k_ray_gi_set || - merge_layouts.size() <= k_merge_set) { - TOAST_ERROR("Render", "GiPass shader layouts have no descriptor sets, radiance cascades are disabled"); - return false; - } - - const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); - const vk::DescriptorSetLayout probe_set_layout = *probe_layouts[0]; - const vk::DescriptorSetLayout debug_set_layout = *debug_layouts[0]; - const vk::DescriptorSetLayout ray_storage_layout = *ray_layouts[k_ray_storage_set]; - const vk::DescriptorSetLayout ray_set_layout = *ray_layouts[k_ray_gi_set]; - const vk::DescriptorSetLayout merge_set_layout = *merge_layouts[k_merge_set]; - m_ray_scene_sets.create(core, ray_shader->reflection, *ray_layouts[k_ray_scene_set], "GiPass Rays"); - m_merge_scene_sets.create(core, merge_shader->reflection, *merge_layouts[k_merge_scene_set], "GiPass Merge"); - m_ray_instances_bound = std::ranges::any_of(ray_shader->reflection.bindings, [](const ShaderBinding& binding) { - return binding.set == k_ray_storage_set && binding.binding == k_ray_instances_binding; - }); - const VoxelTraceScene* trace = VulkanRenderer::instance->voxelTraceScene(); - m_probe_sets.clear(); - m_debug_sets.clear(); - m_ray_storage_sets.clear(); - m_ray_sets.clear(); - m_merge_sets.clear(); - for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { - auto probe = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &probe_set_layout)); - m_probe_sets.push_back(std::move(probe[0])); - setDebugName(core, *m_probe_sets.back(), std::format("GiPass ProbeSet[{}]", i)); - auto debug = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &debug_set_layout)); - m_debug_sets.push_back(std::move(debug[0])); - setDebugName(core, *m_debug_sets.back(), std::format("GiPass DebugSet[{}]", i)); - - DescriptorWriter writer; - const vk::DescriptorSet probe_set = *m_probe_sets.back(); - constexpr auto storage = vk::DescriptorType::eStorageBuffer; - writer.buffer(probe_set, k_frame_binding, storage, *m_frame_data[i]); - writer.buffer(probe_set, k_keys_binding, storage, **m_table_keys); - writer.buffer(probe_set, k_flags_binding, storage, **m_table_flags); - writer.buffer(probe_set, k_previous_binding, storage, **m_table_previous); - writer.buffer(probe_set, k_values_binding, storage, **m_table_values); - writer.buffer(probe_set, k_gi_cells_binding, storage, **m_table_cells); - writer.buffer(probe_set, k_pool_binding, storage, **m_pool); - writer.buffer(probe_set, k_counters_binding, storage, **m_counters); - writer.buffer(probe_set, k_deposit_pool_binding, storage, **m_deposit_pool); - writer.buffer(probe_set, k_parent_binding, storage, **m_parent); - writer.buffer(probe_set, k_ray_counts_binding, storage, **m_ray_counts); - writer.buffer(probe_set, k_deposits_binding, storage, **m_deposits); - writer.buffer(probe_set, k_deposit_slots_binding, storage, **m_deposit_slots); - writer.buffer(probe_set, k_neighbours_binding, storage, **m_neighbours); - writer.buffer(probe_set, k_history_source_binding, storage, **m_history_source); - writer.buffer(probe_set, k_dirty_binding, storage, *m_dirty[i]); - writer.buffer(probe_set, k_points_binding, storage, **m_points); - - const vk::DescriptorSet debug_set = *m_debug_sets.back(); - writer.buffer(debug_set, k_debug_frame_binding, storage, *m_frame_data[i]); - writer.buffer(debug_set, k_debug_keys_binding, storage, **m_table_keys); - writer.buffer(debug_set, k_debug_values_binding, storage, **m_table_values); - writer.buffer(debug_set, k_debug_pool_binding, storage, **m_pool); - writer.buffer(debug_set, k_debug_deposits_binding, storage, **m_deposits); - writer.buffer(debug_set, k_debug_deposit_slots_binding, storage, **m_deposit_slots); - writer.buffer(debug_set, k_debug_history_binding, storage, **m_history); - writer.image( - debug_set, - k_debug_irradiance_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_linear_sampler, - **m_atlas_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - - auto ray_storage = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &ray_storage_layout)); - m_ray_storage_sets.push_back(std::move(ray_storage[0])); - setDebugName(core, *m_ray_storage_sets.back(), std::format("GiPass RayStorageSet[{}]", i)); - const vk::DescriptorSet ray_storage_set = *m_ray_storage_sets.back(); - if (trace != nullptr) { - writer.buffer(ray_storage_set, k_ray_trace_volumes_binding, storage, trace->volumeBuffer(i)); - writer.buffer(ray_storage_set, k_ray_trace_bounds_binding, storage, trace->boundsBuffer(i)); - writer.buffer(ray_storage_set, k_ray_trace_grid_binding, storage, trace->gridBuffer(i)); - if (m_ray_instances_bound) { - writer.buffer(ray_storage_set, k_ray_instances_binding, storage, trace->volumeBuffer(i)); - } - if (ShaderCompiler::isRayQueryAvailable()) { - const VoxelBlasCache* bricks = VulkanRenderer::instance->voxelBlasCache(); - writer.buffer(ray_storage_set, k_ray_trace_brick_bases_binding, storage, trace->brickBaseBuffer(i)); - writer.buffer( - ray_storage_set, - k_ray_trace_bricks_binding, - storage, - bricks != nullptr ? bricks->poolBuffer() : trace->brickBaseBuffer(i) - ); - } - } - - auto ray = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &ray_set_layout)); - m_ray_sets.push_back(std::move(ray[0])); - setDebugName(core, *m_ray_sets.back(), std::format("GiPass RaySet[{}]", i)); - const vk::DescriptorSet ray_set = *m_ray_sets.back(); - writer.buffer(ray_set, k_ray_frame_binding, storage, *m_frame_data[i]); - writer.buffer(ray_set, k_ray_keys_binding, storage, **m_table_keys); - writer.buffer(ray_set, k_ray_values_binding, storage, **m_table_values); - writer.buffer(ray_set, k_ray_pool_binding, storage, **m_pool); - writer.buffer(ray_set, k_ray_ray_counts_binding, storage, **m_ray_counts); - writer.buffer(ray_set, k_ray_deposits_binding, storage, **m_deposits); - writer.buffer(ray_set, k_ray_parent_binding, storage, **m_parent); - writer.buffer(ray_set, k_ray_deposit_slots_binding, storage, **m_deposit_slots); - writer.buffer(ray_set, k_ray_counters_binding, storage, **m_counters); - writer.buffer(ray_set, k_ray_points_binding, storage, **m_points); - writer.image( - ray_set, - k_ray_irradiance_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_linear_sampler, - **m_atlas_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - - auto merge = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &merge_set_layout)); - m_merge_sets.push_back(std::move(merge[0])); - setDebugName(core, *m_merge_sets.back(), std::format("GiPass MergeSet[{}]", i)); - const vk::DescriptorSet merge_set = *m_merge_sets.back(); - writer.buffer(merge_set, k_merge_frame_binding, storage, *m_frame_data[i]); - writer.buffer(merge_set, k_merge_pool_binding, storage, **m_pool); - writer.buffer(merge_set, k_merge_deposit_pool_binding, storage, **m_deposit_pool); - writer.buffer(merge_set, k_merge_deposit_slots_binding, storage, **m_deposit_slots); - writer.buffer(merge_set, k_merge_neighbours_binding, storage, **m_neighbours); - writer.buffer(merge_set, k_merge_deposits_binding, storage, **m_deposits); - writer.buffer(merge_set, k_merge_merged_binding, storage, **m_merged); - writer.image( - merge_set, - k_merge_irradiance_binding, - vk::DescriptorType::eStorageImage, - nullptr, - **m_atlas_view, - vk::ImageLayout::eGeneral - ); - writer.buffer(merge_set, k_merge_counters_binding, storage, **m_counters); - writer.buffer(merge_set, k_merge_history_binding, storage, **m_history); - writer.buffer(merge_set, k_merge_history_source_binding, storage, **m_history_source); - writer.buffer(merge_set, k_merge_dirty_binding, storage, *m_dirty[i]); - writer.flush(core.getDevice()); - } - m_probe_bound.resize(VulkanRenderer::k_frames_in_flight); - m_debug_bound.resize(VulkanRenderer::k_frames_in_flight); - m_ray_bound.resize(VulkanRenderer::k_frames_in_flight); - createChange(core); - m_ray_storage_bound.resize(VulkanRenderer::k_frames_in_flight); - if (trace == nullptr) { - TOAST_WARN("Render", "GiPass found no voxel trace scene so probes get no rays"); - } - - return m_clear_pipeline.isReady() && m_carry_pipeline.isReady() && m_pixel_pipeline.isReady() && m_parent_pipeline.isReady() && - m_compact_pipeline.isReady() && m_keep_pipeline.isReady() && m_slots_pipeline.isReady() && - m_deposit_clear_pipeline.isReady() && m_link_pipeline.isReady() && m_count_pipeline.isReady() && - m_propagate_pipeline.isReady() && m_offset_pipeline.isReady() && m_point_pipeline.isReady() && - m_point_count_pipeline.isReady() && m_merge_pipeline.isReady() && m_irradiance_pipeline.isReady(); -} - -void GiPass::onResize(vk::Extent2D extent) { - m_extent = extent; - if (m_core != nullptr) { - m_debug_target.create(*m_core, extent, m_scene_format, "GiPass Debug"); - m_probe_bound.invalidate(); - m_debug_bound.invalidate(); - m_ray_bound.invalidate(); - createChange(*m_core); - } -} - -void GiPass::createChange(const VulkanCore& core) { - if (m_ray_sets.empty() || m_debug_sets.empty()) { - return; - } - const vk::DeviceSize pixels = static_cast(std::max(m_extent.width, 1u)) * std::max(m_extent.height, 1u); - m_change.reset(); - m_change.emplace(deviceBuffer(core, sizeof(glm::vec4) * pixels, vk::BufferUsageFlagBits::eStorageBuffer, "GiPass Change")); - m_spawn_capacity = spawnCapacity(m_extent); - m_spawn.reset(); - m_spawn.emplace( - deviceBuffer(core, sizeof(uint32_t) * m_spawn_capacity, vk::BufferUsageFlagBits::eStorageBuffer, "GiPass Spawn") - ); - m_hits.reset(); - m_hits.emplace(deviceBuffer( - core, sizeof(glm::uvec4) * (m_spawn_capacity + k_max_points), vk::BufferUsageFlagBits::eStorageBuffer, "GiPass Hits" - )); - DescriptorWriter writer; - for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { - writer.buffer(*m_probe_sets[i], k_spawn_binding, vk::DescriptorType::eStorageBuffer, **m_spawn); - writer.buffer(*m_ray_sets[i], k_ray_spawn_binding, vk::DescriptorType::eStorageBuffer, **m_spawn); - writer.buffer(*m_ray_sets[i], k_ray_hits_binding, vk::DescriptorType::eStorageBuffer, **m_hits); - writer.buffer(*m_ray_sets[i], k_ray_change_binding, vk::DescriptorType::eStorageBuffer, **m_change); - writer.buffer(*m_debug_sets[i], k_debug_change_binding, vk::DescriptorType::eStorageBuffer, **m_change); - } - writer.flush(core.getDevice()); -} - -void GiPass::recordChange(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView scene_view) { - ZoneScoped; - if (!m_change_pipeline.isReady() || !m_change.has_value() || !bindRaySets(frame_index, scene_view)) { - return; - } - const vk::PipelineLayout layout = *m_ray_layout.getPipelineLayout(); - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_change_pipeline.getPipeline()); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eCompute, - layout, - 0, - std::array {m_ray_scene_sets.get(frame_index), *m_ray_storage_sets[frame_index], *m_ray_sets[frame_index]}, - {} - ); - cmd.dispatch(groups(m_extent.width, k_pixel_group), groups(m_extent.height, k_pixel_group), 1); -} - -void GiPass::gatherDirty() { - m_dirty_boxes.gather( - *VulkanRenderer::instance->renderingFrame(), - VulkanRenderer::instance->giSettings().motion_threshold.load(std::memory_order_relaxed) - ); -} - -auto GiPass::writeDirty(uint32_t frame_index) -> bool { - GiDirtyBoxes::Counts counts; - const bool known = m_dirty_boxes.take(counts); - Stats& stats = m_dirty_stats[frame_index]; - stats = Stats {}; - stats.moved = counts.moved; - stats.appeared = counts.appeared; - stats.edits = counts.edits; - stats.largest_motion = counts.largest_motion; - const auto boxes = m_dirty_boxes.boxes(); - const auto count = static_cast(boxes.size() / 2); - const auto& allocation = m_dirty[frame_index].getAllocation(); - auto* mapped = static_cast(allocation.getInfo().pMappedData); - mapped[0] = glm::vec4(static_cast(count), 0.0f, 0.0f, 0.0f); - for (uint32_t i = 0; i < count * 2; ++i) { - mapped[1 + i] = glm::vec4(boxes[i], 0.0f); - } - allocation.flush(0, sizeof(glm::vec4) * (1 + (count * 2))); - m_dirty_boxes.clear(); - return known; -} - -auto GiPass::sceneBuffer(std::string_view name) const -> vk::Buffer { - const auto handle = [](const std::optional& buffer) { - return buffer.has_value() ? **buffer : vk::Buffer {}; - }; - if (name == "gGiFrame") { - return handle(m_published); - } - if (name == "gGiTableKeys") { - return handle(m_table_keys); - } - if (name == "gGiTableValues") { - return handle(m_table_values); - } - if (name == "gGiPool") { - return handle(m_pool); - } - return {}; -} - -auto GiPass::stats() const -> Stats { - std::scoped_lock lock(m_stats_mutex); - return m_stats; -} - -void GiPass::readStats(uint32_t frame_index) { - if (!m_readback_valid[frame_index]) { - return; - } - m_readback_valid[frame_index] = false; - const auto& allocation = m_readback[frame_index].getAllocation(); - allocation.invalidate(0, sizeof(uint32_t) * k_counter_words); - std::array words {}; - std::memcpy(words.data(), allocation.getInfo().pMappedData, sizeof(uint32_t) * k_counter_words); - - const uint32_t parity = m_readback_parity[frame_index]; - Stats stats; - stats.cascades = m_quality.cascades; - for (uint32_t i = 0; i < k_max_cascades; ++i) { - stats.probes[i] = std::min(words[(parity * 8) + i], m_cascades[i].capacity); - stats.seen[i] = words[k_counter_seen + i]; - stats.capacity[i] = m_cascades[i].capacity; - stats.deposits[i] = std::min(words[k_counter_seen + i], m_cascades[i].deposit_capacity); - stats.deposit_capacity[i] = m_cascades[i].deposit_capacity; - const uint64_t sampled = ((static_cast(stats.deposits[i]) * m_cascades[i].directions) + 63) / 64; - stats.depth[i] = sampled > 0 ? static_cast(words[k_counter_depth + i]) / (16.0f * static_cast(sampled)) : 0.0f; - } - stats.table_full = words[k_counter_table_full]; - stats.pool_full = words[k_counter_pool_full]; - stats.deposit_full = words[k_counter_deposit_full]; - stats.rays = words[k_counter_rays]; - stats.slots = std::min(words[k_counter_slots], k_deposit_slots); - stats.moved = m_dirty_stats[frame_index].moved; - stats.appeared = m_dirty_stats[frame_index].appeared; - stats.edits = m_dirty_stats[frame_index].edits; - stats.largest_motion = m_dirty_stats[frame_index].largest_motion; - stats.invalidated = words[k_counter_invalidated]; - stats.fresh = words[k_counter_fresh]; - stats.blend = m_blend; - const uint32_t budget = m_readback_point_budget[frame_index]; - stats.points = std::min(words[k_counter_points + parity], budget); - stats.points_dropped = words[k_counter_points_dropped]; - if (words[k_counter_spawn] > m_readback_spawn_capacity[frame_index] && !m_spawn_overflow_logged) { - m_spawn_overflow_logged = true; - TOAST_WARN( - "Render", - "GI spawn pixels ({}) exceed the spawn list ({}) so the extra pixels trace no rays this frame", - words[k_counter_spawn], - m_readback_spawn_capacity[frame_index] - ); - } - - // Hits offered at a known share give the whole demand so the share fills the budget to 90% without a race - const float offered = static_cast(words[k_counter_points + parity]); - const float demand = offered / std::max(m_readback_point_share[frame_index], 1e-3f); - m_point_share = demand > 0.0f ? std::clamp(0.9f * static_cast(budget) / demand, 1.0f / 64.0f, 1.0f) : 1.0f; - stats.point_share = m_point_share; - stats.quality = m_quality.level; - stats.ray_step = m_quality.step; - stats.update_interval = m_quality.interval; - stats.point_budget = m_quality.multibounce ? m_quality.points : 0; - - std::scoped_lock lock(m_stats_mutex); - m_stats = stats; -} - -void GiPass::bindProbeSet(uint32_t frame_index) { - const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); - const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); - const std::array wanted {depth_view, normal_view}; - if (!m_probe_bound.update(frame_index, wanted)) { - return; - } - DescriptorWriter writer; - writer.image( - *m_probe_sets[frame_index], - k_gi_depth_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - depth_view, - vk::ImageLayout::eDepthReadOnlyOptimal - ); - writer.image( - *m_probe_sets[frame_index], - k_normal_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - normal_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - writer.flush(m_core->getDevice()); -} - -auto GiPass::bindRaySets(uint32_t frame_index, vk::ImageView scene_view) -> bool { - const auto* frame = VulkanRenderer::instance->renderingFrame(); - if (!m_ray_pipeline.isReady() || !scene_view || VulkanRenderer::instance->voxelTraceScene() == nullptr || - !frame->voxel_storage || !frame->voxel_storage->isReady()) { - return false; - } - // Safe since the fence of this slot was waited on - if (m_ray_storage_bound.update(frame_index, frame->voxel_storage)) { - writeVoxelStorageDescriptors(m_core->getDevice(), *m_ray_storage_sets[frame_index], *frame->voxel_storage); - } - - const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); - const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); - const std::array wanted {depth_view, normal_view, scene_view}; - if (m_ray_bound.update(frame_index, wanted)) { - DescriptorWriter writer; - writer.image( - *m_ray_sets[frame_index], - k_ray_scene_colour_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - scene_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - writer.image( - *m_ray_sets[frame_index], - k_ray_depth_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - depth_view, - vk::ImageLayout::eDepthReadOnlyOptimal - ); - writer.image( - *m_ray_sets[frame_index], - k_ray_normal_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - normal_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - writer.flush(m_core->getDevice()); - } - m_ray_scene_sets.updateTlas(frame_index); - return true; -} - -auto GiPass::recordTrace( - vk::CommandBuffer cmd, uint32_t frame_index, uint32_t spawn_x, uint32_t spawn_y, vk::ImageView scene_view -) -> bool { - ZoneScoped; - // Hits without a shade pass would queue and never deposit - if (!m_shade_pipeline.isReady() || !bindRaySets(frame_index, scene_view)) { - return false; - } - const vk::PipelineLayout layout = *m_ray_layout.getPipelineLayout(); - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_ray_pipeline.getPipeline()); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eCompute, - layout, - 0, - std::array {m_ray_scene_sets.get(frame_index), *m_ray_storage_sets[frame_index], *m_ray_sets[frame_index]}, - {} - ); - cmd.dispatch(groups(std::min(spawn_x * spawn_y, m_spawn_capacity), k_group), 1, 1); - if (m_point_trace_pipeline.isReady()) { - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_point_trace_pipeline.getPipeline()); - cmd.dispatch(groups(m_quality.points, k_group), 1, 1); - } - return true; -} - -void GiPass::recordShade(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t rays) { - ZoneScoped; - if (!m_shade_pipeline.isReady()) { - return; - } - const vk::PipelineLayout layout = *m_ray_layout.getPipelineLayout(); - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_shade_pipeline.getPipeline()); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eCompute, - layout, - 0, - std::array {m_ray_scene_sets.get(frame_index), *m_ray_storage_sets[frame_index], *m_ray_sets[frame_index]}, - {} - ); - cmd.dispatch(groups(rays, k_group), 1, 1); -} - -void GiPass::recordMerge(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t cascades) { - ZoneScoped; - const vk::PipelineLayout layout = *m_merge_layout.getPipelineLayout(); - m_merge_scene_sets.updateTlas(frame_index); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eCompute, layout, 0, std::array {m_merge_scene_sets.get(frame_index), *m_merge_sets[frame_index]}, {} - ); - - GpuTimer* timer = VulkanRenderer::instance->gpuTimer(); - static constexpr std::array k_merge_scopes { - "GI merge c0", "GI merge c1", "GI merge c2", "GI merge c3", "GI merge c4", "GI merge c5" - }; - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_merge_pipeline.getPipeline()); - for (uint32_t i = cascades; i-- > 1;) { - const GpuScope scope(timer, frame_index, cmd, k_merge_scopes[i]); - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(uint32_t), &i); - cmd.dispatch(k_stride_groups, 1, 1); - computeBarrier(cmd); - } - - const GpuScope scope(timer, frame_index, cmd, "GI irradiance"); - sync::BarrierBatch barriers; - barriers.image(m_atlas_state, sync::Usage::compute_storage_write); - barriers.flush(cmd); - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_irradiance_pipeline.getPipeline()); - const uint32_t c0 = 0; - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(uint32_t), &c0); - // Mirrors gi_merge irradianceMain with two tiles per group - cmd.dispatch(k_atlas_tiles_per_row / 2, groups(m_cascades[0].deposit_capacity, k_atlas_tiles_per_row), 1); - barriers.image(m_atlas_state, sync::Usage::shader_sampled); - barriers.flush(cmd); -} - -auto GiPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView { - ZoneScoped; - const auto* renderer = VulkanRenderer::instance; - const auto* frame = renderer->renderingFrame(); - const GiSettings& settings = renderer->giSettings(); - const bool enabled = settings.enabled.load(std::memory_order_relaxed) && - settings.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_cascades; - // Lighting falls back to the flat ambient once the frame it reads says no GI - if (!enabled && m_published_valid) { - sync::BarrierBatch barriers; - barriers.memory(sync::Usage::fragment_storage_read, sync::Usage::transfer_dst); - barriers.memory(sync::Usage::compute_storage_read, sync::Usage::transfer_dst); - barriers.flush(cmd); - cmd.fillBuffer(**m_published, 0, vk::WholeSize, 0u); - barriers.memory(sync::Usage::transfer_dst, sync::Usage::fragment_storage_read); - barriers.memory(sync::Usage::transfer_dst, sync::Usage::compute_storage_read); - barriers.flush(cmd); - m_published_valid = false; - } - if (frame == nullptr || frame_index >= m_probe_sets.size() || !enabled || !renderer->getDepthView() || - !renderer->getSceneNormalView()) { - return source_view; - } - - // The fence of this slot was waited on so its last readback is complete - readStats(frame_index); - gatherDirty(); - - m_quality = resolveQuality(); - const Quality& quality = m_quality; - if (quality.level == GiSettings::k_quality_custom && - quality.step > std::clamp(settings.ray_step.load(std::memory_order_relaxed), 1u, 4u) && !m_spawn_step_logged) { - m_spawn_step_logged = true; - TOAST_INFO("Render", "GI custom ray step raised to {} to fit the spawn list", quality.step); - } - const uint32_t cascades = quality.cascades; - const uint32_t step = quality.step; - const float spacing = std::max(quality.spacing, 0.01f); - const KeySettings keys { - .spacing = spacing, - .lod_distance = std::clamp(quality.lod_distance, 0.25f, spacing * k_max_cells_to_lod), - }; - const bool carry = m_key_settings.has_value() && *m_key_settings == keys; - const uint32_t debug_view = settings.debug_view.load(std::memory_order_relaxed); - const uint32_t debug_mode = std::min(settings.debug_mode.load(std::memory_order_relaxed), 5u); - - // Lighting keeps reading the last published tables on skipped frames - if (carry && m_published_valid && debug_view == 0 && ++m_skipped < quality.interval) { - TracyPlot("GI: updated", static_cast(0)); - return source_view; - } - TracyPlot("GI: updated", static_cast(1)); - TracyPlot("GI: update interval", static_cast(quality.interval)); - m_skipped = 0; - m_key_settings = keys; - - ++m_frame; - const uint32_t parity = m_frame & 1u; - const bool history_known = writeDirty(frame_index); - const auto now = std::chrono::steady_clock::now(); - const float frame_seconds = m_last_record == std::chrono::steady_clock::time_point {} - ? 1.0f / 60.0f - : std::clamp(std::chrono::duration(now - m_last_record).count(), 0.001f, 0.1f); - m_last_record = now; - const float history_seconds = settings.history_seconds.load(std::memory_order_relaxed); - float history = 1.0f; - if (settings.history_per_frame.load(std::memory_order_relaxed)) { - history = std::clamp(settings.history_blend.load(std::memory_order_relaxed), 0.005f, 1.0f); - } else if (history_seconds > 0.0f) { - history = std::clamp(1.0f - std::exp(-frame_seconds / history_seconds), 0.001f, 1.0f); - } - m_blend = history; - // Narrowest bucket of the top cascade so the march never coarsens past what any interval resolves - const float cone_slope = std::sqrt(4.0f * glm::pi() / static_cast(m_cascades[cascades - 1].directions)); - FrameData data { - .inverse_view_projection = glm::inverse(frame->frame_data.jittered_view_projection), - .camera = glm::vec4(frame->frame_data.camera_position, keys.spacing), - .lod = glm::vec4( - keys.lod_distance, - k_lod_overlap, - static_cast(settings.probe_lifetime.load(std::memory_order_relaxed)), - static_cast(step) - ), - .frame = glm::uvec4(m_frame, cascades, parity, carry ? 1u : 0u), - // The spawn pixel walks every position of its block so each pixel inserts once every step squared frames - .viewport = glm::uvec4(m_extent.width, m_extent.height, m_frame % step, (m_frame / step) % step), - .pool = glm::uvec4(m_pool_total, m_table_total, m_deposit_total, k_deposit_slots), - .rays = glm::vec4(k_interval_scale, static_cast(renderer->voxelSunReach()), k_deposit_fixed_scale, cone_slope), - .jitter = glm::vec4(r2Jitter(m_frame), history_known ? 1.0f - history : 0.0f, k_reset_history), - .secondary = glm::uvec4(k_max_points, quality.multibounce ? 1u : 0u, std::bit_cast(m_point_share), quality.points), - // Rare directions hold 2 / blend rays fading eight times slower than the blend so they average as many as busy ones - .limits = glm::vec4( - std::max(settings.max_ray_radiance.load(std::memory_order_relaxed), 0.01f), - history >= 1.0f ? 0.0f : 2.0f / history, - history_known ? 1.0f - (history / 8.0f) : 0.0f, - std::max(settings.intensity.load(std::memory_order_relaxed), 0.0f) - ), - }; - for (uint32_t i = 0; i < k_max_cascades; ++i) { - const Cascade& c = m_cascades[i]; - data.cascades[i] = glm::uvec4(c.table_offset, c.table_size - 1, c.pool_offset, c.capacity); - data.deposits[i] = glm::uvec4(c.deposit_offset, c.deposit_capacity, 0u, c.directions); - } - data.queues = glm::uvec4(m_spawn_capacity, m_spawn_capacity, m_spawn_capacity + k_max_points, 0u); - const auto& frame_allocation = m_frame_data[frame_index].getAllocation(); - std::memcpy(frame_allocation.getInfo().pMappedData, &data, sizeof(FrameData)); - frame_allocation.flush(0, sizeof(FrameData)); - - bindProbeSet(frame_index); - - // Lighting read the tables and pool of the last merge earlier in this frame - sync::BarrierBatch war; - war.memory(sync::Usage::fragment_storage_read, sync::Usage::compute_storage_write); - war.memory(sync::Usage::compute_storage_read, sync::Usage::compute_storage_write); - war.flush(cmd); - - const vk::PipelineLayout layout = *m_probe_layout.getPipelineLayout(); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eCompute, layout, 0, std::array {*m_probe_sets[frame_index]}, {} - ); - const auto dispatch = [&](const VulkanPipeline& pipeline, uint32_t cascade, uint32_t x, uint32_t y = 1, uint32_t carried = 0) { - cmd.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline.getPipeline()); - const std::array push {cascade, carried}; - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), push.data()); - cmd.dispatch(x, y, 1); - }; - - GpuTimer* timer = VulkanRenderer::instance->gpuTimer(); - const uint32_t spawn_x = (m_extent.width + step - 1) / step; - const uint32_t spawn_y = (m_extent.height + step - 1) / step; - { - const GpuScope scope(timer, frame_index, cmd, "GI probes"); - dispatch(m_clear_pipeline, 0, groups(m_table_total, k_group)); - computeBarrier(cmd); - for (uint32_t i = 0; i < cascades; ++i) { - dispatch(m_carry_pipeline, i, groups(m_cascades[i].capacity, k_group)); - } - computeBarrier(cmd); - dispatch(m_pixel_pipeline, 0, groups(spawn_x, k_pixel_group), groups(spawn_y, k_pixel_group)); - dispatch(m_point_pipeline, 0, groups(quality.points, k_group)); - computeBarrier(cmd); - for (uint32_t i = 0; i + 1 < cascades; ++i) { - dispatch(m_parent_pipeline, i, groups(m_cascades[i].table_size, k_group)); - computeBarrier(cmd); - } - for (uint32_t i = 0; i < cascades; ++i) { - dispatch(m_compact_pipeline, i, groups(m_cascades[i].table_size, k_group)); - } - computeBarrier(cmd); - for (uint32_t i = 0; i < cascades; ++i) { - dispatch(m_keep_pipeline, i, groups(m_cascades[i].capacity, k_group)); - } - computeBarrier(cmd); - } - { - const GpuScope scope(timer, frame_index, cmd, "GI deposits"); - for (uint32_t carried = 0; carried < 2; ++carried) { - for (uint32_t i = cascades; i-- > 0;) { - dispatch(m_slots_pipeline, i, groups(m_cascades[i].deposit_capacity, k_group), 1, carried); - computeBarrier(cmd); - } - } - dispatch(m_deposit_clear_pipeline, 0, k_stride_groups); - for (uint32_t i = 0; i + 1 < cascades; ++i) { - dispatch(m_link_pipeline, i, groups(m_cascades[i].deposit_capacity, k_group)); - } - dispatch(m_count_pipeline, 0, groups(spawn_x, k_pixel_group), groups(spawn_y, k_pixel_group)); - dispatch(m_point_count_pipeline, 0, groups(quality.points, k_group)); - computeBarrier(cmd); - for (uint32_t i = 0; i + 1 < cascades; ++i) { - dispatch(m_propagate_pipeline, i, groups(m_cascades[i].deposit_capacity, k_group)); - computeBarrier(cmd); - } - for (uint32_t i = cascades; i-- > 0;) { - dispatch(m_offset_pipeline, i, groups(m_cascades[i].deposit_capacity, k_group)); - computeBarrier(cmd); - } - } - bool traced = false; - { - const GpuScope scope(timer, frame_index, cmd, "GI trace"); - traced = recordTrace(cmd, frame_index, spawn_x, spawn_y, source_view); - // Runs without a trace too so a scene with no voxels still sees the sky - computeBarrier(cmd); - } - if (traced) { - const GpuScope scope(timer, frame_index, cmd, "GI shade"); - recordShade(cmd, frame_index, std::min(spawn_x * spawn_y, m_spawn_capacity) + m_quality.points); - computeBarrier(cmd); - } - { - const GpuScope scope(timer, frame_index, cmd, "GI merge"); - recordMerge(cmd, frame_index, cascades); - } - if (debug_view > 0 && debug_mode == 5) { - recordChange(cmd, frame_index, source_view); - } - - sync::BarrierBatch barriers; - // The copy of the frame before wrote the published frame too - barriers.memory(sync::Usage::transfer_dst, sync::Usage::transfer_dst); - barriers.memory(sync::Usage::compute_storage_write, sync::Usage::transfer_src); - barriers.memory(sync::Usage::compute_storage_write, sync::Usage::fragment_storage_read); - barriers.memory(sync::Usage::compute_storage_write, sync::Usage::compute_storage_read); - barriers.flush(cmd); - cmd.copyBuffer(**m_counters, *m_readback[frame_index], vk::BufferCopy(0, 0, sizeof(uint32_t) * k_counter_words)); - cmd.copyBuffer(*m_frame_data[frame_index], **m_published, vk::BufferCopy(0, 0, sizeof(FrameData))); - m_published_valid = true; - barriers.memory(sync::Usage::transfer_dst, sync::Usage::host_read); - barriers.memory(sync::Usage::transfer_dst, sync::Usage::fragment_storage_read); - barriers.memory(sync::Usage::transfer_dst, sync::Usage::compute_storage_read); - barriers.flush(cmd); - m_readback_valid[frame_index] = true; - m_readback_parity[frame_index] = parity; - m_readback_point_share[frame_index] = m_point_share; - m_readback_point_budget[frame_index] = quality.points; - m_readback_spawn_capacity[frame_index] = m_spawn_capacity; - - if (debug_view == 0 || !source_view || !m_debug_pipeline.isReady() || !m_debug_target.isReady()) { - return source_view; - } - return recordDebug(cmd, frame_index, source_view, debug_view - 1, debug_mode); -} - -auto GiPass::recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, uint32_t cascade, uint32_t mode) - -> vk::ImageView { - ZoneScoped; - const vk::ImageView depth_view = VulkanRenderer::instance->getOpaqueDepthView(); - const vk::ImageView normal_view = VulkanRenderer::instance->getOpaqueNormalView(); - const std::array wanted {source_view, depth_view, normal_view}; - if (m_debug_bound.update(frame_index, wanted)) { - DescriptorWriter writer; - writer.image( - *m_debug_sets[frame_index], - k_debug_source_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - source_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - writer.image( - *m_debug_sets[frame_index], - k_debug_depth_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - depth_view, - vk::ImageLayout::eDepthReadOnlyOptimal - ); - writer.image( - *m_debug_sets[frame_index], - k_debug_normal_binding, - vk::DescriptorType::eCombinedImageSampler, - *m_point_sampler, - normal_view, - vk::ImageLayout::eShaderReadOnlyOptimal - ); - writer.flush(m_core->getDevice()); - } - - const vk::PipelineLayout layout = *m_debug_layout.getPipelineLayout(); - m_debug_target.beginScope(cmd); - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_debug_pipeline.getPipeline()); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eGraphics, layout, 0, std::array {*m_debug_sets[frame_index]}, {} - ); - const std::array push {cascade, mode}; - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(push), push.data()); - cmd.draw(3, 1, 0, 0); - m_debug_target.endScope(cmd); - return m_debug_target.view(); -} - -} diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_pass.hpp deleted file mode 100644 index 8a8aadf34..000000000 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.hpp +++ /dev/null @@ -1,318 +0,0 @@ -/// @file gi_pass.hpp -/// @author dario -/// @date 22/10/2026 - -#pragma once - -#include "toast/renderer/core/descriptor_cache.hpp" -#include "toast/renderer/core/gpu_sync.hpp" -#include "toast/renderer/core/vulkan_common.hpp" -#include "toast/renderer/lighting/gi_dirty_boxes.hpp" -#include "toast/renderer/passes/post_process_pass_base.hpp" -#include "toast/renderer/resources/post_process_target.hpp" -#include "toast/renderer/resources/scene_descriptor_set.hpp" -#include "toast/renderer/shaders/shader_layout.hpp" -#include "toast/renderer/shaders/vulkan_pipeline.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace renderer { -class VulkanCore; -class VoxelGpuStorage; - -class GiPass : public IPostProcessPass { -public: - static constexpr uint32_t k_max_cascades = 6; - /// c0 probes and every cascade above holds a quarter down to k_min_capacity - static constexpr uint32_t k_base_capacity = 65536; - static constexpr uint32_t k_min_capacity = 1024; - /// Shared by every cascade and handed out top cascade first - static constexpr uint32_t k_deposit_slots = 1u << 23; - /// Mirrors gi_common kGiAtlasTilesPerRow and kGiAtlasRows and caps the c0 deposit probes at one tile each - static constexpr uint32_t k_atlas_tiles_per_row = 256; - static constexpr uint32_t k_atlas_rows = 128; - static constexpr uint32_t k_atlas_tiles = k_atlas_tiles_per_row * k_atlas_rows; - static constexpr uint32_t k_max_points = 65536; - - struct Stats { - uint32_t cascades = 0; - std::array probes {}; - /// Probes seen within gi_common kGiKeepFrames and the rest are carried without storage - std::array seen {}; - std::array capacity {}; - std::array deposits {}; - std::array deposit_capacity {}; - /// Mean rays of history behind one direction of a deposit probe - std::array depth {}; - uint32_t table_full = 0; - uint32_t pool_full = 0; - uint32_t deposit_full = 0; - uint32_t rays = 0; - uint32_t slots = 0; - uint32_t moved = 0; - uint32_t appeared = 0; - uint32_t edits = 0; - /// Meters including bodies under the motion threshold so physics jitter shows up - float largest_motion = 0.0f; - uint32_t invalidated = 0; - uint32_t fresh = 0; - float blend = 0.0f; - /// Hit points the last trace stored for the secondary cache and the ones past the buffer - uint32_t points = 0; - uint32_t points_dropped = 0; - float point_share = 0.0f; - uint32_t quality = 0; - uint32_t ray_step = 0; - uint32_t update_interval = 0; - uint32_t point_budget = 0; - }; - - GiPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent); - - [[nodiscard]] - auto name() const -> std::string_view override { - return "Radiance cascades"; - } - - auto record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView override; - - void onResize(vk::Extent2D extent) override; - - /// A few frames old since it is read back once the fence of its frame passed - [[nodiscard]] - auto stats() const -> Stats; - - /// Set 0 buffers lighting samples by gi_sample binding name - [[nodiscard]] - auto sceneBuffer(std::string_view name) const -> vk::Buffer; - - [[nodiscard]] - auto irradianceView() const -> vk::ImageView { - return m_atlas_view.has_value() ? **m_atlas_view : vk::ImageView {}; - } - - [[nodiscard]] - auto irradianceSampler() const -> vk::Sampler { - return *m_linear_sampler; - } - -private: - /// Mirrors gi_common GiFrame - struct FrameData { - glm::mat4 inverse_view_projection {1.0f}; - glm::vec4 camera {0.0f}; - glm::vec4 lod {0.0f}; - glm::uvec4 frame {0u}; - glm::uvec4 viewport {0u}; - glm::uvec4 pool {0u}; - glm::vec4 rays {0.0f}; - glm::vec4 jitter {0.0f}; - glm::uvec4 secondary {0u}; - glm::vec4 limits {0.0f}; - std::array cascades {}; - std::array deposits {}; - glm::uvec4 queues {0u}; - }; - - /// Mirrors gi_common kGiCounter layout with counts per parity then table full pool full and seen per cascade - static constexpr uint32_t k_counter_words = 44; - static constexpr uint32_t k_counter_table_full = 16; - static constexpr uint32_t k_counter_pool_full = 17; - static constexpr uint32_t k_counter_seen = 18; - static constexpr uint32_t k_counter_deposit_full = 24; - static constexpr uint32_t k_counter_rays = 25; - static constexpr uint32_t k_counter_slots = 26; - static constexpr uint32_t k_counter_invalidated = 27; - static constexpr uint32_t k_counter_points = 28; - static constexpr uint32_t k_counter_points_dropped = 30; - static constexpr uint32_t k_counter_fresh = 31; - /// Sixteenths of the history rays of every 64th bucket per cascade - static constexpr uint32_t k_counter_depth = 32; - /// Pixels with a deposit that may exceed the spawn list - static constexpr uint32_t k_counter_spawn = 38; - /// Hits queued by pixel rays - static constexpr uint32_t k_counter_pixel_hits = 39; - /// Hits queued by point rays - static constexpr uint32_t k_counter_point_hits = 40; - - struct Cascade { - uint32_t table_offset = 0; - uint32_t table_size = 0; - uint32_t pool_offset = 0; - uint32_t capacity = 0; - uint32_t deposit_offset = 0; - uint32_t deposit_capacity = 0; - uint32_t directions = 0; - }; - - /// The cost knobs of renderer.gi.quality - struct Quality { - uint32_t level = 0; - uint32_t step = 2; - uint32_t cascades = 5; - float spacing = 0.1f; - float lod_distance = 4.0f; - bool multibounce = true; - uint32_t points = k_max_points; - uint32_t interval = 1; - }; - - /// What decides a probe key so changing it drops every carried probe - struct KeySettings { - float spacing = 0.0f; - float lod_distance = 0.0f; - [[nodiscard]] - auto operator==(const KeySettings&) const -> bool = default; - }; - - void createLayout(); - void createBuffers(const VulkanCore& core); - auto createPipelines(const VulkanCore& core) -> bool; - void readStats(uint32_t frame_index); - void bindProbeSet(uint32_t frame_index); - auto bindRaySets(uint32_t frame_index, vk::ImageView scene_view) -> bool; - /// False when the ray sets could not bind so nothing was traced - auto recordTrace(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t spawn_x, uint32_t spawn_y, vk::ImageView scene_view) - -> bool; - void recordShade(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t rays); - void recordMerge(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t cascades); - void recordChange(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView scene_view); - /// Sized to the viewport so it is rebuilt on resize while the device is idle - void createChange(const VulkanCore& core); - auto resolveQuality() const -> Quality; - /// Every rendered frame so the boxes of skipped GI frames still reach the next one - void gatherDirty(); - /// @return false when the edits are no longer known so every probe must drop its history - auto writeDirty(uint32_t frame_index) -> bool; - auto recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, uint32_t cascade, uint32_t mode) - -> vk::ImageView; - - const VulkanCore* m_core = nullptr; - vk::Format m_scene_format = vk::Format::eUndefined; - vk::Extent2D m_extent {}; - - std::array m_cascades {}; - uint32_t m_table_total = 0; - uint32_t m_pool_total = 0; - uint32_t m_deposit_total = 0; - - ShaderLayout m_probe_layout; - VulkanPipeline m_clear_pipeline; - VulkanPipeline m_carry_pipeline; - VulkanPipeline m_pixel_pipeline; - VulkanPipeline m_point_pipeline; - VulkanPipeline m_parent_pipeline; - VulkanPipeline m_compact_pipeline; - VulkanPipeline m_keep_pipeline; - VulkanPipeline m_slots_pipeline; - VulkanPipeline m_deposit_clear_pipeline; - VulkanPipeline m_link_pipeline; - VulkanPipeline m_count_pipeline; - VulkanPipeline m_point_count_pipeline; - VulkanPipeline m_propagate_pipeline; - VulkanPipeline m_offset_pipeline; - - /// gi_rays with the scene in set 0 the voxel storage and trace scene in set 1 and the probes in set 2 - ShaderLayout m_ray_layout; - VulkanPipeline m_ray_pipeline; - VulkanPipeline m_point_trace_pipeline; - VulkanPipeline m_shade_pipeline; - VulkanPipeline m_change_pipeline; - SceneDescriptorSets m_ray_scene_sets; - std::vector m_ray_storage_sets; - DescriptorCache> m_ray_storage_bound; - std::vector m_ray_sets; - DescriptorCache> m_ray_bound; - /// Reflection keeps gVoxelInstances only when the trace code reads it - bool m_ray_instances_bound = false; - - /// gi_merge with the scene in set 0 for the sky and the cascades in set 1 - ShaderLayout m_merge_layout; - VulkanPipeline m_merge_pipeline; - VulkanPipeline m_irradiance_pipeline; - SceneDescriptorSets m_merge_scene_sets; - std::vector m_merge_sets; - - ShaderLayout m_debug_layout; - VulkanPipeline m_debug_pipeline; - PostProcessTarget m_debug_target; - - vk::raii::Sampler m_point_sampler = nullptr; - vk::raii::Sampler m_linear_sampler = nullptr; - - std::optional m_table_keys; - std::optional m_table_flags; - std::optional m_table_previous; - std::optional m_table_values; - std::optional m_table_cells; - std::optional m_pool; - std::optional m_counters; - std::optional m_deposit_pool; - std::optional m_parent; - std::optional m_ray_counts; - std::optional m_deposits; - std::optional m_deposit_slots; - std::optional m_neighbours; - std::optional m_merged; - /// FrameData of the last merge so lighting next frame reads the frame its tables belong to - std::optional m_published; - /// Two halves by pool parity of gi_common GiHistory - std::optional m_history; - std::optional m_history_source; - /// Mirrors gi_common GiPoint in two halves by pool parity - std::optional m_points; - /// Per pixel float4 of gi_rays changeMain - std::optional m_change; - /// Pixels with a deposit packed x | y << 16 sized to the most any preset spawns - std::optional m_spawn; - uint32_t m_spawn_capacity = 0; - /// Off screen hits as uint4 with the pixel rays in the spawn capacity then the point rays in k_max_points - std::optional m_hits; - bool m_spawn_overflow_logged = false; - bool m_spawn_step_logged = false; - std::vector m_dirty; - - std::vector m_dirty_stats; - /// gi_probes gDirty holds GiDirtyBoxes::k_max_boxes - GiDirtyBoxes m_dirty_boxes; - uint32_t m_skipped = 0; - Quality m_quality; - /// Kept in shader read layout between frames - std::optional m_atlas; - std::optional m_atlas_view; - sync::ImageState m_atlas_state; - std::vector m_frame_data; - std::vector m_readback; - std::vector m_readback_valid; - /// Pool parity the counts in each readback belong to - std::vector m_readback_parity; - /// Share of off screen hits each readback frame kept so the next share can size the demand - std::vector m_readback_point_share; - std::vector m_readback_point_budget; - /// Spawn list capacity each readback frame was recorded with - std::vector m_readback_spawn_capacity; - float m_point_share = 0.5f; - - std::vector m_probe_sets; - DescriptorCache> m_probe_bound; - std::vector m_debug_sets; - DescriptorCache> m_debug_bound; - - bool m_published_valid = false; - uint32_t m_frame = 0; - std::chrono::steady_clock::time_point m_last_record; - float m_blend = 0.05f; - std::optional m_key_settings; - - mutable std::mutex m_stats_mutex; - Stats m_stats; -}; - -} diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp index 8caacaaf1..d702bf72e 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp @@ -63,28 +63,38 @@ TracedSpecularPass::TracedSpecularPass(const VulkanCore& core, vk::Format scene_ return; } - const auto build_pipeline = - [&](VulkanPipeline& pipeline, vk::Format format, vk::Extent2D target_extent, const char* entry, const char* debug_name) { - VulkanPipeline::Config config; - config.pipeline_type = VulkanPipeline::PipelineType::graphics; - config.debug_name = debug_name; - config.color_format = format; - // Roughness and the no trace mark live in alpha - config.write_color_alpha = true; - config.extent = target_extent; - config.shader_spirv = shader->spirv; - config.fragment_entry = entry; - config.pipeline_layout = *m_layout.getPipelineLayout(); - config.vertex_bindings = {}; - config.vertex_attributes = {}; - config.cull_mode = vk::CullModeFlagBits::eNone; - config.depth_test = false; - config.depth_write = false; - pipeline.rebuild(core, config); - }; + const auto build_pipeline = [&](VulkanPipeline& pipeline, + vk::Format format, + vk::Extent2D target_extent, + const char* entry, + const char* debug_name, + std::optional extra = std::nullopt) { + VulkanPipeline::Config config; + if (extra.has_value()) { + config.extra_color_formats = {*extra}; + config.write_extra_color = true; + config.extra_blend_mask = 0u; + } + config.pipeline_type = VulkanPipeline::PipelineType::graphics; + config.debug_name = debug_name; + config.color_format = format; + // Roughness and the no trace mark live in alpha + config.write_color_alpha = true; + config.extent = target_extent; + config.shader_spirv = shader->spirv; + config.fragment_entry = entry; + config.pipeline_layout = *m_layout.getPipelineLayout(); + config.vertex_bindings = {}; + config.vertex_attributes = {}; + config.cull_mode = vk::CullModeFlagBits::eNone; + config.depth_test = false; + config.depth_write = false; + pipeline.rebuild(core, config); + }; const vk::Extent2D half = PostProcessTarget::halfExtent(extent); build_pipeline(m_surface_pipeline, k_surface_format, half, "surfaceMain", "TracedSpecular Surface"); - build_pipeline(m_trace_pipeline, k_trace_format, half, "traceMain", "TracedSpecular Trace"); + build_pipeline(m_trace_pipeline, k_trace_format, half, "traceMain", "TracedSpecular Trace", k_hit_format); + build_pipeline(m_shade_pipeline, k_trace_format, half, "shadeMain", "TracedSpecular Shade"); build_pipeline(m_resolve_pipeline, k_trace_format, half, "resolveMain", "TracedSpecular Resolve"); build_pipeline(m_temporal_pipeline, k_trace_format, half, "temporalMain", "TracedSpecular Temporal"); build_pipeline(m_composite_pipeline, scene_format, extent, "compositeMain", "TracedSpecular Composite"); @@ -98,9 +108,9 @@ TracedSpecularPass::TracedSpecularPass(const VulkanCore& core, vk::Format scene_ createSets(core); createTargets(core, extent); - m_ready = m_surface_pipeline.isReady() && m_trace_pipeline.isReady() && m_resolve_pipeline.isReady() && - m_temporal_pipeline.isReady() && m_composite_pipeline.isReady() && m_pyramid_pipeline.isReady() && - m_filter_pipeline.isReady() && !m_scene_sets.empty() && !m_storage_sets.empty(); + m_ready = m_surface_pipeline.isReady() && m_trace_pipeline.isReady() && m_shade_pipeline.isReady() && + m_resolve_pipeline.isReady() && m_temporal_pipeline.isReady() && m_composite_pipeline.isReady() && + m_pyramid_pipeline.isReady() && m_filter_pipeline.isReady() && !m_scene_sets.empty() && !m_storage_sets.empty(); if (m_ready) { TOAST_INFO("Render", "TracedSpecularPass ready (GGX rays traced at half resolution)"); } @@ -164,6 +174,7 @@ void TracedSpecularPass::createTargets(const VulkanCore& core, vk::Extent2D exte m_target.create(core, extent, m_scene_format, "TracedSpecular"); m_surface.create(core, half, k_surface_format, "TracedSpecular Surface"); m_trace.create(core, half, k_trace_format, "TracedSpecular Trace"); + m_hit.create(core, half, k_hit_format, "TracedSpecular Hit"); m_resolved.create(core, half, k_trace_format, "TracedSpecular Resolved"); m_history[0].create(core, half, k_trace_format, "TracedSpecular History0"); m_history[1].create(core, half, k_trace_format, "TracedSpecular History1"); @@ -324,6 +335,7 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: m_pyramid_view.has_value() ? **m_pyramid_view : vk::ImageView {}, m_hiz.view(), m_filtered.view(), + m_hit.view(), }; if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { return source_view; @@ -396,7 +408,49 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: sync::transition(cmd, m_pyramid_state, sync::Usage::shader_sampled); } draw(m_surface, m_surface_pipeline, "TracedSpecular surface"); - draw(m_trace, m_trace_pipeline, "TracedSpecular trace"); + + // Trace and shade apart so the walk never holds the hit lighting registers, the shade draw loads the trace and lights its hits + const auto draw_into = [&](std::span targets, + vk::AttachmentLoadOp load, + const VulkanPipeline& pipeline, + std::string_view scope_name) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, scope_name); + sync::BarrierBatch to_attachment; + std::array attachments {}; + for (size_t i = 0; i < targets.size(); ++i) { + to_attachment.image(targets[i]->state(), sync::Usage::color_attachment); + attachments[i].imageView = targets[i]->view(); + attachments[i].imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + attachments[i].loadOp = load; + attachments[i].storeOp = vk::AttachmentStoreOp::eStore; + } + to_attachment.flush(cmd); + const vk::Extent2D extent = targets[0]->extent(); + vk::RenderingInfo rendering_info {}; + rendering_info.renderArea = vk::Rect2D({0, 0}, extent); + rendering_info.layerCount = 1; + rendering_info.colorAttachmentCount = static_cast(targets.size()); + rendering_info.pColorAttachments = attachments.data(); + cmd.beginRendering(rendering_info); + cmd.setViewport( + 0, std::array {vk::Viewport(0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f)} + ); + cmd.setScissor(0, std::array {vk::Rect2D({0, 0}, extent)}); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.getPipeline()); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, layout, k_specular_scene_set, sets, {}); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(Params), ¶ms); + cmd.draw(3, 1, 0, 0); + cmd.endRendering(); + sync::BarrierBatch to_sampled; + for (const PostProcessTarget* target : targets) { + to_sampled.image(target->state(), sync::Usage::shader_sampled); + } + to_sampled.flush(cmd); + }; + const std::array trace_targets {&m_trace, &m_hit}; + draw_into(trace_targets, vk::AttachmentLoadOp::eDontCare, m_trace_pipeline, "TracedSpecular trace"); + const std::array shade_targets {&m_trace}; + draw_into(shade_targets, vk::AttachmentLoadOp::eLoad, m_shade_pipeline, "TracedSpecular shade"); draw(m_resolved, m_resolve_pipeline, "TracedSpecular resolve"); draw(history_write, m_temporal_pipeline, "TracedSpecular temporal"); draw(m_filtered, m_filter_pipeline, "TracedSpecular filter"); diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp index 59ad1c210..65eda1429 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp @@ -62,13 +62,15 @@ class TracedSpecularPass : public IPostProcessPass { static constexpr vk::Format k_trace_format = vk::Format::eR16G16B16A16Sfloat; /// voxel_specular.slang packSurface static constexpr vk::Format k_surface_format = vk::Format::eR32G32B32A32Uint; + /// voxel_specular.slang gHit, the distance and a flag where the trace left a voxel hit for the shade pass + static constexpr vk::Format k_hit_format = vk::Format::eR32G32Uint; /// Last frame resolve box filtered to half resolution then halved per level so rough screen hits read it blurred static constexpr vk::Format k_pyramid_format = vk::Format::eR16G16B16A16Sfloat; /// Mirrors voxel_specular.slang kPyramidLevels static constexpr uint32_t k_pyramid_levels = 6; - static constexpr uint32_t k_image_bindings = 16; + static constexpr uint32_t k_image_bindings = 17; void createSets(const VulkanCore& core); void createTargets(const VulkanCore& core, vk::Extent2D extent); @@ -85,6 +87,7 @@ class TracedSpecularPass : public IPostProcessPass { ShaderLayout m_layout; VulkanPipeline m_surface_pipeline; VulkanPipeline m_trace_pipeline; + VulkanPipeline m_shade_pipeline; VulkanPipeline m_resolve_pipeline; VulkanPipeline m_temporal_pipeline; VulkanPipeline m_composite_pipeline; @@ -106,6 +109,7 @@ class TracedSpecularPass : public IPostProcessPass { PostProcessTarget m_surface; PostProcessTarget m_trace; + PostProcessTarget m_hit; PostProcessTarget m_resolved; /// The temporal pass reads one and writes the other std::array m_history; diff --git a/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp b/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp index 749e193b1..de640e619 100644 --- a/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp +++ b/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp @@ -286,37 +286,50 @@ auto LensFlarePass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag }; const uint32_t glare_instances = ((m_quarter_a.extent.width + 1) / 2) * ((m_quarter_a.extent.height + 1) / 2); + // One scope per stage so the perf window splits the pass cost + GpuTimer* timer = VulkanRenderer::instance->gpuTimer(); using Load = vk::AttachmentLoadOp; - params.texel = texel(output, m_quarter_a.extent, 2.0f); - draw(cmd, m_threshold_pipeline, *sets.sets[step_threshold], m_quarter_a, params, Load::eDontCare, 3, 1); - - params.texel = texel(m_quarter_a.extent, m_glare_target.extent, 1.0f); - draw(cmd, m_glare_pipeline, *sets.sets[step_glare], m_glare_target, params, Load::eClear, k_glare_vertices, glare_instances); - - for (uint32_t level = 0; level < k_streak_levels; ++level) { - const vk::Extent2D from = level == 0 ? m_quarter_a.extent : m_streak[level - 1].extent; - params.texel = texel(from, m_streak[level].extent, 1.0f); - draw(cmd, m_streak_down_pipeline, *sets.sets[step_streak_down + level], m_streak[level], params, Load::eDontCare, 3, 1); + { + const GpuScope scope(timer, frame_index, cmd, "Lens flare threshold"); + params.texel = texel(output, m_quarter_a.extent, 2.0f); + draw(cmd, m_threshold_pipeline, *sets.sets[step_threshold], m_quarter_a, params, Load::eDontCare, 3, 1); } - for (uint32_t level = k_streak_levels - 1; level-- > 0;) { - params.texel = texel(m_streak[level + 1].extent, m_streak[level].extent, 1.0f); - draw(cmd, m_streak_up_pipeline, *sets.sets[step_streak_up + level], m_streak[level], params, Load::eLoad, 3, 1); + { + const GpuScope scope(timer, frame_index, cmd, "Lens flare glare"); + params.texel = texel(m_quarter_a.extent, m_glare_target.extent, 1.0f); + draw(cmd, m_glare_pipeline, *sets.sets[step_glare], m_glare_target, params, Load::eClear, k_glare_vertices, glare_instances); } + { + const GpuScope scope(timer, frame_index, cmd, "Lens flare streaks"); + for (uint32_t level = 0; level < k_streak_levels; ++level) { + const vk::Extent2D from = level == 0 ? m_quarter_a.extent : m_streak[level - 1].extent; + params.texel = texel(from, m_streak[level].extent, 1.0f); + draw(cmd, m_streak_down_pipeline, *sets.sets[step_streak_down + level], m_streak[level], params, Load::eDontCare, 3, 1); + } + for (uint32_t level = k_streak_levels - 1; level-- > 0;) { + params.texel = texel(m_streak[level + 1].extent, m_streak[level].extent, 1.0f); + draw(cmd, m_streak_up_pipeline, *sets.sets[step_streak_up + level], m_streak[level], params, Load::eLoad, 3, 1); + } + } + { + const GpuScope scope(timer, frame_index, cmd, "Lens flare ghosts and halo"); + params.texel = texel(m_quarter_a.extent, m_eighth.extent, 1.0f); + draw(cmd, m_blur_down_pipeline, *sets.sets[step_blur_down], m_eighth, params, Load::eDontCare, 3, 1); - params.texel = texel(m_quarter_a.extent, m_eighth.extent, 1.0f); - draw(cmd, m_blur_down_pipeline, *sets.sets[step_blur_down], m_eighth, params, Load::eDontCare, 3, 1); - - params.texel = texel(m_eighth.extent, m_quarter_b.extent, 1.0f); - draw(cmd, m_blur_up_pipeline, *sets.sets[step_blur_up], m_quarter_b, params, Load::eDontCare, 3, 1); - - draw(cmd, m_chroma_pipeline, *sets.sets[step_chroma], m_quarter_a, params, Load::eDontCare, 3, 1); - draw(cmd, m_ghosts_pipeline, *sets.sets[step_ghosts], m_flares, params, Load::eDontCare, 3, 1); - draw(cmd, m_halo_pipeline, *sets.sets[step_halo], m_flares, params, Load::eLoad, 3, 1); + params.texel = texel(m_eighth.extent, m_quarter_b.extent, 1.0f); + draw(cmd, m_blur_up_pipeline, *sets.sets[step_blur_up], m_quarter_b, params, Load::eDontCare, 3, 1); - params.texel = texel(m_flares.extent, output, 1.0f); - params.texel.z = 1.0f / static_cast(m_glare_target.extent.width); - params.texel.w = 1.0f / static_cast(m_glare_target.extent.height); - draw(cmd, m_mix_pipeline, *sets.sets[step_mix], m_composite, params, Load::eDontCare, 3, 1); + draw(cmd, m_chroma_pipeline, *sets.sets[step_chroma], m_quarter_a, params, Load::eDontCare, 3, 1); + draw(cmd, m_ghosts_pipeline, *sets.sets[step_ghosts], m_flares, params, Load::eDontCare, 3, 1); + draw(cmd, m_halo_pipeline, *sets.sets[step_halo], m_flares, params, Load::eLoad, 3, 1); + } + { + const GpuScope scope(timer, frame_index, cmd, "Lens flare mix"); + params.texel = texel(m_flares.extent, output, 1.0f); + params.texel.z = 1.0f / static_cast(m_glare_target.extent.width); + params.texel.w = 1.0f / static_cast(m_glare_target.extent.height); + draw(cmd, m_mix_pipeline, *sets.sets[step_mix], m_composite, params, Load::eDontCare, 3, 1); + } return **m_composite.view; } diff --git a/engine/src/toast/renderer/passes/post/taa_pass.cpp b/engine/src/toast/renderer/passes/post/taa_pass.cpp index 25ddc6e70..f301bf2ad 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.cpp @@ -79,7 +79,9 @@ void TaaPass::createResources(const VulkanCore& core) { void TaaPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { // DLSS writes the resolve as a storage image, R16G16B16A16Sfloat storage support is mandatory in Vulkan - const vk::ImageUsageFlags usage = m_dlss.available() ? vk::ImageUsageFlagBits::eStorage : vk::ImageUsageFlags {}; + // and clears it on a reset so it needs the transfer destination too + const vk::ImageUsageFlags usage = + m_dlss.available() ? vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferDst : vk::ImageUsageFlags {}; m_targets[0].create(core, extent, m_scene_format, "TaaPass History A", usage); m_targets[1].create(core, extent, m_scene_format, "TaaPass History B", usage); m_bound_views.invalidate(); @@ -238,6 +240,9 @@ auto TaaPass::recordDlss( barriers.image(target.state(), sync::Usage::compute_storage_write); barriers.image(depth.image, depth.range, depth.usage, sync::Usage::shader_sampled); barriers.flush(cmd); + // NGX clears the output on a reset before it writes it, and only a later dependency orders after the layout transition + barriers.memory(sync::Usage::compute_storage_write, sync::Usage::transfer_dst); + barriers.flush(cmd); DlssInputs inputs {}; inputs.color = source_view; diff --git a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp index c0bbccba6..892273ed5 100644 --- a/engine/src/toast/renderer/resources/scene_descriptor_set.cpp +++ b/engine/src/toast/renderer/resources/scene_descriptor_set.cpp @@ -4,7 +4,6 @@ #include "toast/renderer/passes/lighting/cluster_lighting_pass.hpp" #include "toast/renderer/passes/lighting/environment_pass.hpp" #include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" -#include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/passes/lighting/reflection_probe_pass.hpp" #include "toast/renderer/passes/lighting/shadow_pass.hpp" #include "toast/renderer/raytracing/ray_tracing_scene.hpp" @@ -111,21 +110,6 @@ void SceneDescriptorSets::create( continue; } - // Left unwritten for GiPass own sets since it is created after them and they never sample GI - if (binding.name == "gGiIrradiance") { - if (const auto* gi = VulkanRenderer::instance->giPass(); gi != nullptr) { - writer.image( - *m_sets[i], - binding.binding, - vk::DescriptorType::eCombinedImageSampler, - gi->irradianceSampler(), - gi->irradianceView(), - vk::ImageLayout::eShaderReadOnlyOptimal - ); - } - continue; - } - const bool is_probe_irradiance = binding.name == "gProbeIrradiance"; if (binding.name == "gProbeMaps" || is_probe_irradiance) { const auto* probes = VulkanRenderer::instance->getReflectionProbePass(); @@ -226,11 +210,6 @@ void SceneDescriptorSets::create( } else if (binding.name == "gBlueNoise") { buffer = VulkanRenderer::instance->getBlueNoiseBuffer(); descriptor_type = vk::DescriptorType::eStorageBuffer; - } else if (binding.name.starts_with("gGi")) { - if (const auto* gi = VulkanRenderer::instance->giPass(); gi != nullptr) { - buffer = gi->sceneBuffer(binding.name); - } - descriptor_type = vk::DescriptorType::eStorageBuffer; } else if (binding.name == "gIrradianceSH") { if (auto* probes = VulkanRenderer::instance->getReflectionProbePassMutable(); probes != nullptr) { buffer = probes->getShBuffer(); diff --git a/engine/src/toast/renderer/settings/gi_settings.hpp b/engine/src/toast/renderer/settings/gi_settings.hpp index 36341e1a8..73eb13b09 100644 --- a/engine/src/toast/renderer/settings/gi_settings.hpp +++ b/engine/src/toast/renderer/settings/gi_settings.hpp @@ -9,46 +9,15 @@ namespace renderer { -/// renderer.gi settings written by the settings thread and read by GiPass on the render thread +/// renderer.gi settings written by the settings thread and read by GiClipmapPass on the render thread struct GiSettings { static constexpr uint32_t k_quality_custom = 4; std::atomic_bool enabled {true}; - /// Low medium high epic and custom where only custom reads the cost knobs below + /// Low medium high epic and custom where only custom reads the clipmap knobs below std::atomic quality {2}; - /// GI frames run once every this many rendered frames - std::atomic update_interval {1}; - /// Off screen hits kept for the secondary cache each frame - std::atomic secondary_points {65536}; - /// Off screen hits seed and read a coarser secondary cache for every bounce past the first - std::atomic_bool multibounce {true}; - /// Meters between c0 probes at LOD 0 - std::atomic probe_spacing {0.1f}; - /// Chebyshev meters from the camera where LOD 1 starts - std::atomic lod_distance {4.0f}; - std::atomic cascades {5}; - /// Pixels per side of the block one probe insertion and later one ray comes from - std::atomic ray_step {2}; - std::atomic probe_lifetime {60}; - /// 0 keeps no history - std::atomic history_seconds {0.3f}; - /// Blend history_blend per frame instead of history_seconds - std::atomic_bool history_per_frame {false}; - /// Share of a new frame when history_per_frame is on and 1 keeps no history - std::atomic history_blend {0.03f}; - /// Meters a body has to move in a frame before GI treats it as a change and not physics jitter - std::atomic motion_threshold {0.01f}; - std::atomic max_ray_radiance {16.0f}; /// Scales bounced light where surfaces are lit and not where GI feeds its own bounces so it cannot run away std::atomic intensity {2.0f}; - /// 0 off and otherwise 1 + the cascade drawn - std::atomic debug_view {0}; - /// Mirrors gi_debug.slang kGiDebug with 0 cells 1 interval radiance 2 coverage 3 irradiance 4 history depth 5 change - std::atomic debug_mode {0}; - - static constexpr uint32_t k_backend_cascades = 0; - static constexpr uint32_t k_backend_clipmap = 1; - std::atomic backend {k_backend_cascades}; /// Meters per level 0 cell std::atomic clip_cell {0.2f}; std::atomic clip_resolution {128}; diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index 50f8c6b37..a91886caa 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -45,7 +45,7 @@ struct PresetKnobs { float glass_reflection_reach = 32.0f; }; -/// Low Medium High Epic without ray tracing, then Low RT Medium RT High RT Epic RT. Radiance cascades run in every tier +/// Low Medium High Epic without ray tracing, then Low RT Medium RT High RT Epic RT. The radiance clipmap runs in every tier constexpr std::array k_preset_tiers { { // Without ray tracing @@ -149,7 +149,7 @@ constexpr std::array k_preset_tiers { .glass_lit_surfaces = 1, .glass_reflection_reach = 8.0f}, {.ssr = true, - .ssao = true, + .ssao = false, .traced_specular = false, .specular_roughness = 0.4f, .specular_reach = 24.0f, @@ -168,7 +168,7 @@ constexpr std::array k_preset_tiers { .glass_lit_surfaces = 2, .glass_reflection_reach = 16.0f}, {.ssr = true, - .ssao = true, + .ssao = false, .traced_specular = true, .specular_roughness = 0.45f, .specular_reach = 24.0f, @@ -188,7 +188,7 @@ constexpr std::array k_preset_tiers { .glass_lit_surfaces = 3, .glass_reflection_reach = 24.0f}, {.ssr = true, - .ssao = true, + .ssao = false, .traced_specular = true, .specular_roughness = 0.6f, .specular_reach = 32.0f, @@ -221,16 +221,32 @@ struct PresetState { PresetState g_preset; -/// RT tiers fall back to the non RT tier of the same level when not tracing -auto activeKnobs() -> const PresetKnobs& { +/// DLSS Quality input share +constexpr float k_laptop_render_scale = 2.0f / 3.0f; + +/// NVIDIA names its mobile parts "... Laptop GPU", and native size on one cost about 40% of the frame in the 4060 Laptop capture +auto laptopWithDlss(const VulkanCore& core) -> bool { + static const bool laptop = + core.dlssExtensionsEnabled() && + std::string_view(core.getPhysicalDevice().getProperties().deviceName.data()).find("Laptop") != std::string_view::npos; + return laptop; +} + +/// RT tiers fall back to the non RT tier of the same level when not tracing, and laptops render tiers at DLSS Quality at most +auto activeKnobs() -> PresetKnobs { if (g_preset.preset >= k_preset_custom) { return g_preset.knobs; } + const VulkanCore& core = g_preset.renderer->getCore(); uint32_t tier = g_preset.preset; - if (tier >= k_tiers_per_branch && !g_preset.renderer->getCore().isRayTracingSupported()) { + if (tier >= k_tiers_per_branch && !core.isRayTracingSupported()) { tier -= k_tiers_per_branch; } - return k_preset_tiers[tier]; + PresetKnobs knobs = k_preset_tiers[tier]; + if (laptopWithDlss(core)) { + knobs.render_scale = std::min(knobs.render_scale, k_laptop_render_scale); + } + return knobs; } void applyPreset() { @@ -444,7 +460,9 @@ void registerQuality(VulkanRenderer& renderer) { 1.0, {.label = "Render scale", .category = "Quality", - .description = "Share of the output resolution the world renders at before TAA upsamples it. Preset Custom only", + .description = + "Share of the output resolution the world renders at before TAA upsamples it. Presets cap it at 0.67 (DLSS Quality) " + "on a laptop GPU with DLSS. Preset Custom only", .min = 0.1, .max = 1.0, .step = 0.05} @@ -1319,9 +1337,9 @@ void registerGi(VulkanRenderer& renderer) { toast::settings::declareBool( "renderer.gi.enabled", true, - {.label = "Radiance cascades", + {.label = "Radiance clipmap", .category = "Global illumination", - .description = "World space radiance cascade probes. Preset Custom only"} + .description = "World space voxel clipmap that cones gather bounce light from. Preset Custom only"} ) .onChange(presetKnob(&PresetKnobs::gi_enabled, k_same_bool)); @@ -1331,7 +1349,7 @@ void registerGi(VulkanRenderer& renderer) { { .label = "Quality", .category = "Global illumination", - .description = "Rays per frame, cascades, probe spacing, multibounce and update rate. Custom uses the knobs below", + .description = "Clipmap resolution and level count. Custom uses the knobs below", .options = {"Low", "Medium", "High", "Epic", "Custom"} } ) @@ -1339,172 +1357,6 @@ void registerGi(VulkanRenderer& renderer) { return static_cast(std::clamp(v, 0, GiSettings::k_quality_custom)); })); - toast::settings::declareInt( - "renderer.gi.update_interval", - 1, - {.label = "Update interval", - .category = "Global illumination", - .description = "Rendered frames per GI update. Custom quality only", - .min = 1.0, - .max = 4.0} - ) - .onChange([&gi](int64_t v) { - gi.update_interval.store(static_cast(std::clamp(v, 1, 4)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.secondary_points", - 65536, - {.label = "Multibounce points", - .category = "Global illumination", - .description = "Off screen hits kept for the secondary cache per frame. Custom quality only", - .min = 1024.0, - .max = 65536.0} - ) - .onChange([&gi](int64_t v) { - gi.secondary_points.store(static_cast(std::clamp(v, 1024, 65536)), std::memory_order_relaxed); - }); - - toast::settings::declareBool( - "renderer.gi.multibounce", - true, - {.label = "Multibounce", - .category = "Global illumination", - .description = "GI rays that hit something the camera cannot see seed a coarser secondary probe cache and read it " - "back, so light keeps bouncing off screen. Costs about half again the rays. Custom quality only"} - ) - .onChange([&gi](bool enabled) { gi.multibounce.store(enabled, std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.probe_spacing", - 0.1, - {.label = "Probe spacing", - .category = "Global illumination", - .description = - "Meters between cascade 0 probes near the camera. Every cascade and every LOD doubles it. Custom quality only", - .min = 0.025, - .max = 1.0, - .step = 0.025} - ) - .onChange([&gi](double v) { gi.probe_spacing.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.lod_distance", - 4.0, - {.label = "LOD distance", - .category = "Global illumination", - .description = "Meters from the camera where probes start doubling their spacing. Custom quality only", - .min = 0.5, - .max = 64.0, - .step = 0.5} - ) - .onChange([&gi](double v) { gi.lod_distance.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareInt( - "renderer.gi.cascades", - 5, - {.label = "Cascades", - .category = "Global illumination", - .description = "Each cascade reaches four times farther than the one below. Custom quality only", - .min = 1.0, - .max = 6.0} - ) - .onChange([&gi](int64_t v) { - gi.cascades.store(static_cast(std::clamp(v, 1, 6)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.ray_resolution", - 1, - { - .label = "Ray resolution", - .category = "Global illumination", - .description = "Pixels that place probes and trace rays each frame. Custom quality only", - .options = {"Full", "Half", "Quarter"} - } - ) - .onChange([&gi](int64_t v) { - constexpr std::array k_steps {1, 2, 4}; - gi.ray_step.store(k_steps[static_cast(std::clamp(v, 0, 2))], std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.probe_lifetime", - 60, - {.label = "Probe lifetime", - .category = "Global illumination", - .description = "Frames a probe stays after no pixel needs it", - .min = 1.0, - .max = 600.0} - ) - .onChange([&gi](int64_t v) { - gi.probe_lifetime.store(static_cast(std::clamp(v, 1, 600)), std::memory_order_relaxed); - }); - - toast::settings::declareFloat( - "renderer.gi.history_seconds", - 0.3, - {.label = "History length", - .category = "Global illumination", - .description = "Seconds of light every probe direction averages, the same at any frame rate. Longer is smoother " - "in dark places lit only through gaps but follows moving lights more slowly, 0 keeps no history. " - "Voxel changes and moving bodies reset the probes around them either way", - .min = 0.0, - .max = 5.0, - .step = 0.05} - ) - .onChange([&gi](double v) { gi.history_seconds.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareBool( - "renderer.gi.history_per_frame", - false, - {.label = "Per frame history", - .category = "Global illumination", - .description = "Blend a fixed share of every frame into the history instead of a length in seconds. Less ghosting " - "at high frame rates, more flicker where light only reaches through thin gaps"} - ) - .onChange([&gi](bool enabled) { gi.history_per_frame.store(enabled, std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.history", - 0.03, - {.label = "History blend", - .category = "Global illumination", - .description = "Share of each new frame in the light of every probe direction while Per frame history is on. " - "Lower is smoother but follows moving lights more slowly, 1 keeps no history", - .min = 0.005, - .max = 1.0, - .step = 0.005} - ) - .onChange([&gi](double v) { gi.history_blend.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.motion_threshold", - 0.01, - {.label = "Motion threshold", - .category = "Global illumination", - .description = "Meters a voxel body has to move in one frame before the probes around it drop their history. " - "Raise it when resting physics bodies jitter and the perf window keeps reporting moved bodies", - .min = 0.0, - .max = 0.2, - .step = 0.001} - ) - .onChange([&gi](double v) { gi.motion_threshold.store(static_cast(v), std::memory_order_relaxed); }); - - toast::settings::declareFloat( - "renderer.gi.max_ray_radiance", - 16.0, - {.label = "Ray brightness clamp", - .category = "Global illumination", - .description = "Brightest a single GI ray hit may count as, keeping its colour. Rays rarely catch a small very bright " - "emitter like a lamp shade, so each catch jumps the light around it. Lower is steadier, higher keeps " - "more bounce from bright emitters", - .min = 0.5, - .max = 1000.0, - .step = 0.5} - ) - .onChange([&gi](double v) { gi.max_ray_radiance.store(static_cast(v), std::memory_order_relaxed); }); - toast::settings::declareFloat( "renderer.gi.intensity", 2.0, @@ -1518,54 +1370,6 @@ void registerGi(VulkanRenderer& renderer) { ) .onChange([&gi](double v) { gi.intensity.store(static_cast(v), std::memory_order_relaxed); }); - toast::settings::declareInt( - "renderer.gi.debug_view", - 0, - { - .label = "Probe view", - .category = "Global illumination", - .description = "Draws the probe cells of one cascade over the scene. Red has no probe and dim was carried from an " - "earlier frame", - .options = {"Off", "Cascade 0", "Cascade 1", "Cascade 2", "Cascade 3", "Cascade 4", "Cascade 5"} - } - ) - .onChange([&gi](int64_t v) { - gi.debug_view.store(static_cast(std::clamp(v, 0, 6)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.debug_mode", - 0, - { - .label = "Probe view shows", - .category = "Global illumination", - .description = "Probe cells, the accumulated radiance of the cascade interval, the share of directions facing the " - "surface that got a ray this frame, the merged irradiance lighting will read, which ignores the " - "cascade picked, or how many rays of history the directions facing the surface hold, red none, " - "yellow about 8, green 64 and up, or how much the irradiance at each pixel changes per frame, black " - "steady, blue 1%, yellow 5%, red 15% and up. Purple probes have no storage", - .options = {"Probe cells", "Interval radiance", "Coverage", "Irradiance", "History depth", "Irradiance change"} - } - ) - .onChange([&gi](int64_t v) { - gi.debug_mode.store(static_cast(std::clamp(v, 0, 5)), std::memory_order_relaxed); - }); - - toast::settings::declareInt( - "renderer.gi.backend", - 0, - { - .label = "Backend", - .category = "Global illumination", - .description = "Radiance clipmap is in development and only fills its voxel clipmap so far, lighting gets no GI " - "from it yet", - .options = {"Radiance cascades", "Radiance clipmap"} - } - ) - .onChange([&gi](int64_t v) { - gi.backend.store(static_cast(std::clamp(v, 0, 1)), std::memory_order_relaxed); - }); - toast::settings::declareFloat( "renderer.gi.clip_cell", 0.2, diff --git a/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp b/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp index 8fe564662..201252548 100644 --- a/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp +++ b/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp @@ -6,9 +6,44 @@ #include "toast/renderer/shaders/spirv_entry_points.hpp" +#include + namespace renderer { namespace { +auto statisticsFlags(const VulkanCore& core) -> vk::PipelineCreateFlags { + return core.isPipelineStatsEnabled() ? vk::PipelineCreateFlagBits::eCaptureStatisticsKHR : vk::PipelineCreateFlags {}; +} + +/// One line per stage the driver compiled, with whatever it reports such as register count, see TOAST_PIPELINE_STATS +void logPipelineStatistics(const VulkanCore& core, vk::Pipeline pipeline, const std::string& name) { + if (!core.isPipelineStatsEnabled()) { + return; + } + const auto& device = core.getDevice(); + const auto executables = device.getPipelineExecutablePropertiesKHR(vk::PipelineInfoKHR(pipeline)); + for (uint32_t index = 0; index < executables.size(); ++index) { + std::string line; + for (const auto& statistic : device.getPipelineExecutableStatisticsKHR(vk::PipelineExecutableInfoKHR(pipeline, index))) { + switch (statistic.format) { + case vk::PipelineExecutableStatisticFormatKHR::eBool32: + line += std::format("{}={} ", statistic.name.data(), statistic.value.b32 != VK_FALSE); + break; + case vk::PipelineExecutableStatisticFormatKHR::eInt64: + line += std::format("{}={} ", statistic.name.data(), statistic.value.i64); + break; + case vk::PipelineExecutableStatisticFormatKHR::eUint64: + line += std::format("{}={} ", statistic.name.data(), statistic.value.u64); + break; + case vk::PipelineExecutableStatisticFormatKHR::eFloat64: + line += std::format("{}={:.2f} ", statistic.name.data(), statistic.value.f64); + break; + } + } + TOAST_INFO("Render", "Pipeline stats {} [{}]: {}", name, executables[index].name.data(), line); + } +} + auto createShaderModule(const vk::raii::Device& device, std::span spirv) -> vk::raii::ShaderModule { if (spirv.empty()) { TOAST_CRITICAL("Render", "Shader SPIR-V bytecode is empty!"); @@ -270,6 +305,7 @@ auto createGraphicsPipelineImpl( } vk::GraphicsPipelineCreateInfo pipeline_ci {}; + pipeline_ci.flags = statisticsFlags(core); pipeline_ci.pNext = &rendering_ci; pipeline_ci.stageCount = static_cast(shader_stages.size()); pipeline_ci.pStages = shader_stages.data(); @@ -303,7 +339,7 @@ auto createComputePipelineImpl( {}, vk::ShaderStageFlagBits::eCompute, *shader_module, compute_entry.c_str() ); - const vk::ComputePipelineCreateInfo pipeline_ci({}, shader_stage_ci, pipeline_layout); + const vk::ComputePipelineCreateInfo pipeline_ci(statisticsFlags(core), shader_stage_ci, pipeline_layout); auto pipelines = device.createComputePipelines(core.getPipelineCache(), pipeline_ci); return std::move(pipelines[0]); } @@ -362,6 +398,7 @@ auto VulkanPipeline::rebuild(const VulkanCore& core, const Config& config) -> vo setDebugName(core, **m_shader_module, config.debug_name + " ShaderModule"); setDebugName(core, *m_pipeline, config.debug_name + " Pipeline"); } + logPipelineStatistics(core, *m_pipeline, config.debug_name); } auto VulkanPipeline::reset() -> void { diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 2dd42b7ae..9c7dfcfa4 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -94,7 +94,6 @@ class SelectionOutline; class SkinningPass; class VoxelPass; class DebrisPass; -class GiPass; class GiClipmapPass; class TracedSpecularPass; class TaaPass; @@ -372,6 +371,11 @@ class VulkanRenderer { return m_voxel_gi.view.has_value() ? **m_voxel_gi.view : vk::ImageView {}; } + [[nodiscard]] + auto getVoxelAmbientOcclusionView() const noexcept -> vk::ImageView { + return m_voxel_ao.view.has_value() ? **m_voxel_ao.view : vk::ImageView {}; + } + /// Marched and sampled diffuse over albedo before denoising [[nodiscard]] auto getVoxelNoisyDiffuseView() const noexcept -> vk::ImageView { @@ -981,8 +985,6 @@ class VulkanRenderer { return m_debris_pass; } - void setGiPass(GiPass* pass) noexcept { m_gi_pass = pass; } - void setGiClipmapPass(GiClipmapPass* pass) noexcept { m_gi_clipmap_pass = pass; } [[nodiscard]] @@ -1015,11 +1017,6 @@ class VulkanRenderer { return m_glass_backdrop_captured; } - [[nodiscard]] - auto giPass() const noexcept -> GiPass* { - return m_gi_pass; - } - [[nodiscard]] auto giSettings() noexcept -> GiSettings& { return m_gi_settings; @@ -1589,7 +1586,6 @@ class VulkanRenderer { VoxelPass* m_voxel_pass = nullptr; DebrisPass* m_debris_pass = nullptr; - GiPass* m_gi_pass = nullptr; GiClipmapPass* m_gi_clipmap_pass = nullptr; bool m_glass_backdrop_captured = false; bool m_glass_nearest_valid = false; @@ -1653,6 +1649,7 @@ class VulkanRenderer { bool m_voxel_denoised_indirect_frame = false; /// Half the render extent SceneColorResources m_voxel_gi; + SceneColorResources m_voxel_ao; SceneColorResources m_voxel_noisy_specular; /// The voxel lighting writes the parity one and reads the other std::array m_voxel_reservoirs; diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 82f1cbc7e..b5371d07a 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -262,7 +262,7 @@ void VulkanRenderer::updateVoxelTraceScene() { const VoxelGpuStorage* storage = render_frame->voxel_storage.get(); if (storage != nullptr && storage->isReady()) { // The clipmap fill reads this list so a capped volume would vanish from GI - const bool clipmap = m_gi_settings.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_clipmap; + const bool clipmap = m_gi_settings.enabled.load(std::memory_order_relaxed); const auto cap = clipmap ? VoxelTraceScene::k_max_volumes : std::min(voxelShadowInstances(), VoxelTraceScene::k_max_volumes); // Drawn volumes first so the cap drops off screen ones @@ -520,7 +520,7 @@ auto VulkanRenderer::recordVoxelScopes( m_scene_color.view.has_value() && m_scene_normal.view.has_value() && m_scene_indirect.view.has_value() && m_scene_ambient_specular.view.has_value() && m_scene_motion.view.has_value() && m_voxel_noisy_diffuse.view.has_value() && m_voxel_noisy_specular.view.has_value() && m_voxel_reservoirs[0].view.has_value() && - m_voxel_reservoirs[1].view.has_value() && m_voxel_candidate_reservoirs.view.has_value(); + m_voxel_reservoirs[1].view.has_value() && m_voxel_candidate_reservoirs.view.has_value() && m_voxel_ao.view.has_value(); if (m_voxel_pass == nullptr || !m_voxel_pass->isEnabled() || !targets_ready || m_depth_resources.state.usage != sync::Usage::depth_attachment || !m_voxel_pass->prepare(m_current_frame)) { // SSAO binds it every frame, so it must leave the undefined layout even when no voxel scope records @@ -688,16 +688,22 @@ auto VulkanRenderer::recordVoxelScopes( barriers.image(lighting_reservoirs.state, sync::Usage::color_attachment); barriers.image(m_voxel_reservoirs[1 - m_voxel_reservoir_parity].state, sync::Usage::fragment_sampled); barriers.image(m_scene_motion.state, sync::Usage::fragment_sampled); + // The G-buffer set binds it every frame and only the ambient upsample reads it + barriers.image(m_voxel_ao.state, sync::Usage::fragment_sampled); barriers.flush(cmd); if (m_voxel_gi.view.has_value()) { if (m_voxel_pass->giGatherActive()) { barriers.image(m_voxel_gi.state, sync::Usage::color_attachment); barriers.flush(cmd); - const vk::Rect2D half { + vk::Rect2D half { { 0, 0}, {(scissor.extent.width + 1) / 2, (scissor.extent.height + 1) / 2} }; + // Only the checkerboard pixels, two per texel of a row + if (m_voxel_pass->giGatherPacked()) { + half.extent.width = (half.extent.width + 1) / 2; + } const std::array gather_attachments {attachment(m_voxel_gi, vk::AttachmentLoadOp::eDontCare, clear_zero)}; vk::RenderingInfo gather_info {}; gather_info.renderArea = half; @@ -763,6 +769,36 @@ auto VulkanRenderer::recordVoxelScopes( // Before the marched scope so occlusion scales only the indirect if (m_voxel_pass->ambientRaysActive()) { + // One ray per 2x2 block, upsampled by the full resolution scope below + barriers.image(m_voxel_ao.state, sync::Usage::color_attachment); + barriers.flush(cmd); + const vk::Rect2D half { + { 0, 0}, + {(scissor.extent.width + 1) / 2, (scissor.extent.height + 1) / 2} + }; + const std::array trace_attachments {attachment(m_voxel_ao, vk::AttachmentLoadOp::eDontCare, clear_zero)}; + vk::RenderingInfo trace_info {}; + trace_info.renderArea = half; + trace_info.layerCount = 1; + trace_info.colorAttachmentCount = static_cast(trace_attachments.size()); + trace_info.pColorAttachments = trace_attachments.data(); + cmd.beginRendering(trace_info); + cmd.setViewport( + 0, + std::array { + vk::Viewport {0.0f, 0.0f, static_cast(half.extent.width), static_cast(half.extent.height), 0.0f, 1.0f} + } + ); + cmd.setScissor(0, std::array {half}); + { + TracyVkZone(m_tracy_vk_ctx, cmd, "VoxelAmbientTrace"); + const GpuScope scope(m_gpu_timer.get(), m_current_frame, cmd, "Voxel ambient trace"); + m_voxel_pass->recordAmbientTrace(cmd, m_current_frame); + } + cmd.endRendering(); + barriers.image(m_voxel_ao.state, sync::Usage::fragment_sampled); + barriers.flush(cmd); + const std::array ambient_attachments {attachment(m_voxel_noisy_diffuse, vk::AttachmentLoadOp::eLoad, clear_zero)}; vk::RenderingInfo ambient_info {}; ambient_info.renderArea = scissor; @@ -842,6 +878,8 @@ auto VulkanRenderer::recordVoxelScopes( barriers.image(m_voxel_noisy_diffuse.state, sync::Usage::fragment_sampled); barriers.image(m_voxel_noisy_specular.state, sync::Usage::fragment_sampled); barriers.image(m_scene_motion.state, sync::Usage::fragment_sampled); + // The temporal pass writes its luminance for the composite taps + barriers.image(m_scene_indirect.state, sync::Usage::fragment_sampled); barriers.flush(cmd); { TracyVkZone(m_tracy_vk_ctx, cmd, "VoxelDenoiseTemporal"); diff --git a/engine/src/toast/renderer/vulkan_renderer_resources.cpp b/engine/src/toast/renderer/vulkan_renderer_resources.cpp index c21c228dc..32b88c8c6 100644 --- a/engine/src/toast/renderer/vulkan_renderer_resources.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_resources.cpp @@ -359,6 +359,7 @@ void VulkanRenderer::createSceneColorResources() { create(m_voxel_denoised_indirect, k_voxel_denoised_indirect_format, "VoxelDenoisedIndirect"); create(m_voxel_noisy_specular, k_voxel_noisy_format, "VoxelNoisySpecular"); create(m_voxel_gi, k_voxel_gi_format, "VoxelGi", {}, 2); + create(m_voxel_ao, k_voxel_ao_format, "VoxelAmbientOcclusion", {}, 2); create(m_voxel_reservoirs[0], k_voxel_reservoir_format, "VoxelReservoirs0"); create(m_voxel_reservoirs[1], k_voxel_reservoir_format, "VoxelReservoirs1"); create(m_voxel_candidate_reservoirs, k_voxel_reservoir_format, "VoxelCandidateReservoirs"); From 01ab3a873b65f7721420a80bac916d17df64bd4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Thu, 26 Nov 2026 12:01:02 +0100 Subject: [PATCH 5/8] dante just create the folder bro --- flake.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index a1e3c27f9..8517b5a31 100644 --- a/flake.nix +++ b/flake.nix @@ -155,7 +155,7 @@ export VCPKG_ROOT="${pkgs.vcpkg}/share/vcpkg" export NIX_SSL_CERT_FILE="${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt" export PKG_CONFIG="${pkgs.pkg-config}/bin/pkg-config" - # export VCPKG_DEFAULT_BINARY_CACHE="/var/cache/vcpkg" + export VCPKG_DEFAULT_BINARY_CACHE="/var/cache/vcpkg" export VCPKG_KEEP_ENV_VARS=$(env | grep -E '^(NIX_|PKG_CONFIG|VCPKG_DEFAULT_BINARY_CACHE)' | cut -d= -f1 | tr '\n' ';') export PROTOBUF_PROTOC="${pkgs.protobuf}/bin/protoc" export GRPC_PROTOC_PLUGIN="${pkgs.grpc}/bin/grpc_csharp_plugin" From d6d845bb20c9cc416ac035ae52088eea7419b395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Thu, 26 Nov 2026 12:23:36 +0100 Subject: [PATCH 6/8] fixed tidi --- engine/src/toast/renderer/passes/game/game_pass.hpp | 2 +- engine/src/toast/renderer/passes/post/taa_pass.cpp | 4 ++-- engine/src/toast/renderer/settings/renderer_settings.cpp | 2 +- engine/src/toast/renderer/upscale/dlss_upscaler.cpp | 1 + engine/src/toast/renderer/upscale/dlss_upscaler.hpp | 2 +- engine/src/toast/world/workspace_voxel.cpp | 2 +- 6 files changed, 7 insertions(+), 6 deletions(-) diff --git a/engine/src/toast/renderer/passes/game/game_pass.hpp b/engine/src/toast/renderer/passes/game/game_pass.hpp index 30830f5be..b5894c47e 100644 --- a/engine/src/toast/renderer/passes/game/game_pass.hpp +++ b/engine/src/toast/renderer/passes/game/game_pass.hpp @@ -70,7 +70,7 @@ struct GameViewDesc { const char* name = nullptr; uint32_t width = 256; uint32_t height = 256; - float clear_color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + std::array clear_color = {0.0f, 0.0f, 0.0f, 0.0f}; /// Own depth attachment cleared every frame bool depth = false; }; diff --git a/engine/src/toast/renderer/passes/post/taa_pass.cpp b/engine/src/toast/renderer/passes/post/taa_pass.cpp index f301bf2ad..8c7f2ad76 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.cpp @@ -220,7 +220,7 @@ auto TaaPass::recordDlss( source_view == renderer->getSceneColorView() ? renderer->getSceneColorImage() : PostProcessTarget::imageOf(source_view); const sync::ImageState& depth = renderer->getDepthState(); if (!color_image || !depth || !m_motion_fill.motionImage() || !m_motion_fill.reactiveImage()) { - const char* missing = !color_image ? "the TAA source view is neither the scene colour nor a post process target" + /*const char* missing = !color_image ? "the TAA source view is neither the scene colour nor a post process target" : !depth ? "the depth image is missing" : !m_motion_fill.motionImage() ? "the motion image is missing" : "the reactive image is missing"; @@ -228,7 +228,7 @@ auto TaaPass::recordDlss( if (!m_dlss_source_logged) { m_dlss_source_logged = true; TOAST_WARN("Render", "DLSS skipped: {}; using TAA", missing); - } + }*/ return false; } diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index a91886caa..403b979ff 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -228,7 +228,7 @@ constexpr float k_laptop_render_scale = 2.0f / 3.0f; auto laptopWithDlss(const VulkanCore& core) -> bool { static const bool laptop = core.dlssExtensionsEnabled() && - std::string_view(core.getPhysicalDevice().getProperties().deviceName.data()).find("Laptop") != std::string_view::npos; + std::string_view(core.getPhysicalDevice().getProperties().deviceName.data()).contains("Laptop"); return laptop; } diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.cpp b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp index cff5bdf74..80587bd91 100644 --- a/engine/src/toast/renderer/upscale/dlss_upscaler.cpp +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp @@ -87,6 +87,7 @@ auto discoveryInfo() -> NVSDK_NGX_FeatureDiscoveryInfo { auto extensionNames(const VkExtensionProperties* properties, uint32_t count) -> std::vector { std::vector names; + names.reserve(count); for (uint32_t i = 0; i < count; ++i) { names.push_back(properties[i].extensionName); } diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp index 0e460c190..75d082925 100644 --- a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp @@ -14,7 +14,7 @@ #include #include -struct NVSDK_NGX_Parameter; +struct NVSDK_NGX_Parameter; struct NVSDK_NGX_Handle; namespace renderer { diff --git a/engine/src/toast/world/workspace_voxel.cpp b/engine/src/toast/world/workspace_voxel.cpp index c82f69da6..63b2e240e 100644 --- a/engine/src/toast/world/workspace_voxel.cpp +++ b/engine/src/toast/world/workspace_voxel.cpp @@ -1589,7 +1589,7 @@ auto Workspace::pickSceneHit() -> std::optional { } else if (const auto sphere = node.as(); sphere.exists()) { t = rayBallEntry(origin, local_direction, glm::vec3(0.0f), sphere->radius); } else if (const auto capsule = node.as(); capsule.exists()) { - t = rayCapsuleEntry(origin, local_direction, capsule->radius, std::max(capsule->height * 0.5f - capsule->radius, 0.0f)); + t = rayCapsuleEntry(origin, local_direction, capsule->radius, std::max((capsule->height * 0.5f) - capsule->radius, 0.0f)); } if (t.has_value() && *t < collider_t) { collider_t = *t; From 11cceea6a72e46eae67b3ef8ac2a02f55f6aec53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Thu, 26 Nov 2026 19:28:49 +0100 Subject: [PATCH 7/8] tidi again --- engine/src/toast/backtrace.cpp | 16 +++++----- .../toast/renderer/passes/game/game_pass.hpp | 2 +- .../toast/renderer/passes/post/taa_pass.cpp | 4 +-- .../renderer/settings/renderer_settings.cpp | 5 ++- .../toast/renderer/upscale/dlss_upscaler.hpp | 2 +- engine/src/toast/world/workspace_voxel.cpp | 4 +-- tests/voxel/01-volume_sharing.cpp | 2 +- tests/voxel/02-solid_tracking.cpp | 30 +----------------- tests/voxel/03-mask_moments.cpp | 31 +++++++++++++++++++ 9 files changed, 49 insertions(+), 47 deletions(-) create mode 100644 tests/voxel/03-mask_moments.cpp diff --git a/engine/src/toast/backtrace.cpp b/engine/src/toast/backtrace.cpp index 1842b2903..6779e0e1a 100644 --- a/engine/src/toast/backtrace.cpp +++ b/engine/src/toast/backtrace.cpp @@ -39,15 +39,15 @@ void unloadDbghelpSymbols() noexcept { if (dbghelp == nullptr) { return; } - const auto enumModules = reinterpret_cast(GetProcAddress(dbghelp, "SymEnumerateModules64")); - const auto unloadModule = reinterpret_cast(GetProcAddress(dbghelp, "SymUnloadModule64")); - if (enumModules == nullptr || unloadModule == nullptr) { + const auto enum_modules = reinterpret_cast(GetProcAddress(dbghelp, "SymEnumerateModules64")); + const auto unload_module = reinterpret_cast(GetProcAddress(dbghelp, "SymUnloadModule64")); + if (enum_modules == nullptr || unload_module == nullptr) { return; } - const auto unloadSession = [&](HANDLE process) { + const auto unload_session = [&](HANDLE process) { std::vector bases; - enumModules( + enum_modules( process, [](PCSTR, DWORD64 base, PVOID user) -> BOOL { static_cast*>(user)->push_back(base); @@ -56,14 +56,14 @@ void unloadDbghelpSymbols() noexcept { &bases ); for (const DWORD64 base : bases) { - unloadModule(process, base); + unload_module(process, base); } }; - unloadSession(GetCurrentProcess()); + unload_session(GetCurrentProcess()); constexpr std::uintptr_t k_max_handle = 0x10000; for (std::uintptr_t value = 4; value < k_max_handle; value += 4) { - unloadSession(reinterpret_cast(value)); + unload_session(reinterpret_cast(value)); } } #endif diff --git a/engine/src/toast/renderer/passes/game/game_pass.hpp b/engine/src/toast/renderer/passes/game/game_pass.hpp index b5894c47e..44cccadc3 100644 --- a/engine/src/toast/renderer/passes/game/game_pass.hpp +++ b/engine/src/toast/renderer/passes/game/game_pass.hpp @@ -70,7 +70,7 @@ struct GameViewDesc { const char* name = nullptr; uint32_t width = 256; uint32_t height = 256; - std::array clear_color = {0.0f, 0.0f, 0.0f, 0.0f}; + std::array clear_color = {0.0f, 0.0f, 0.0f, 0.0f}; /// Own depth attachment cleared every frame bool depth = false; }; diff --git a/engine/src/toast/renderer/passes/post/taa_pass.cpp b/engine/src/toast/renderer/passes/post/taa_pass.cpp index 8c7f2ad76..d2b2a0a5d 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.cpp @@ -226,8 +226,8 @@ auto TaaPass::recordDlss( : "the reactive image is missing"; m_dlss.setRuntimeReason(missing); if (!m_dlss_source_logged) { - m_dlss_source_logged = true; - TOAST_WARN("Render", "DLSS skipped: {}; using TAA", missing); + m_dlss_source_logged = true; + TOAST_WARN("Render", "DLSS skipped: {}; using TAA", missing); }*/ return false; } diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index 403b979ff..0597c7cbf 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -226,9 +226,8 @@ constexpr float k_laptop_render_scale = 2.0f / 3.0f; /// NVIDIA names its mobile parts "... Laptop GPU", and native size on one cost about 40% of the frame in the 4060 Laptop capture auto laptopWithDlss(const VulkanCore& core) -> bool { - static const bool laptop = - core.dlssExtensionsEnabled() && - std::string_view(core.getPhysicalDevice().getProperties().deviceName.data()).contains("Laptop"); + static const bool laptop = core.dlssExtensionsEnabled() && + std::string_view(core.getPhysicalDevice().getProperties().deviceName.data()).contains("Laptop"); return laptop; } diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp index 75d082925..0e460c190 100644 --- a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp @@ -14,7 +14,7 @@ #include #include -struct NVSDK_NGX_Parameter; +struct NVSDK_NGX_Parameter; struct NVSDK_NGX_Handle; namespace renderer { diff --git a/engine/src/toast/world/workspace_voxel.cpp b/engine/src/toast/world/workspace_voxel.cpp index 63b2e240e..6a6c95358 100644 --- a/engine/src/toast/world/workspace_voxel.cpp +++ b/engine/src/toast/world/workspace_voxel.cpp @@ -1568,7 +1568,7 @@ auto Workspace::pickSceneHit() -> std::optional { float collider_t = std::numeric_limits::max(); // Colliders are tested against the shape the debug draw shows, from outside only so a surrounding trigger never eats clicks - const auto pickCollider = [&](physics::Collider& collider, const Box& node) { + const auto pick_collider = [&](physics::Collider& collider, const Box& node) { if (!collider.draw_debug) { return; } @@ -1602,7 +1602,7 @@ auto Workspace::pickSceneHit() -> std::optional { return; } if (auto* collider = reflect_cast(&*node)) { - pickCollider(*collider, node); + pick_collider(*collider, node); } else if (auto* voxels = reflect_cast(&*node)) { voxels->syncTransform(); const auto add = [&](const voxel::Volume* volume, const glm::mat4& model) { diff --git a/tests/voxel/01-volume_sharing.cpp b/tests/voxel/01-volume_sharing.cpp index a59c9f342..aed508630 100644 --- a/tests/voxel/01-volume_sharing.cpp +++ b/tests/voxel/01-volume_sharing.cpp @@ -5,7 +5,7 @@ #include #include -TOAST_TEST_NAMED("voxel", "voxel/01-reshare_touches_only_changed_bricks", test_voxel_01_reshare_touches_only_changed_bricks) { +TOAST_TEST_NAMED("voxel", "voxel/01-volume_sharing", test_voxel_01_volume_sharing) { voxel::BrickPool pool(16); voxel::Volume source(pool, glm::uvec3 {3, 1, 1}); source.setVoxel({1, 1, 1}, 3); diff --git a/tests/voxel/02-solid_tracking.cpp b/tests/voxel/02-solid_tracking.cpp index 633aa1dac..1bc2626f1 100644 --- a/tests/voxel/02-solid_tracking.cpp +++ b/tests/voxel/02-solid_tracking.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -47,7 +46,7 @@ void checkSameConnectivity(const voxel::Connectivity& a, const voxel::Connectivi } -TOAST_TEST_NAMED("voxel", "voxel/02-solid_counts_follow_every_write", test_voxel_02_solid_counts_follow_every_write) { +TOAST_TEST_NAMED("voxel", "voxel/02-solid_tracking", test_voxel_02_solid_tracking) { voxel::BrickPool pool(64); voxel::Volume volume(pool, glm::uvec3 {4, 2, 2}); checkTracking(volume); @@ -125,30 +124,3 @@ TOAST_TEST_NAMED("voxel", "voxel/02-solid_counts_follow_every_write", test_voxel checkSameConnectivity(voxel::analyseConnectivity(volume, &cache), voxel::analyseConnectivity(volume)); checkSameConnectivity(voxel::analyseConnectivity(volume, &cache), voxel::analyseConnectivity(volume)); } - -TOAST_TEST_NAMED("voxel", "voxel/03-mask_moments_match_a_voxel_walk", test_voxel_03_mask_moments_match_a_voxel_walk) { - uint64_t state = 0x9E3779B97F4A7C15ull; - const auto next = [&state] { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - return state; - }; - for (int round = 0; round < 64; ++round) { - voxel::BrickOccupancy mask {}; - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - // mixes sparse, dense and empty slices - mask[z] = round % 3 == 0 ? next() & next() : (round % 3 == 1 ? next() | next() : (z % 2 == 0 ? next() : 0ull)); - } - voxel::MassMoments walked; - voxel::forEachSetVoxel(mask, [&](uint32_t, uint32_t x, uint32_t y, uint32_t z) { - walked.add(static_cast(x), static_cast(y), static_cast(z), 1); - }); - assert(voxel::maskMoments(mask) == walked); - } - voxel::MassMoments full; - voxel::forEachSetVoxel(voxel::k_full_brick, [&](uint32_t, uint32_t x, uint32_t y, uint32_t z) { - full.add(static_cast(x), static_cast(y), static_cast(z), 1); - }); - assert(voxel::maskMoments(voxel::k_full_brick) == full); -} diff --git a/tests/voxel/03-mask_moments.cpp b/tests/voxel/03-mask_moments.cpp new file mode 100644 index 000000000..f31bb2a88 --- /dev/null +++ b/tests/voxel/03-mask_moments.cpp @@ -0,0 +1,31 @@ +#include "test_registry.hpp" + +#include +#include + +TOAST_TEST_NAMED("voxel", "voxel/03-mask_moments", test_voxel_03_mask_moments) { + uint64_t state = 0x9E3779B97F4A7C15ull; + const auto next = [&state] { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + return state; + }; + for (int round = 0; round < 64; ++round) { + voxel::BrickOccupancy mask {}; + for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { + // mixes sparse, dense and empty slices + mask[z] = round % 3 == 0 ? next() & next() : (round % 3 == 1 ? next() | next() : (z % 2 == 0 ? next() : 0ull)); + } + voxel::MassMoments walked; + voxel::forEachSetVoxel(mask, [&](uint32_t, uint32_t x, uint32_t y, uint32_t z) { + walked.add(static_cast(x), static_cast(y), static_cast(z), 1); + }); + assert(voxel::maskMoments(mask) == walked); + } + voxel::MassMoments full; + voxel::forEachSetVoxel(voxel::k_full_brick, [&](uint32_t, uint32_t x, uint32_t y, uint32_t z) { + full.add(static_cast(x), static_cast(y), static_cast(z), 1); + }); + assert(voxel::maskMoments(voxel::k_full_brick) == full); +} From 078bc9aa17608d115d6bbb7b590fdf558cdf123d Mon Sep 17 00:00:00 2001 From: Xein Date: Thu, 26 Nov 2026 23:43:02 +0100 Subject: [PATCH 8/8] clang tidy? --- engine/src/toast/renderer/upscale/dlss_upscaler.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp index 0e460c190..d6828c1a0 100644 --- a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp @@ -14,8 +14,8 @@ #include #include -struct NVSDK_NGX_Parameter; -struct NVSDK_NGX_Handle; +struct NVSDK_NGX_Parameter; // NOLINT +struct NVSDK_NGX_Handle; // NOLINT namespace renderer { class VulkanCore;