From 4082c85082c59d21774b5a003a084b55574727aa 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 14:07:06 +0100 Subject: [PATCH 01/15] performance fixes nd player crashes --- editor/Program.cs | 2 + editor/Resources/files/lib/CMakeLists.txt | 3 + editor/Workspace/MainWindowView.axaml | 11 +- editor/Workspace/MainWindowViewModel.cs | 45 +++- engine/CMakeLists.txt | 2 +- engine/src/toast/assets/asset_manager.cpp | 18 ++ engine/src/toast/assets/asset_manager.hpp | 2 +- engine/src/toast/assets/core_types.hpp | 6 + engine/src/toast/assets/types.cpp | 18 +- engine/src/toast/crash_handler.cpp | 86 +++++++- engine/src/toast/engine.cpp | 2 + engine/src/toast/physics/fracture.hpp | 4 +- .../src/toast/physics/fragment_extraction.cpp | 45 ++-- .../src/toast/physics/fragment_extraction.hpp | 8 + engine/src/toast/physics/simulator.cpp | 191 +++++++++-------- engine/src/toast/physics/simulator.hpp | 11 +- engine/src/toast/physics/voxel_query.hpp | 4 +- engine/src/toast/physics/voxel_shape_data.hpp | 3 + engine/src/toast/physics/voxel_smash.hpp | 8 +- .../src/toast/renderer/core/vulkan_core.cpp | 6 + .../src/toast/renderer/debug/voxel_debug.cpp | 4 +- .../passes/lighting/gi_clipmap_pass.cpp | 2 +- .../passes/lighting/reflection_probe_pass.cpp | 5 + .../passes/lighting/traced_specular_pass.cpp | 2 + .../toast/renderer/shaders/shader_cache.cpp | 5 +- .../renderer/shaders/shader_compiler.cpp | 19 +- engine/src/toast/renderer/vulkan_renderer.hpp | 3 + .../toast/renderer/vulkan_renderer_record.cpp | 26 ++- .../toast/renderer/vulkan_renderer_thread.cpp | 5 +- .../toast/renderer/vulkan_renderer_voxel.cpp | 72 ++++--- engine/src/toast/voxel/brick.hpp | 33 ++- engine/src/toast/voxel/brick_pool.cpp | 39 ++-- engine/src/toast/voxel/brick_pool.hpp | 28 ++- engine/src/toast/voxel/connectivity.cpp | 121 ++++++----- engine/src/toast/voxel/connectivity.hpp | 35 +++- engine/src/toast/voxel/mass_accumulator.hpp | 51 +++++ engine/src/toast/voxel/surface.cpp | 48 +++-- engine/src/toast/voxel/surface.hpp | 4 +- engine/src/toast/voxel/voxel_edit.cpp | 69 +++---- engine/src/toast/voxel/voxel_volume.cpp | 194 ++++++++++-------- engine/src/toast/voxel/voxel_volume.hpp | 103 +++++++++- engine/src/toast/world/world.cpp | 13 ++ tests/voxel/01-volume_sharing.cpp | 41 ++++ tests/voxel/02-solid_tracking.cpp | 154 ++++++++++++++ tools/crash_reporter/CrashReport.cs | 15 +- tools/crash_reporter/CrashTarget.cs | 26 +++ tools/crash_reporter/Native.cs | 5 + tools/crash_reporter/Program.cs | 1 + tools/player/CMakeLists.txt | 7 +- tools/player/player.csproj | 3 +- tools/player/program.cs | 13 +- 51 files changed, 1156 insertions(+), 465 deletions(-) create mode 100644 tests/voxel/01-volume_sharing.cpp create mode 100644 tests/voxel/02-solid_tracking.cpp diff --git a/editor/Program.cs b/editor/Program.cs index f30c30d0b..bf51495b9 100644 --- a/editor/Program.cs +++ b/editor/Program.cs @@ -26,6 +26,8 @@ public static int Main(string[] args) { } Task.Run(ShellIntegration.Apply); + // Read by the mimalloc inside slang-compiler.dll when the engine loads, so it hands freed compile memory back at once + if (Environment.GetEnvironmentVariable("MIMALLOC_PURGE_DELAY") is null) Environment.SetEnvironmentVariable("MIMALLOC_PURGE_DELAY", "0"); return BuildAvaloniaApp() .StartWithClassicDesktopLifetime(args); diff --git a/editor/Resources/files/lib/CMakeLists.txt b/editor/Resources/files/lib/CMakeLists.txt index 26f633a39..d44a9229a 100644 --- a/editor/Resources/files/lib/CMakeLists.txt +++ b/editor/Resources/files/lib/CMakeLists.txt @@ -73,6 +73,9 @@ target_compile_options(my_game PRIVATE if (MSVC) target_compile_options(my_game PRIVATE /MP) + # Release keeps a PDB so the crash reporter can name frames in the game + target_compile_options(my_game PRIVATE $<$:/Zi>) + target_link_options(my_game PRIVATE $<$:/DEBUG /OPT:REF /OPT:ICF>) endif () find_program(CLANG_FORMAT NAMES clang-format) diff --git a/editor/Workspace/MainWindowView.axaml b/editor/Workspace/MainWindowView.axaml index 3d2deb9ca..04cb45fe3 100644 --- a/editor/Workspace/MainWindowView.axaml +++ b/editor/Workspace/MainWindowView.axaml @@ -38,6 +38,8 @@ + @@ -280,9 +282,14 @@ - + Command="{Binding CompileGameDevelopmentCommand}" + ToolTip.Tip="Optimized build with the dev tools, Tracy and full symbols" /> + SaveBeforeBuild(Avalonia.Controls.Window owner) { return true; } + /// Engine and game in RelWithDebInfo: optimized, with the dev tools, Tracy and full symbols [RelayCommand(CanExecute = nameof(CanCompileGameRelease))] - private async Task CompileGameRelease() { + private Task CompileGameDevelopment() => CompileGame("RelWithDebInfo"); + + /// Engine and game in Release: full optimization, no dev tools or Tracy + [RelayCommand(CanExecute = nameof(CanCompileGameRelease))] + private Task CompileGameRelease() => CompileGame("Release"); + + private async Task CompileGame(string gameConfig) { if (App.MainWindow is not { } owner) return; if (!ProjectContext.IsInitialized) return; + + // The game links against the engine of the same config, which sits next to the editor's own out// + var toastPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", gameConfig, "toast_engine")); + if (!File.Exists(Path.Combine(toastPath, "bin", OperatingSystem.IsWindows() ? "toast_engine.dll" : "libtoast_engine.so"))) { + Log.Error($"Cannot build the game in {gameConfig}: the {gameConfig} engine was not built ({toastPath})"); + return; + } if (!await SaveBeforeBuild(owner)) return; var playerPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "tools", "player")); - var toastPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "toast_engine")); var packerBin = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "packer", $"packer{(OperatingSystem.IsWindows() ? ".exe" : "")}")); var outputDir = Path.GetFullPath(Path.Combine(ProjectContext.ProjectPath, "build")); var stageRoot = Path.GetFullPath(Path.Combine(ProjectContext.ProjectPath, ".toast", "pack_stage")); var cmakeGenerator = OperatingSystem.IsWindows() ? "-G \"Visual Studio 18 2026\"" : "-G \"Ninja\""; - -#if DEBUG - const string gameConfig = "Debug"; -#elif RELWITHDEBINFO - const string gameConfig = "RelWithDebInfo"; -#else - const string gameConfig = "Release"; -#endif var cmakeCache = $".toast/cmake_release_cache_{gameConfig}"; Directory.CreateDirectory(outputDir); @@ -1235,6 +1240,25 @@ async Task CopyProjectToast(Action log) { await Task.Run(() => File.Copy(toastFile, dest, true)); } + // The engine's crash handler looks for crash_reporter/ next to toast_engine.dll; runtimes/ holds its native libraries + async Task CopyCrashReporter(Action log) { + var src = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "crash_reporter")); + if (!Directory.Exists(src)) { + log($"warning: crash reporter not found: {src}"); + return; + } + + var dest = Path.Combine(outputDir, "crash_reporter"); + log(" copy crash_reporter/"); + await Task.Run(() => { + foreach (var file in Directory.EnumerateFiles(src, "*", SearchOption.AllDirectories)) { + var target = Path.Combine(dest, Path.GetRelativePath(src, file)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(file, target, true); + } + }); + } + // Baked lighting (irradiance volume SH, reflection probe captures) lives in cache://, which belongs to no content // database and so never reaches a pak; the player resolves cache:// to /cache async Task CopyBakedLighting(Action log) { @@ -1325,6 +1349,7 @@ await Task.Run(() => { ), // Copy Engine libs LoaderTask.Do("copy libraries", CopyDlls), + LoaderTask.Do("copy crash reporter", CopyCrashReporter), LoaderTask.Do("copy project.toast", CopyProjectToast), LoaderTask.Do("copy baked lighting", CopyBakedLighting) }; diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 23e4aed7e..587af4228 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -175,7 +175,7 @@ target_include_directories(toast_engine PUBLIC "${_toast_build_config_dir}") # Replaces global operator new and delete so Tracy lists every heap allocation, only active where Tracy is option(TOAST_TRACK_HEAP "Report C++ heap allocations to Tracy" ON) # 0 records no callstack, around 8 to 16 shows who allocates but slows allocation heavy code down a lot -set(TOAST_HEAP_CALLSTACK_DEPTH 0 CACHE STRING "Callstack frames Tracy captures per heap allocation") +set(TOAST_HEAP_CALLSTACK_DEPTH 8 CACHE STRING "Callstack frames Tracy captures per heap allocation") target_compile_definitions(toast_engine PRIVATE $<$,$>,$>:TOAST_TRACK_HEAP> TOAST_HEAP_CALLSTACK_DEPTH=${TOAST_HEAP_CALLSTACK_DEPTH} diff --git a/engine/src/toast/assets/asset_manager.cpp b/engine/src/toast/assets/asset_manager.cpp index f14f3cc10..649899580 100644 --- a/engine/src/toast/assets/asset_manager.cpp +++ b/engine/src/toast/assets/asset_manager.cpp @@ -56,6 +56,8 @@ void AssetManager::mountPack(std::string_view scheme, const std::filesystem::pat AssetManager::AssetManager() { instance = this; + // A manager destroyed earlier (another project, another test) left handles not counting + Asset::setFreeingAll(false); AssetRegistry::init(); reloadManifest(); @@ -507,6 +509,22 @@ auto AssetManager::openDatabase(const std::filesystem::path& db_file) -> bool { return ok; } +AssetManager::~AssetManager() { + // Assets hold handles to other assets, so unreferenced ones go first, round after round, before the map frees the rest + // in hash order; freeing a referenced asset first would let its holder release freed memory + for (size_t remaining = cache.size() + retired_assets.size();;) { + std::erase_if(cache, [](const auto& item) { return item.second->refCount() == 0; }); + std::erase_if(retired_assets, [](const auto& asset) { return asset->refCount() == 0; }); + const size_t left = cache.size() + retired_assets.size(); + if (left == remaining) { + break; + } + remaining = left; + } + // What is left is still held, by each other or by nodes a world never freed, so its handles stop counting + Asset::setFreeingAll(true); +} + void AssetManager::clearUnusedAssets() { ZoneScoped; diff --git a/engine/src/toast/assets/asset_manager.hpp b/engine/src/toast/assets/asset_manager.hpp index 791b8af0f..49953a451 100644 --- a/engine/src/toast/assets/asset_manager.hpp +++ b/engine/src/toast/assets/asset_manager.hpp @@ -67,7 +67,7 @@ struct Paths { class AssetManager { public: AssetManager(); - ~AssetManager() = default; + ~AssetManager(); static auto get() noexcept -> AssetManager&; diff --git a/engine/src/toast/assets/core_types.hpp b/engine/src/toast/assets/core_types.hpp index e96345c31..3f23f4f34 100644 --- a/engine/src/toast/assets/core_types.hpp +++ b/engine/src/toast/assets/core_types.hpp @@ -56,6 +56,9 @@ class TOAST_API Asset { [[nodiscard]] virtual auto type() const -> std::string_view = 0; + /// Set while the AssetManager frees assets that still have handles, so those handles leave the freed assets alone + static void setFreeingAll(bool freeing) noexcept; + protected: void addRef() noexcept; void release() noexcept; @@ -63,6 +66,9 @@ class TOAST_API Asset { friend class HandleBase; private: + [[nodiscard]] + static auto freeingAll() noexcept -> bool; + std::atomic m_ref_count {0}; ///< starts at 0; HandleBase increments on copy and decrements on destroy }; diff --git a/engine/src/toast/assets/types.cpp b/engine/src/toast/assets/types.cpp index 76fb54506..54bae40c9 100644 --- a/engine/src/toast/assets/types.cpp +++ b/engine/src/toast/assets/types.cpp @@ -5,6 +5,18 @@ void Asset::addRef() noexcept { m_ref_count.fetch_add(1, std::memory_order_relaxed); } +namespace { +std::atomic_bool g_freeing_all {false}; +} + +void Asset::setFreeingAll(bool freeing) noexcept { + g_freeing_all.store(freeing, std::memory_order_release); +} + +auto Asset::freeingAll() noexcept -> bool { + return g_freeing_all.load(std::memory_order_acquire); +} + void Asset::release() noexcept { m_ref_count.fetch_sub(1, std::memory_order_relaxed); } @@ -26,7 +38,7 @@ HandleBase::HandleBase(Asset* asset, toast::UID uid, std::string_view uri) : m_a } HandleBase::~HandleBase() { - if (m_asset) { + if (m_asset && !Asset::freeingAll()) { m_asset->release(); } } @@ -40,7 +52,7 @@ HandleBase::HandleBase(const HandleBase& other) : m_asset(other.m_asset), m_uid( auto HandleBase::operator=(const HandleBase& other) -> HandleBase& { if (this != &other) { - if (m_asset) { + if (m_asset && !Asset::freeingAll()) { m_asset->release(); } m_asset = other.m_asset; @@ -61,7 +73,7 @@ HandleBase::HandleBase(HandleBase&& other) noexcept : m_asset(other.m_asset), m_ auto HandleBase::operator=(HandleBase&& other) noexcept -> HandleBase& { if (this != &other) { - if (m_asset) { + if (m_asset && !Asset::freeingAll()) { m_asset->release(); } m_asset = other.m_asset; diff --git a/engine/src/toast/crash_handler.cpp b/engine/src/toast/crash_handler.cpp index b9ba11022..1f99857ab 100644 --- a/engine/src/toast/crash_handler.cpp +++ b/engine/src/toast/crash_handler.cpp @@ -45,6 +45,21 @@ SharedState g_shared; Kind g_kind = Kind::exception; DWORD g_crashed_thread = 0; +/// Read by the reporter started ahead of time, layout mirrored by CrashArgs.ReadHandoff in tools/crash_reporter +struct ReporterHandoff { + DWORD tid = 0; + int32_t kind = 0; + uint64_t pointers = 0; + uint64_t message = 0; + std::array dump_directory {}; +}; + +static_assert(offsetof(ReporterHandoff, dump_directory) == 24); + +ReporterHandoff g_handoff; +/// Started suspended at install, since a crash can hold the heap lock CreateProcess needs +PROCESS_INFORMATION g_standby {}; + std::array g_reporter_path {}; std::array g_dump_directory {}; std::array g_command_line {}; @@ -101,11 +116,22 @@ auto resolveReporter() noexcept -> bool { } std::array candidate {}; - for (const wchar_t* relative : {L"\\..\\..\\crash_reporter\\crash_reporter.exe", L"\\crash_reporter\\crash_reporter.exe"}) { + // Dev layout, the player and exports, then older exports that put it flat next to the engine + for (const wchar_t* relative : + {L"\\..\\..\\crash_reporter\\crash_reporter.exe", L"\\crash_reporter\\crash_reporter.exe", L"\\crash_reporter.exe"}) { if (swprintf_s(candidate.data(), candidate.size(), L"%ls%ls", directory.data(), relative) < 0) { continue; } - if (GetFullPathNameW(candidate.data(), MAX_PATH, g_reporter_path.data(), nullptr) > 0 && fileExists(g_reporter_path.data())) { + if (GetFullPathNameW(candidate.data(), MAX_PATH, g_reporter_path.data(), nullptr) == 0 || + !fileExists(g_reporter_path.data())) { + continue; + } + // Old exports copied only the exe and dll, and without its runtimeconfig .NET shows an install dialog instead + std::array config {}; + const size_t stem = wcslen(g_reporter_path.data()) - 4; + if (swprintf_s(config.data(), config.size(), L"%.*ls.runtimeconfig.json", static_cast(stem), g_reporter_path.data()) > + 0 && + fileExists(config.data())) { return true; } } @@ -142,6 +168,50 @@ auto WINAPI launchReporter(LPVOID) -> DWORD { return 0; } +/// The job kills the waiting reporter with this process when nothing crashed +void startStandbyReporter() noexcept { + g_handoff.pointers = reinterpret_cast(&g_shared.pointers); + g_handoff.message = reinterpret_cast(g_shared.message.data()); + swprintf_s( + g_command_line.data(), + g_command_line.size(), + L"\"%ls\" --pid %lu --handoff 0x%llx", + g_reporter_path.data(), + GetCurrentProcessId(), + static_cast(reinterpret_cast(&g_handoff)) + ); + + HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits {}; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (job == nullptr || !SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) { + if (job != nullptr) { + CloseHandle(job); + } + return; + } + + STARTUPINFOW startup {}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process {}; + if (!CreateProcessW( + nullptr, g_command_line.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &startup, &process + )) { + CloseHandle(job); + return; + } + if (!AssignProcessToJobObject(job, process.hProcess)) { + // Without the job it would outlive this process, so report the old way instead + TerminateProcess(process.hProcess, 0); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + CloseHandle(job); + return; + } + // The job handle stays open for the life of the process on purpose + g_standby = process; +} + auto WINAPI flushLogsThread(LPVOID) -> DWORD { logging::Logger::crashFlush(g_flush_reason.data(), g_flush_trace); return 0; @@ -209,8 +279,15 @@ void report(Kind kind, const EXCEPTION_POINTERS* pointers, const char* message) flushLogs(pointers, message); - // Fresh thread since after a stack overflow this one has too little stack to start a process - if (HANDLE thread = CreateThread(nullptr, 256 * 1024, launchReporter, nullptr, 0, nullptr)) { + // Resuming allocates nothing, so this works while the crash holds the heap lock + if (g_standby.hProcess != nullptr) { + g_handoff.tid = g_crashed_thread; + g_handoff.kind = static_cast(g_kind); + wcsncpy_s(g_handoff.dump_directory.data(), g_handoff.dump_directory.size(), g_dump_directory.data(), _TRUNCATE); + ResumeThread(g_standby.hThread); + WaitForSingleObject(g_standby.hProcess, INFINITE); + } else if (HANDLE thread = CreateThread(nullptr, 256 * 1024, launchReporter, nullptr, 0, nullptr)) { + // Fresh thread since after a stack overflow this one has too little stack to start a process WaitForSingleObject(thread, INFINITE); CloseHandle(thread); } @@ -410,6 +487,7 @@ void install() noexcept { } if (g_reporter_ready) { + startStandbyReporter(); // First in the chain so managed faults pass through untouched AddVectoredExceptionHandler(1, onVectoredException); } else { diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 9d3ffb7d5..3238d9fcc 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -409,6 +409,8 @@ Engine::~Engine() noexcept { m->input_system.reset(); m->physics_simulator.reset(); m->audio_system.reset(); + // lua_close runs userdata finalizers, and an Asset proxy releases its asset, which must still exist + m->lua_state.reset(); m->renderer.reset(); m->asset_manager.reset(); m->vulkan_core.reset(); diff --git a/engine/src/toast/physics/fracture.hpp b/engine/src/toast/physics/fracture.hpp index 60d0d10c7..b0a368b79 100644 --- a/engine/src/toast/physics/fracture.hpp +++ b/engine/src/toast/physics/fracture.hpp @@ -147,8 +147,8 @@ void forEachSolidVoxel(const voxel::Volume& volume, const glm::vec3& low, const // yeah this is O(n^6) 🥀 const auto brick_dim = static_cast(voxel::k_brick_dim); - const glm::ivec3 first_brick = first / brick_dim; - const glm::ivec3 last_brick = last / brick_dim; + const glm::ivec3 first_brick = voxel::brickOf(first); + const glm::ivec3 last_brick = voxel::brickOf(last); for (int32_t bz = first_brick.z; bz <= last_brick.z; ++bz) { for (int32_t by = first_brick.y; by <= last_brick.y; ++by) { for (int32_t bx = first_brick.x; bx <= last_brick.x; ++bx) { diff --git a/engine/src/toast/physics/fragment_extraction.cpp b/engine/src/toast/physics/fragment_extraction.cpp index 7cd273031..8d5f8cb91 100644 --- a/engine/src/toast/physics/fragment_extraction.cpp +++ b/engine/src/toast/physics/fragment_extraction.cpp @@ -4,48 +4,25 @@ namespace physics { namespace { -auto unitBrickMoments() -> const voxel::MassMoments& { - static const voxel::MassMoments unit = [] { - voxel::MassMoments moments; - for (int32_t z = 0; std::cmp_less(z, voxel::k_brick_dim); ++z) { - for (int32_t y = 0; std::cmp_less(y, voxel::k_brick_dim); ++y) { - for (int32_t x = 0; std::cmp_less(x, voxel::k_brick_dim); ++x) { - moments.add(x, y, z, 1); - } - } - } - return moments; - }(); - return unit; -} - -template -void forEachSetVoxel(const voxel::BrickOccupancy& mask, Callback&& callback) { - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t word = mask[z]; - while (word != 0ull) { - const auto bit = static_cast(std::countr_zero(word)); - word &= word - 1ull; - callback((z * voxel::k_brick_dim * voxel::k_brick_dim) + bit, bit & 7u, bit >> 3u, z); - } - } -} - auto materialOf(const voxel::Volume& source, voxel::BrickEntry entry, uint32_t index) -> uint8_t { return entry.tag() == voxel::BrickTag::uniform ? static_cast(entry.payload()) : source.pool()->material(entry.payload())[index]; } +} + auto maskedMoments( const voxel::Volume& source, voxel::BrickEntry entry, const voxel::BrickOccupancy& mask, bool whole, glm::ivec3 origin, const DensityTable& density ) -> voxel::MassMoments { - if (whole && entry.tag() == voxel::BrickTag::uniform) { - return unitBrickMoments().scaled(density[entry.payload()]).shifted(origin.x, origin.y, origin.z); + if (entry.tag() == voxel::BrickTag::uniform) { + static constexpr voxel::MassMoments k_full = voxel::maskMoments(voxel::k_full_brick); + const voxel::MassMoments unit = whole ? k_full : voxel::maskMoments(mask); + return unit.scaled(density[entry.payload()]).shifted(origin.x, origin.y, origin.z); } voxel::MassMoments moments; - forEachSetVoxel(mask, [&](uint32_t index, uint32_t x, uint32_t y, uint32_t z) { + voxel::forEachSetVoxel(mask, [&](uint32_t index, uint32_t x, uint32_t y, uint32_t z) { moments.add( origin.x + static_cast(x), origin.y + static_cast(y), @@ -56,6 +33,8 @@ auto maskedMoments( return moments; } +namespace { + struct BrickMask { glm::ivec3 brick {0}; voxel::BrickOccupancy voxels {}; @@ -154,7 +133,9 @@ auto extractFragmentVolume(voxel::Volume& source, const DetachedComponent& compo } bytes.fill(voxel::k_empty_palette_index); - forEachSetVoxel(mask, [&](uint32_t index, uint32_t, uint32_t, uint32_t) { bytes[index] = materialOf(source, entry, index); }); + voxel::forEachSetVoxel(mask, [&](uint32_t index, uint32_t, uint32_t, uint32_t) { + bytes[index] = materialOf(source, entry, index); + }); fragment.setBrickMaterial(local, bytes); if (whole) { @@ -191,7 +172,7 @@ void restoreFragment(voxel::Volume& source, voxel::Volume& fragment, glm::ivec3 } const voxel::BrickOccupancy* occupancy = fragment.occupancyPointer(local); - forEachSetVoxel(*occupancy, [&](uint32_t index, uint32_t vx, uint32_t vy, uint32_t vz) { + voxel::forEachSetVoxel(*occupancy, [&](uint32_t index, uint32_t vx, uint32_t vy, uint32_t vz) { const glm::ivec3 voxel_pos = (brick * static_cast(voxel::k_brick_dim)) + glm::ivec3(static_cast(vx), static_cast(vy), static_cast(vz)); source.setVoxel(voxel_pos, materialOf(fragment, entry, index)); diff --git a/engine/src/toast/physics/fragment_extraction.hpp b/engine/src/toast/physics/fragment_extraction.hpp index f7b7e6d9d..caf066d65 100644 --- a/engine/src/toast/physics/fragment_extraction.hpp +++ b/engine/src/toast/physics/fragment_extraction.hpp @@ -34,6 +34,14 @@ struct ExtractedFragment { uint32_t voxels = 0; }; +/// Moments of the voxels of one brick under mask at origin, whole means mask is the full brick so a uniform one takes the closed +/// form +[[nodiscard]] +auto maskedMoments( + const voxel::Volume& source, voxel::BrickEntry entry, const voxel::BrickOccupancy& mask, bool whole, glm::ivec3 origin, + const DensityTable& density +) -> voxel::MassMoments; + /// @returns nullopt with source untouched when the pool is short of bricks [[nodiscard]] auto extractFragmentVolume(voxel::Volume& source, const DetachedComponent& component, const DensityTable& density) diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 290386c48..9b7ca2fd8 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include namespace physics { @@ -118,36 +119,14 @@ auto placeholderMaterialLibrary() -> const voxel::MaterialLibrary& { auto computeOccupiedBounds(const voxel::Volume& volume) -> AABB { ZoneScopedN("physics::ComputeOccupiedBounds"); - const glm::ivec3 brick_dims = glm::ivec3(volume.brickDims()); - const auto brick_dim = static_cast(voxel::k_brick_dim); - glm::ivec3 min {std::numeric_limits::max()}; - glm::ivec3 max {std::numeric_limits::min()}; - - for (int32_t z = 0; z < brick_dims.z; ++z) { - for (int32_t y = 0; y < brick_dims.y; ++y) { - for (int32_t x = 0; x < brick_dims.x; ++x) { - const glm::ivec3 brick {x, y, z}; - const voxel::BrickOccupancy* occupancy = volume.occupancyPointer(brick); - if (occupancy == nullptr || voxel::isEmpty(*occupancy)) { - continue; - } - - const voxel::BrickExtent extent = voxel::occupiedExtent(*occupancy); - const glm::ivec3 brick_base = brick * brick_dim; - min = glm::min(min, brick_base + glm::ivec3(extent.min.x, extent.min.y, extent.min.z)); - max = glm::max(max, brick_base + glm::ivec3(extent.max.x, extent.max.y, extent.max.z)); - } - } - } - - if (glm::any(glm::greaterThan(min, max))) { + const std::optional bounds = voxel::occupiedBounds(volume); + if (not bounds.has_value()) { // nothing left return {}; } - return { - .min = glm::vec3(min) * voxel::k_voxel_size, - .max = glm::vec3(max + glm::ivec3(1)) * voxel::k_voxel_size, + .min = glm::vec3(bounds->min) * voxel::k_voxel_size, + .max = glm::vec3(bounds->max + glm::ivec3(1)) * voxel::k_voxel_size, }; } @@ -157,31 +136,11 @@ auto accumulateMassMoments(const voxel::Volume& volume, const voxel::Palette& pa ZoneScopedN("physics::AccumulateMassMoments"); voxel::MassMoments moments; - const glm::ivec3 brick_dims = glm::ivec3(volume.brickDims()); + const DensityTable density = voxel::densityTable(palette, materials); const auto brick_dim = static_cast(voxel::k_brick_dim); - for (int32_t bz = 0; bz < brick_dims.z; ++bz) { - for (int32_t by = 0; by < brick_dims.y; ++by) { - for (int32_t bx = 0; bx < brick_dims.x; ++bx) { - const glm::ivec3 brick {bx, by, bz}; - if (volume.entryAt(brick).tag() == voxel::BrickTag::empty) { - continue; - } - for (int32_t lz = 0; lz < brick_dim; ++lz) { - for (int32_t ly = 0; ly < brick_dim; ++ly) { - for (int32_t lx = 0; lx < brick_dim; ++lx) { - const glm::ivec3 v = brick * brick_dim + glm::ivec3(lx, ly, lz); - const uint8_t palette_index = volume.materialAt(v); - if (palette_index == voxel::k_empty_palette_index) { - continue; - } - const uint32_t material_index = voxel::resolveMaterialIndex(palette, materials, palette_index); - moments.add(v.x, v.y, v.z, materials.materials[material_index].density); - } - } - } - } - } - } + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t) { + moments += maskedMoments(volume, volume.entryAt(brick), *volume.occupancyPointer(brick), true, brick * brick_dim, density); + }); return moments; } } @@ -331,14 +290,21 @@ void Simulator::publishQuerySnapshot() { } } if (source.data) { - auto data = std::make_shared(); + std::shared_ptr& recycled = snapshot->voxels[index].data; + std::shared_ptr data = recycled.use_count() == 1 + ? std::const_pointer_cast(std::move(recycled)) + : std::make_shared(); data->surface = source.data->surface; data->palette = source.data->palette; data->materials = source.data->materials; - if (volume) { + if (volume == nullptr) { + data->owned_volume.reset(); + } else if (data->owned_volume) { + data->owned_volume->reshareFrom(*volume); + } else { data->owned_volume = std::make_unique(voxel::Volume::instanceOf(*volume)); - data->volume = data->owned_volume.get(); } + data->volume = data->owned_volume.get(); key.data = std::move(data); } snapshot->voxels[index] = std::move(key); @@ -884,7 +850,7 @@ void Simulator::publishProfile(std::span islands) { void Simulator::clearFragmentFromSource( ShapeID shape_id, VoxelShapeData& data, voxel::Volume& source, const DetachedComponent& component, - const RemovedVoxels* already_removed + const RemovedVoxels* already_removed, std::vector* deferred_dirty ) { ZoneScoped; @@ -896,13 +862,27 @@ void Simulator::clearFragmentFromSource( : discardComponent(source, component, voxel::densityTable(data.palette, data.materials)); data.moments -= removed.moments; data.solid_voxel_count -= std::min(data.solid_voxel_count, removed.voxels); + } - std::vector dirty_bricks; - dirty_bricks.reserve(component.pieces.size()); - for (const auto& p : component.pieces) { - dirty_bricks.emplace_back(p.brick); - } + std::vector dirty_bricks; + std::vector& dirty = deferred_dirty != nullptr ? *deferred_dirty : dirty_bricks; + dirty.reserve(dirty.size() + component.pieces.size()); + for (const auto& p : component.pieces) { + dirty.emplace_back(p.brick); + } + if (deferred_dirty == nullptr) { + finishSourceCarve(shape_id, data, source, dirty_bricks); + } +} +void Simulator::finishSourceCarve( + ShapeID shape_id, VoxelShapeData& data, voxel::Volume& source, std::span dirty_bricks +) { + ZoneScoped; + ZoneValue(static_cast(dirty_bricks.size())); + + { + std::scoped_lock voxel_lock {voxelDataMutex()}; // Not tryCollapseUniform here since clearing a voxel only unfills a brick and never passes isFull data.surface.repairBricks(source, dirty_bricks); } @@ -951,13 +931,9 @@ auto Simulator::debrisIfSmall(ShapeID shape_id) -> bool { DetachedComponent whole; whole.voxel_count = solid; - for (uint32_t index = 0; index < data->volume->brickCount(); ++index) { - const glm::ivec3 brick = data->volume->brickAtIndex(index); - const voxel::BrickOccupancy* occupancy = data->volume->occupancyPointer(brick); - if (occupancy != nullptr && not voxel::isEmpty(*occupancy)) { - whole.pieces.push_back({.brick = brick, .voxels = *occupancy}); - } - } + data->volume->forEachSolidBrick([&](glm::ivec3 brick, uint32_t) { + whole.pieces.push_back({.brick = brick, .voxels = *data->volume->occupancyPointer(brick)}); + }); emitComponentDebris(shape_id, whole, nullptr); shape = tryGetShape(shape_id); @@ -1016,16 +992,7 @@ void Simulator::emitDebris( const glm::vec3 push_direction = push != nullptr ? push->direction : glm::vec3 {0.0f}; const float push_length = glm::length(push_direction); - const glm::ivec3 dims = data->volume != nullptr ? glm::ivec3(data->volume->voxelDims()) : glm::ivec3(0); - const auto solid_at = [&](const glm::ivec3& v) { - if (glm::any(glm::lessThan(v, glm::ivec3(0))) || glm::any(glm::greaterThanEqual(v, dims))) { - return false; - } - const auto brick_dim = static_cast(voxel::k_brick_dim); - const voxel::BrickOccupancy* occupancy = data->volume->occupancyPointer(v / brick_dim); - const glm::uvec3 in_brick = glm::uvec3(v % brick_dim); - return occupancy != nullptr && voxel::isSolid(*occupancy, in_brick.x, in_brick.y, in_brick.z); - }; + const auto solid_at = [&](const glm::ivec3& v) { return data->volume != nullptr && data->volume->isSolidAt(v); }; const auto blocked_ahead = [&](const glm::vec3& from, const glm::vec3& direction, glm::vec3& normal_local) { glm::ivec3 previous = glm::ivec3(glm::floor(from)); for (float t = 0.25f; t <= k_debris_lookahead_voxels; t += 0.25f) { @@ -1178,16 +1145,10 @@ void Simulator::emitComponentDebris(ShapeID shape_id, const DetachedComponent& c } const voxel::BrickOccupancy mask = piece.voxels & *occupancy; const glm::ivec3 base = piece.brick * static_cast(voxel::k_brick_dim); - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t word = mask[z]; - while (word != 0ull) { - const auto bit = static_cast(std::countr_zero(word)); - word &= word - 1ull; - const glm::ivec3 v = - base + glm::ivec3(static_cast(bit & 7u), static_cast(bit >> 3u), static_cast(z)); - voxels.push_back({.voxel = v, .material = data->volume->materialAt(v)}); - } - } + voxel::forEachSetVoxel(mask, [&](uint32_t, uint32_t x, uint32_t y, uint32_t z) { + const glm::ivec3 v = base + glm::ivec3(glm::uvec3(x, y, z)); + voxels.push_back({.voxel = v, .material = data->volume->materialAt(v)}); + }); } if (voxels.empty()) { return; @@ -1658,7 +1619,9 @@ void Simulator::unlockSleep(BodyID id) { m_fragments[it->second].sequence = m_next_fragment_sequence++; } -auto Simulator::spawnFragmentBody(ShapeID source_shape_id, const DetachedComponent& component, const FragmentPush* push) -> bool { +auto Simulator::spawnFragmentBody( + ShapeID source_shape_id, const DetachedComponent& component, const FragmentPush* push, std::vector* deferred_dirty +) -> bool { ZoneScopedN("physics::SpawnFragment"); ZoneValue(static_cast(component.voxel_count)); @@ -1760,7 +1723,7 @@ auto Simulator::spawnFragmentBody(ShapeID source_shape_id, const DetachedCompone shape = tryGetShape(source_shape_id); if (shape != nullptr) { if (VoxelShapeData* source_data = tryGetVoxelData(shape->voxel.data)) { - clearFragmentFromSource(source_shape_id, *source_data, *source_data->volume, component, &removed); + clearFragmentFromSource(source_shape_id, *source_data, *source_data->volume, component, &removed, deferred_dirty); } } if (toast::VoxelNode* node = voxelNodeFor(source_shape_id)) { @@ -5066,8 +5029,8 @@ void Simulator::applyDamageCommand(const DamageCommand& c) { } const auto brick_dim = static_cast(voxel::k_brick_dim); - const glm::ivec3 first_brick = first / brick_dim; - const glm::ivec3 last_brick = last / brick_dim; + const glm::ivec3 first_brick = voxel::brickOf(first); + const glm::ivec3 last_brick = voxel::brickOf(last); struct Doomed { // we 100% need to remove this voxels @@ -5177,7 +5140,7 @@ void Simulator::applyDamageCommand(const DamageCommand& c) { data->connectivity_dirty = true; ++removed; removed_sum += glm::vec3(v); - const glm::ivec3 brick = v / brick_dim; + const glm::ivec3 brick = voxel::brickOf(v); if (dirty_seen.insert(voxelKey(brick)).second) { dirty_bricks.push_back(brick); } @@ -5746,8 +5709,8 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) } const auto brick_dim = static_cast(voxel::k_brick_dim); - const glm::ivec3 first_brick = first / brick_dim; - const glm::ivec3 last_brick = last / brick_dim; + const glm::ivec3 first_brick = voxel::brickOf(first); + const glm::ivec3 last_brick = voxel::brickOf(last); const auto mark = [&](BrickMask& entry, const glm::ivec3& v, const glm::ivec3& brick) { entry.brick = brick; const glm::ivec3 local = v - (brick * brick_dim); @@ -5767,6 +5730,22 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) const glm::ivec3 brick_first = glm::max(first, brick * brick_dim); const glm::ivec3 brick_last = glm::min(last, (brick * brick_dim) + (brick_dim - 1)); + const glm::vec3 to_box = + glm::clamp( + local_point, glm::vec3(brick_first) * voxel::k_voxel_size, glm::vec3(brick_last + 1) * voxel::k_voxel_size + ) - + local_point; + if (glm::dot(to_box, to_box) > scan * scan) { + continue; + } + + const voxel::BrickEntry entry = volume.entryAt(brick); + const bool uniform = entry.tag() == voxel::BrickTag::uniform; + if (uniform && not exploded_materials[entry.payload()].breakable) { + continue; + } + const uint8_t* brick_material = uniform ? nullptr : std::as_const(*volume.pool()).material(entry.payload()).data(); + BrickMask* brick_debris = nullptr; BrickMask* chunk_mask = nullptr; uint64_t chunk_mask_key = 0; @@ -5788,7 +5767,11 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) continue; } - const uint8_t palette_index = volume.materialAt(v); + const uint8_t palette_index = + uniform ? static_cast(entry.payload()) + : brick_material[voxel::localIndex( + static_cast(local.x), static_cast(local.y), static_cast(local.z) + )]; const ExplodedMaterial& exploded = exploded_materials[palette_index]; if (not exploded.breakable) { continue; @@ -6000,13 +5983,15 @@ auto Simulator::breakPieces( std::ranges::sort(picked.pieces, std::greater {}, &DetachedComponent::voxel_count); + std::vector carved_bricks; size_t flown = 0; for (const DetachedComponent& piece : picked.pieces) { const bool may_fly = chunks && flown < spawn_cap && piece.voxel_count >= tunables().min_fragment_voxels; if (may_fly) { const std::optional push = push_for(piece); const size_t before = m_fragments.size(); - if (spawnFragmentBody(shape_id, piece, push.has_value() ? &*push : nullptr) && m_fragments.size() > before) { + if (spawnFragmentBody(shape_id, piece, push.has_value() ? &*push : nullptr, &carved_bricks) && + m_fragments.size() > before) { ++flown; continue; } @@ -6021,12 +6006,17 @@ auto Simulator::breakPieces( shape = tryGetShape(shape_id); data = shape != nullptr ? tryGetVoxelData(shape->voxel.data) : nullptr; if (data != nullptr && data->volume != nullptr) { - clearFragmentFromSource(shape_id, *data, *data->volume, piece); + clearFragmentFromSource(shape_id, *data, *data->volume, piece, nullptr, &carved_bricks); } } shape = tryGetShape(shape_id); data = shape != nullptr ? tryGetVoxelData(shape->voxel.data) : nullptr; + if (data != nullptr && data->volume != nullptr && not carved_bricks.empty()) { + finishSourceCarve(shape_id, *data, *data->volume, carved_bricks); + shape = tryGetShape(shape_id); + data = shape != nullptr ? tryGetVoxelData(shape->voxel.data) : nullptr; + } if (data == nullptr) { return 0; } @@ -6079,14 +6069,19 @@ auto Simulator::runConnectivityAnalysis() -> std::vector { ShapeID id {.slot = static_cast(index), .generation = slot.generation}; uint32_t revision = data->surface_revision; data->connectivity_dirty = false; + if (data->connectivity_cache == nullptr) { + data->connectivity_cache = std::make_unique(); + } + // The voxel lock is held until every job is awaited below so the cache and the volume stay put + voxel::ConnectivityCache* cache = data->connectivity_cache.get(); // clang-format off pending.emplace_back(PendingJob { .shape = id, .revision = revision, - .future = toast::ThreadPool::push([volume] { + .future = toast::ThreadPool::push([volume, cache] { ZoneScopedN("physics::ConnectivityBatch"); // NOLINT - return voxel::analyseConnectivity(*volume); + return voxel::analyseConnectivity(*volume, cache); }) }); // clang-format on diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 33474d9a6..5c156cee8 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -654,11 +654,15 @@ class TOAST_API Simulator { auto correctPositions(std::span manifold_indices) -> size_t; void publishProfile(std::span islands); + /// @param deferred_dirty when set only carves and collects the dirty bricks, finishSourceCarve does the rest once void clearFragmentFromSource( ShapeID shape_id, VoxelShapeData& data, voxel::Volume& source, const DetachedComponent& component, - const RemovedVoxels* already_removed = nullptr + const RemovedVoxels* already_removed = nullptr, std::vector* deferred_dirty = nullptr ); + /// Surface repair, bounds, mass and the small or empty leftovers of a source after one or more carves + void finishSourceCarve(ShapeID shape_id, VoxelShapeData& data, voxel::Volume& source, std::span dirty_bricks); + void emitDebris( ShapeID shape_id, std::span voxels, const DebrisBlast* blast, const FragmentPush* push, uint64_t seed, bool together = false @@ -667,7 +671,10 @@ class TOAST_API Simulator { void emitComponentDebris(ShapeID shape_id, const DetachedComponent& component, const FragmentPush* push); [[nodiscard]] - auto spawnFragmentBody(ShapeID source_shape_id, const DetachedComponent& component, const FragmentPush* push = nullptr) -> bool; + auto spawnFragmentBody( + ShapeID source_shape_id, const DetachedComponent& component, const FragmentPush* push = nullptr, + std::vector* deferred_dirty = nullptr + ) -> bool; auto smashShape(ShapeID shape_id, const SmashVolume& volume, const CapsuleSmash& smash, bool chunks) -> uint32_t; auto explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) -> uint32_t; [[nodiscard]] diff --git a/engine/src/toast/physics/voxel_query.hpp b/engine/src/toast/physics/voxel_query.hpp index f4348e566..ca377eaa4 100644 --- a/engine/src/toast/physics/voxel_query.hpp +++ b/engine/src/toast/physics/voxel_query.hpp @@ -347,7 +347,7 @@ void queryVoxelRay( return; } - const glm::ivec3 brick = cell >> 3; + const glm::ivec3 brick = voxel::brickOf(cell); const glm::ivec3 brick_min = brick * k_brick; const voxel::BrickEntry entry = volume.entryAt(brick); @@ -366,7 +366,7 @@ void queryVoxelRay( palette_index = static_cast(entry.payload()); } else { const voxel::BrickOccupancy* occupancy = volume.occupancyPointer(brick); - const glm::uvec3 local = glm::uvec3(cell - brick_min); + const voxel::BrickCoord local = voxel::localOf(cell); if (occupancy != nullptr && voxel::isSolid(*occupancy, local.x, local.y, local.z)) { palette_index = volume.materialAt(cell); } diff --git a/engine/src/toast/physics/voxel_shape_data.hpp b/engine/src/toast/physics/voxel_shape_data.hpp index 386cffd89..9bfde76a5 100644 --- a/engine/src/toast/physics/voxel_shape_data.hpp +++ b/engine/src/toast/physics/voxel_shape_data.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -39,6 +40,8 @@ struct VoxelShapeData { std::optional pending_push; std::vector detached_components; std::unique_ptr owned_volume; + /// The last connectivity analysis so the next one skips the bricks a carve did not touch + std::unique_ptr connectivity_cache; BodyID fragment_origin; uint64_t fragment_sequence = 0; float fragment_sleep_seconds = 0.0f; diff --git a/engine/src/toast/physics/voxel_smash.hpp b/engine/src/toast/physics/voxel_smash.hpp index 87f6b50d6..296fbd047 100644 --- a/engine/src/toast/physics/voxel_smash.hpp +++ b/engine/src/toast/physics/voxel_smash.hpp @@ -126,8 +126,8 @@ auto collectBrokenPieces( } const auto brick_dim = static_cast(voxel::k_brick_dim); - const glm::ivec3 first_brick = first / brick_dim; - const glm::ivec3 last_brick = last / brick_dim; + const glm::ivec3 first_brick = voxel::brickOf(first); + const glm::ivec3 last_brick = voxel::brickOf(last); for (int32_t bz = first_brick.z; bz <= last_brick.z; ++bz) { for (int32_t by = first_brick.y; by <= last_brick.y; ++by) { @@ -224,8 +224,8 @@ auto collectCellPieces( std::vector> cells; const auto brick_dim = static_cast(voxel::k_brick_dim); - const glm::ivec3 first_brick = first / brick_dim; - const glm::ivec3 last_brick = last / brick_dim; + const glm::ivec3 first_brick = voxel::brickOf(first); + const glm::ivec3 last_brick = voxel::brickOf(last); for (int32_t bz = first_brick.z; bz <= last_brick.z; ++bz) { for (int32_t by = first_brick.y; by <= last_brick.y; ++by) { for (int32_t bx = first_brick.x; bx <= last_brick.x; ++bx) { diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index d431d5744..7a0ecdfb0 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -797,6 +797,11 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re supported_vulkan12.shaderSampledImageArrayNonUniformIndexing == VK_TRUE, "Vulkan 1.2 shaderSampledImageArrayNonUniformIndexing" ); + // Some compiled shaders declare StorageBufferArrayNonUniformIndexing, undefined behaviour without the feature + require_feature( + supported_vulkan12.shaderStorageBufferArrayNonUniformIndexing == VK_TRUE, + "Vulkan 1.2 shaderStorageBufferArrayNonUniformIndexing" + ); // eDepthAttachmentOptimal and eDepthReadOnlyOptimal are only legal with this enabled require_feature(supported_vulkan12.separateDepthStencilLayouts == VK_TRUE, "Vulkan 1.2 separateDepthStencilLayouts"); // AsyncCompute tickets are timeline values @@ -984,6 +989,7 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re vulkan12_features.descriptorBindingVariableDescriptorCount = VK_TRUE; vulkan12_features.bufferDeviceAddress = VK_TRUE; vulkan12_features.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; + vulkan12_features.shaderStorageBufferArrayNonUniformIndexing = VK_TRUE; vulkan12_features.separateDepthStencilLayouts = VK_TRUE; vulkan12_features.timelineSemaphore = VK_TRUE; vulkan11_features.shaderDrawParameters = VK_TRUE; diff --git a/engine/src/toast/renderer/debug/voxel_debug.cpp b/engine/src/toast/renderer/debug/voxel_debug.cpp index 016829425..b6249c186 100644 --- a/engine/src/toast/renderer/debug/voxel_debug.cpp +++ b/engine/src/toast/renderer/debug/voxel_debug.cpp @@ -251,7 +251,7 @@ void voxelDebugProbeText(const RenderFrame& frame, const std::optionalhit.has_value()) { const Probe& probe = *result->hit; const glm::ivec3 voxel = probe.hit.voxel; - const glm::ivec3 brick = voxel / static_cast(voxel::k_brick_dim); + const glm::ivec3 brick = voxel::brickOf(voxel); const glm::ivec3 local = voxel - brick * static_cast(voxel::k_brick_dim); const glm::ivec3 coarse = brick / static_cast(voxel::gpu::k_coarse_bricks); const std::string_view name = voxelDebugNodeName(frame, probe.proxy.record_index); @@ -402,7 +402,7 @@ auto probe(const RenderFrame& frame, glm::vec2 cursor) -> std::optional(voxel::k_brick_dim)); + const glm::uvec3 brick(voxel::brickOf(hit.voxel)); Probe out {.proxy = proxy, .hit = hit}; out.world_position = near_point + direction * hit.t; 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 4789d8f48..81da155a7 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp @@ -158,7 +158,7 @@ GiClipmapPass::GiClipmapPass(const VulkanCore& core, vk::Format scene_format, vk for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { vk::BufferCreateInfo buffer_ci {}; buffer_ci.size = sizeof(FrameData); - buffer_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer; + buffer_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc; vma::AllocationCreateInfo alloc_ci {}; alloc_ci.usage = vma::MemoryUsage::eAuto; alloc_ci.flags = vma::AllocationCreateFlagBits::eMapped | vma::AllocationCreateFlagBits::eHostAccessSequentialWrite; diff --git a/engine/src/toast/renderer/passes/lighting/reflection_probe_pass.cpp b/engine/src/toast/renderer/passes/lighting/reflection_probe_pass.cpp index cfa45f007..58a6ef5c4 100644 --- a/engine/src/toast/renderer/passes/lighting/reflection_probe_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/reflection_probe_pass.cpp @@ -880,6 +880,11 @@ auto ReflectionProbePass::loadProbe(uint32_t probe, std::string_view uri) -> boo TOAST_WARN("Render", "{} is not a probe capture this build understands; it will be re-baked", uri); return false; } + // Same bounds as setProbeResolution, a larger face would overrun the staging cube + if (header.face_size < 32 || header.face_size > k_max_face_size) { + TOAST_WARN("Render", "{} has a face size of {}px; it will be re-baked", uri, header.face_size); + return false; + } if (header.format != static_cast(m_format) || header.mip_levels != m_mip_levels) { TOAST_WARN("Render", "{} was written for a different render target layout; it will be re-baked", uri); return false; 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 524f19e1c..8caacaaf1 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp @@ -387,6 +387,8 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: target.endScope(cmd); }; + // The pyramid draws bind the same set before the surface draw first writes it + m_surface.makeSampleable(cmd); if (previous_view) { const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "TracedSpecular colour pyramid"); recordPyramid(cmd, layout, sets, params); diff --git a/engine/src/toast/renderer/shaders/shader_cache.cpp b/engine/src/toast/renderer/shaders/shader_cache.cpp index a7e39db45..059268bcf 100644 --- a/engine/src/toast/renderer/shaders/shader_cache.cpp +++ b/engine/src/toast/renderer/shaders/shader_cache.cpp @@ -148,7 +148,10 @@ auto ShaderCache::loadFromDisk(toast::UID uid) -> EntryPtr { auto spirv_bytes = manager.tryLoadBytes(spirvUri(uid)); auto json_bytes = manager.tryLoadBytes(reflectionUri(uid)); - if (!spirv_bytes || spirv_bytes->empty() || !json_bytes) { + // A truncated file would abort in createShaderModule instead of recompiling + constexpr uint32_t k_spirv_magic = 0x07230203; + if (!spirv_bytes || spirv_bytes->size() < sizeof(uint32_t) || spirv_bytes->size() % sizeof(uint32_t) != 0 || !json_bytes || + std::memcmp(spirv_bytes->data(), &k_spirv_magic, sizeof(k_spirv_magic)) != 0) { return nullptr; } diff --git a/engine/src/toast/renderer/shaders/shader_compiler.cpp b/engine/src/toast/renderer/shaders/shader_compiler.cpp index 0ec1a30ac..4ba780c1b 100644 --- a/engine/src/toast/renderer/shaders/shader_compiler.cpp +++ b/engine/src/toast/renderer/shaders/shader_compiler.cpp @@ -67,9 +67,15 @@ class SlangGlobalSessionPool { } void release(Slang::ComPtr session) { + std::vector> idle; { const std::lock_guard lock(m_mutex); m_free.push_back(std::move(session)); + // Each session keeps gigabytes cached after a compile wave, so they go once nothing compiles + if (m_free.size() == m_created) { + idle.swap(m_free); + m_created = 0; + } } m_available.notify_one(); } @@ -362,7 +368,18 @@ auto compileModule(std::string_view module_name, std::string_view source_path, s } auto ShaderCompiler::compile(toast::UID uid, std::string_view source, std::string_view source_uri) -> CompiledShaderCode { - return compileModule(uid.get(), source_uri, source); + // Slang's own mimalloc keeps what a thread freed until that thread exits, gigabytes on a long-lived pool worker + CompiledShaderCode result; + std::exception_ptr error; + std::thread([&] { + try { + result = compileModule(uid.get(), source_uri, source); + } catch (...) { error = std::current_exception(); } + }).join(); + if (error) { + std::rethrow_exception(error); + } + return result; } } diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index a821317a7..4758b7410 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -1809,6 +1809,7 @@ class VulkanRenderer { uint32_t record = 0; bool mirrored = false; uint64_t frame = 0; + VoxelCollisionWorld::Volume collision; }; std::unordered_map m_voxel_proxy_math; @@ -1820,6 +1821,8 @@ class VulkanRenderer { /// What the published collision world was built from so a still scene keeps it const VoxelGpuStorage* m_voxel_collision_storage = nullptr; size_t m_voxel_collision_count = 0; + /// Collision entries of this frame's drawn proxies, scratch that keeps its capacity + std::vector m_voxel_collision_volumes; std::unordered_map m_mesh_previous_models; bool m_voxel_upload_failed_warned = false; diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 5051b6d48..46cc0a2de 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -523,6 +523,10 @@ auto VulkanRenderer::recordVoxelScopes( m_voxel_reservoirs[1].view.has_value() && m_voxel_candidate_reservoirs.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 + if (m_voxel_denoised_indirect.view.has_value()) { + sync::transition(*frame.command_buffer, m_voxel_denoised_indirect.state, sync::Usage::fragment_sampled); + } return false; } // Decided once since voxel lighting and the post pass must agree on which pixels lost their environment specular @@ -1188,6 +1192,9 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex to_nearest.image(m_glass_mask.state, sync::Usage::color_attachment); to_nearest.image(m_glass_nearest_normal.state, sync::Usage::color_attachment); to_nearest.image(m_glass_nearest_motion.state, sync::Usage::color_attachment); + // The nearest pipeline binds the storage set that holds the backdrop just copied + to_nearest.image(m_glass_backdrop.state, sync::Usage::fragment_sampled); + to_nearest.image(m_glass_backdrop_depth.state, sync::Usage::depth_sampled); to_nearest.flush(cmd); vk::RenderingAttachmentInfo nearest_mask {}; @@ -1384,7 +1391,24 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex const vk::Image image = m_output_target->getColorImage(image_index); sync::Usage& output_usage = m_output_image_usage.at(image_index); - barriers.image(image, colorSubresourceRange(), output_usage, sync::Usage::color_attachment); + if (output_usage == sync::Usage::none) { + // A fresh image has no tracked stage, but its transition must still wait for the acquire, which waits at color output + const vk::ImageMemoryBarrier2 first_use( + vk::PipelineStageFlagBits2::eColorAttachmentOutput, + vk::AccessFlagBits2::eNone, + vk::PipelineStageFlagBits2::eColorAttachmentOutput, + vk::AccessFlagBits2::eColorAttachmentWrite, + vk::ImageLayout::eUndefined, + vk::ImageLayout::eColorAttachmentOptimal, + VK_QUEUE_FAMILY_IGNORED, + VK_QUEUE_FAMILY_IGNORED, + image, + colorSubresourceRange() + ); + frame.command_buffer.pipelineBarrier2(vk::DependencyInfo({}, {}, {}, first_use)); + } else { + barriers.image(image, colorSubresourceRange(), output_usage, sync::Usage::color_attachment); + } output_usage = sync::Usage::color_attachment; barriers.flush(*frame.command_buffer); diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index a9ab5a0a7..86ea10003 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -70,7 +70,7 @@ namespace renderer { void VulkanRenderer::waitForOutputImage() { ZoneScoped; using clock = std::chrono::steady_clock; - constexpr auto k_budget = std::chrono::milliseconds(8); + constexpr auto k_budget = std::chrono::milliseconds(16); constexpr auto k_step = std::chrono::milliseconds(1); const auto deadline = clock::now() + k_budget; while (clock::now() < deadline) { @@ -348,6 +348,9 @@ void VulkanRenderer::mainRenderThread() try { } catch (const vk::DeviceLostError& error) { // Nothing recovers a lost device and the abort would otherwise drop the queued logs TOAST_CRITICAL("Render", "GPU device lost on the render thread, shutting down: {}", error.what()); +} catch (const std::exception& error) { + // Escaping the thread would terminate without the reason in the log + TOAST_CRITICAL("Render", "Unhandled exception on the render thread: {}", error.what()); } void VulkanRenderer::acquireFrameSlot() noexcept { diff --git a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp index 5f0a9cd4d..d95a089e6 100644 --- a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp @@ -7,6 +7,7 @@ #include "vulkan_renderer.hpp" #include +#include #include #include #include @@ -64,6 +65,32 @@ auto packedGlassBricks(const voxel::gpu::PackedScene& scene) -> std::vector VoxelCollisionWorld::Volume { + const glm::vec3 extent = voxel::localExtent(dims); + glm::vec3 box_min {std::numeric_limits::max()}; + glm::vec3 box_max {std::numeric_limits::lowest()}; + for (int corner = 0; corner < 8; ++corner) { + const glm::vec3 local( + (corner & 1) != 0 ? extent.x : 0.0f, (corner & 2) != 0 ? extent.y : 0.0f, (corner & 4) != 0 ? extent.z : 0.0f + ); + const glm::vec3 world = glm::vec3(model * glm::vec4(local, 1.0f)); + box_min = glm::min(box_min, world); + box_max = glm::max(box_max, world); + } + const glm::mat4 to_voxel_units = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f / voxel::k_voxel_size)); + return VoxelCollisionWorld::Volume { + .world_to_voxel = to_voxel_units * inverse, + .bounds_center = glm::vec3(sphere), + .bounds_radius = sphere.w, + .box_min = box_min, + .box_max = box_max, + .record_index = record, + }; +} + auto brickCoord(const voxel::gpu::VolumeRecord& record, uint32_t index) -> uint32_t { const uint32_t x = index % record.brick_dims_x; const uint32_t y = (index / record.brick_dims_x) % record.brick_dims_y; @@ -103,22 +130,23 @@ auto packedBrickLists( std::vector> out(scene.records.size()); for (uint32_t r = 0; r < scene.records.size(); ++r) { const voxel::gpu::VolumeRecord& record = scene.records[r]; - auto list = std::make_shared(); - list->dims = glm::uvec3(record.brick_dims_x, record.brick_dims_y, record.brick_dims_z); - for (const uint32_t index : glass[r]) { - list->glass.push_back(brickCoord(record, index)); - } + const glm::uvec3 dims(record.brick_dims_x, record.brick_dims_y, record.brick_dims_z); + const auto glass_coords = glass[r] | std::views::transform([&](uint32_t index) { return brickCoord(record, index); }); const uint64_t rid = storage.nodeRid(r); const auto kept = previous != nullptr && rid != 0 && !dirty.contains(rid) ? previous->recordIndexOf(rid) : std::nullopt; const VoxelBrickList* old = kept.has_value() ? previous->brickList(*kept).get() : nullptr; - if (old != nullptr && old->dims != list->dims) { + if (old != nullptr && old->dims != dims) { old = nullptr; } - if (old != nullptr && old->glass == list->glass) { + if (old != nullptr && std::ranges::equal(old->glass, glass_coords)) { out[r] = previous->brickList(*kept); continue; } + + auto list = std::make_shared(); + list->dims = dims; + list->glass.assign(glass_coords.begin(), glass_coords.end()); if (old != nullptr) { list->occupied = old->occupied; } else { @@ -550,6 +578,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { // Existing keys are rewritten in place so a steady scene allocates nothing here const uint64_t proxy_frame = ++m_voxel_proxy_frame; frame.voxel_instances.reserve(gathered.size()); + m_voxel_collision_volumes.clear(); bool collision_changed = m_voxel_collision_storage != m_voxel_storage.get(); for (const Gathered& entry : gathered) { @@ -594,9 +623,11 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { math.dims = dims; math.record = *record; math.mirrored = glm::determinant(model) < 0.0f; + math.collision = collisionVolume(model, math.inverse, math.sphere, dims, *record); collision_changed = true; } math.frame = proxy_frame; + m_voxel_collision_volumes.push_back(math.collision); const auto previous = m_voxel_previous_models.find(node_rid); const bool has_previous = previous != m_voxel_previous_models.end(); @@ -637,32 +668,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { auto collision = std::make_shared(); collision->storage = m_voxel_storage; - collision->volumes.reserve(frame.voxel_instances.size()); - const glm::mat4 to_voxel_units = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f / voxel::k_voxel_size)); - for (const VoxelVolumeProxy& proxy : frame.voxel_instances) { - // the debris pass culls by the box of the volume - const glm::vec3 extent = voxel::localExtent(proxy.brick_dims); - glm::vec3 box_min {std::numeric_limits::max()}; - glm::vec3 box_max {std::numeric_limits::lowest()}; - for (int corner = 0; corner < 8; ++corner) { - const glm::vec3 local( - (corner & 1) != 0 ? extent.x : 0.0f, (corner & 2) != 0 ? extent.y : 0.0f, (corner & 4) != 0 ? extent.z : 0.0f - ); - const glm::vec3 world = glm::vec3(proxy.model * glm::vec4(local, 1.0f)); - box_min = glm::min(box_min, world); - box_max = glm::max(box_max, world); - } - collision->volumes.push_back( - VoxelCollisionWorld::Volume { - .world_to_voxel = to_voxel_units * proxy.inverse_model, - .bounds_center = proxy.bounds_center, - .bounds_radius = proxy.bounds_radius, - .box_min = box_min, - .box_max = box_max, - .record_index = proxy.record_index, - } - ); - } + collision->volumes = m_voxel_collision_volumes; std::scoped_lock lock(m_voxel_collision_mutex); m_voxel_collision_world = std::move(collision); } diff --git a/engine/src/toast/voxel/brick.hpp b/engine/src/toast/voxel/brick.hpp index 71410777e..baccdc46e 100644 --- a/engine/src/toast/voxel/brick.hpp +++ b/engine/src/toast/voxel/brick.hpp @@ -131,6 +131,19 @@ constexpr auto popCount(const BrickOccupancy& brick) noexcept -> uint32_t { return total; } +/// Calls visit(local_index, x, y, z) for every set bit in ascending index order +template +constexpr void forEachSetVoxel(const BrickOccupancy& mask, Visit&& visit) { + for (uint32_t z = 0; z < k_brick_dim; ++z) { + uint64_t word = mask[z]; + while (word != 0ull) { + const auto bit = static_cast(std::countr_zero(word)); + word &= word - 1ull; + visit((z * k_brick_dim * k_brick_dim) + bit, bit & 7u, bit >> 3u, z); + } + } +} + struct BrickExtent { BrickCoord min; BrickCoord max; @@ -290,16 +303,18 @@ constexpr auto dilate(const BrickOccupancy& brick) noexcept -> BrickOccupancy { neighboursNegZ(brick) | neighboursPosZ(brick); } +/// Packs the x == 0 column bits of a slice (bit y * 8) into the low byte with bit y, one multiply instead of 8 tests +[[nodiscard]] +constexpr auto gatherColumn(uint64_t slice) noexcept -> uint64_t { + return ((slice & k_column_x_min) * 0x0102040810204080ull) >> 56; +} + /// @brief x == 0 plane with bit z * 8 + y [[nodiscard]] constexpr auto faceNegX(const BrickOccupancy& brick) noexcept -> uint64_t { uint64_t out = 0; for (uint32_t z = 0; z < k_brick_dim; ++z) { - for (uint32_t y = 0; y < k_brick_dim; ++y) { - if (((brick[z] >> sliceBit(0, y)) & 1ull) != 0ull) { - out |= 1ull << ((z * k_brick_dim) + y); - } - } + out |= gatherColumn(brick[z]) << (z * k_brick_dim); } return out; } @@ -309,15 +324,13 @@ constexpr auto faceNegX(const BrickOccupancy& brick) noexcept -> uint64_t { constexpr auto facePosX(const BrickOccupancy& brick) noexcept -> uint64_t { uint64_t out = 0; for (uint32_t z = 0; z < k_brick_dim; ++z) { - for (uint32_t y = 0; y < k_brick_dim; ++y) { - if (((brick[z] >> sliceBit(k_brick_dim - 1, y)) & 1ull) != 0ull) { - out |= 1ull << ((z * k_brick_dim) + y); - } - } + out |= gatherColumn(brick[z] >> (k_brick_dim - 1)) << (z * k_brick_dim); } return out; } +static_assert(gatherColumn(0x0100000000000001ull) == 0x81ull && gatherColumn(0x8080808080808080ull >> 7) == 0xFFull); + /// @brief y == 0 plane with bit z * 8 + x [[nodiscard]] constexpr auto faceNegY(const BrickOccupancy& brick) noexcept -> uint64_t { diff --git a/engine/src/toast/voxel/brick_pool.cpp b/engine/src/toast/voxel/brick_pool.cpp index 647c7d18f..851b1240f 100644 --- a/engine/src/toast/voxel/brick_pool.cpp +++ b/engine/src/toast/voxel/brick_pool.cpp @@ -27,9 +27,12 @@ BrickPool::BrickPool(uint32_t capacity) : m_capacity(capacity), m_free_head(packHead(k_invalid_brick, 0)), m_next_free(std::make_unique[]>(capacity)), // NOLINT(modernize-avoid-c-arrays) - m_is_free(std::make_unique[]>(capacity)), // NOLINT(modernize-avoid-c-arrays) m_references(std::make_unique[]>(capacity)) { // NOLINT(modernize-avoid-c-arrays) assert(capacity < k_invalid_brick); +#ifndef NDEBUG + // only the double free assert reads it so release builds skip the array and its store per allocation + m_is_free = std::make_unique[]>(capacity); // NOLINT(modernize-avoid-c-arrays) +#endif // allocate clears every brick m_material = std::make_unique_for_overwrite( // NOLINT(modernize-avoid-c-arrays) @@ -41,16 +44,20 @@ BrickPool::BrickPool(uint32_t capacity) } } -auto BrickPool::allocate() -> uint32_t { +auto BrickPool::allocate(bool cleared) -> uint32_t { uint64_t head = m_free_head.load(std::memory_order_acquire); while (headId(head) != k_invalid_brick) { const uint32_t id = headId(head); const uint32_t next = m_next_free[id].load(std::memory_order_relaxed); if (m_free_head.compare_exchange_weak(head, packHead(next, headTag(head) + 1), std::memory_order_acquire)) { +#ifndef NDEBUG m_is_free[id].store(false, std::memory_order_relaxed); +#endif m_references[id].store(1, std::memory_order_release); m_allocated.fetch_add(1, std::memory_order_relaxed); - clearBrick(id); + if (cleared) { + clearBrick(id); + } return id; } } @@ -64,7 +71,9 @@ auto BrickPool::allocate() -> uint32_t { m_allocated.fetch_add(1, std::memory_order_relaxed); m_references[unused].store(1, std::memory_order_release); - clearBrick(unused); + if (cleared) { + clearBrick(unused); + } return unused; } @@ -102,26 +111,4 @@ void BrickPool::clearBrick(uint32_t id) { m_occupancy[id] = BrickOccupancy {}; } -auto BrickPool::material(uint32_t id) -> std::span { - assert(isValid(id)); - const size_t base = static_cast(id) * k_brick_material_bytes; - return std::span(m_material.get() + base, k_brick_material_bytes); -} - -auto BrickPool::material(uint32_t id) const -> std::span { - assert(isValid(id)); - const size_t base = static_cast(id) * k_brick_material_bytes; - return std::span(m_material.get() + base, k_brick_material_bytes); -} - -auto BrickPool::occupancy(uint32_t id) -> BrickOccupancy& { - assert(isValid(id)); - return m_occupancy[id]; -} - -auto BrickPool::occupancy(uint32_t id) const -> const BrickOccupancy& { - assert(isValid(id)); - return m_occupancy[id]; -} - } diff --git a/engine/src/toast/voxel/brick_pool.hpp b/engine/src/toast/voxel/brick_pool.hpp index 1b593f595..c2c5769c3 100644 --- a/engine/src/toast/voxel/brick_pool.hpp +++ b/engine/src/toast/voxel/brick_pool.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -27,9 +28,10 @@ class TOAST_API BrickPool { public: explicit BrickPool(uint32_t capacity); + /// @param cleared false leaves stale contents for a caller that overwrites the whole brick /// @returns k_invalid_brick when the pool is exhausted [[nodiscard]] - auto allocate() -> uint32_t; + auto allocate(bool cleared = true) -> uint32_t; /// @brief The id must come from allocate and not already be freed void free(uint32_t id); @@ -39,16 +41,32 @@ class TOAST_API BrickPool { auto referenceCount(uint32_t id) const noexcept -> uint32_t; [[nodiscard]] - auto material(uint32_t id) -> std::span; + auto material(uint32_t id) -> std::span { + assert(isValid(id)); + return std::span( + m_material.get() + (static_cast(id) * k_brick_material_bytes), k_brick_material_bytes + ); + } [[nodiscard]] - auto material(uint32_t id) const -> std::span; + auto material(uint32_t id) const -> std::span { + assert(isValid(id)); + return std::span( + m_material.get() + (static_cast(id) * k_brick_material_bytes), k_brick_material_bytes + ); + } [[nodiscard]] - auto occupancy(uint32_t id) -> BrickOccupancy&; + auto occupancy(uint32_t id) -> BrickOccupancy& { + assert(isValid(id)); + return m_occupancy[id]; + } [[nodiscard]] - auto occupancy(uint32_t id) const -> const BrickOccupancy&; + auto occupancy(uint32_t id) const -> const BrickOccupancy& { + assert(isValid(id)); + return m_occupancy[id]; + } [[nodiscard]] auto capacity() const noexcept -> uint32_t { diff --git a/engine/src/toast/voxel/connectivity.cpp b/engine/src/toast/voxel/connectivity.cpp index 3803a82b9..87841d03f 100644 --- a/engine/src/toast/voxel/connectivity.cpp +++ b/engine/src/toast/voxel/connectivity.cpp @@ -2,7 +2,7 @@ namespace voxel { -auto analyseConnectivity(const Volume& volume) -> Connectivity { +auto analyseConnectivity(const Volume& volume, ConnectivityCache* cache) -> Connectivity { ZoneScopedN("voxel::AnalyseConnectivity"); Connectivity out; @@ -15,26 +15,47 @@ auto analyseConnectivity(const Volume& volume) -> Connectivity { // pieces of brick s are first_piece[s] .. first_piece[s + 1] std::vector first_piece(brick_count + 1u, 0u); - for (int32_t z = 0; std::cmp_less(z, dims.z); ++z) { - for (int32_t y = 0; std::cmp_less(y, dims.y); ++y) { - for (int32_t x = 0; std::cmp_less(x, dims.x); ++x) { - const glm::ivec3 brick(x, y, z); - first_piece[slot_of(brick)] = static_cast(out.pieces.size()); + std::vector faces; + const bool reuse = cache != nullptr && cache->dims == dims; + size_t cursor = 0; + uint32_t filled = 0; + uint32_t reused = 0; + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t slot) { + std::fill(first_piece.begin() + filled, first_piece.begin() + slot + 1, static_cast(out.pieces.size())); + filled = slot + 1; + const BrickOccupancy& occupancy = *volume.occupancyPointer(brick); - const BrickOccupancy* occupancy = volume.occupancyPointer(brick); - if (occupancy == nullptr) { - continue; - } - for (const BrickOccupancy& part : brickComponents(*occupancy)) { - BrickPiece piece; - piece.brick = brick; - piece.voxels = part; - out.pieces.push_back(piece); + // Pieces of an unchanged brick come out the same and in the same order, so the last ones stand in for the flood fill + if (reuse) { + while (cursor < cache->pieces.size() && slot_of(cache->pieces[cursor].brick) < slot) { + ++cursor; + } + size_t end = cursor; + BrickOccupancy merged {}; + while (end < cache->pieces.size() && slot_of(cache->pieces[end].brick) == slot) { + merged = merged | cache->pieces[end].voxels; + ++end; + } + const bool unchanged = end > cursor && merged == occupancy; + if (unchanged) { + for (size_t i = cursor; i < end; ++i) { + out.pieces.push_back(BrickPiece {.brick = brick, .voxels = cache->pieces[i].voxels}); + faces.push_back(cache->faces[i]); } + ++reused; + } + cursor = end; + if (unchanged) { + return; } } - } - first_piece[brick_count] = static_cast(out.pieces.size()); + forEachBrickComponent(occupancy, [&](const BrickOccupancy& part) { + out.pieces.push_back(BrickPiece {.brick = brick, .voxels = part}); + faces.push_back(computeFaces(part)); + }); + }); + std::fill(first_piece.begin() + filled, first_piece.end(), static_cast(out.pieces.size())); + ZoneValue(static_cast(reused)); // Lambdas since an anonymous namespace type could collide in the unity build const auto piece_count = static_cast(out.pieces.size()); @@ -62,48 +83,36 @@ auto analyseConnectivity(const Volume& volume) -> Connectivity { set_size[a] += set_size[b]; }; - std::vector faces(piece_count); - for (uint32_t i = 0; i < piece_count; ++i) { - faces[i] = computeFaces(out.pieces[i].voxels); - } - - for (int32_t z = 0; std::cmp_less(z, dims.z); ++z) { - for (int32_t y = 0; std::cmp_less(y, dims.y); ++y) { - for (int32_t x = 0; std::cmp_less(x, dims.x); ++x) { - const glm::ivec3 brick(x, y, z); - const uint32_t here = slot_of(brick); + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t here) { + for (int32_t axis = 0; axis < 3; ++axis) { + glm::ivec3 next = brick; + next[axis] += 1; + if (std::cmp_greater_equal(next[axis], dims[axis])) { + continue; + } + const uint32_t there = slot_of(next); - for (int32_t axis = 0; axis < 3; ++axis) { - glm::ivec3 next = brick; - next[axis] += 1; - if (std::cmp_greater_equal(next[axis], dims[axis])) { - continue; + for (uint32_t p = first_piece[here]; p < first_piece[here + 1u]; ++p) { + uint64_t outward = faces[p].pos_z; + if (axis == 0) { + outward = faces[p].pos_x; + } else if (axis == 1) { + outward = faces[p].pos_y; + } + for (uint32_t q = first_piece[there]; q < first_piece[there + 1u]; ++q) { + uint64_t inward = faces[q].neg_z; + if (axis == 0) { + inward = faces[q].neg_x; + } else if (axis == 1) { + inward = faces[q].neg_y; } - const uint32_t there = slot_of(next); - - for (uint32_t p = first_piece[here]; p < first_piece[here + 1u]; ++p) { - uint64_t outward = faces[p].pos_z; - if (axis == 0) { - outward = faces[p].pos_x; - } else if (axis == 1) { - outward = faces[p].pos_y; - } - for (uint32_t q = first_piece[there]; q < first_piece[there + 1u]; ++q) { - uint64_t inward = faces[q].neg_z; - if (axis == 0) { - inward = faces[q].neg_x; - } else if (axis == 1) { - inward = faces[q].neg_y; - } - if (facesConnect(outward, inward)) { - unite(p, q); - } - } + if (facesConnect(outward, inward)) { + unite(p, q); } } } } - } + }); // Numbered by first appearance so labels do not depend on union find internals std::vector label(piece_count, k_no_component); @@ -114,6 +123,12 @@ auto analyseConnectivity(const Volume& volume) -> Connectivity { } out.pieces[i].component = label[root]; } + + if (cache != nullptr) { + cache->dims = dims; + cache->pieces = out.pieces; + cache->faces = std::move(faces); + } return out; } diff --git a/engine/src/toast/voxel/connectivity.hpp b/engine/src/toast/voxel/connectivity.hpp index f5e685ecf..5a9d058a4 100644 --- a/engine/src/toast/voxel/connectivity.hpp +++ b/engine/src/toast/voxel/connectivity.hpp @@ -18,17 +18,14 @@ namespace voxel { inline constexpr uint32_t k_no_component = 0xFFFFFFFFu; -/// @brief Edge or corner contact does not connect -[[nodiscard]] -inline auto brickComponents(const BrickOccupancy& brick) -> std::vector { - if (isEmpty(brick)) { - return {}; - } +/// @brief Edge or corner contact does not connect, visits each component without allocating +template +void forEachBrickComponent(const BrickOccupancy& brick, Visit&& visit) { if (isFull(brick)) { - return std::vector(1, brick); + visit(brick); + return; } - std::vector out; BrickOccupancy remaining = brick; while (!isEmpty(remaining)) { // x & (~x + 1) isolates the lowest set bit @@ -48,9 +45,15 @@ inline auto brickComponents(const BrickOccupancy& brick) -> std::vector std::vector { + std::vector out; + forEachBrickComponent(brick, [&](const BrickOccupancy& part) { out.push_back(part); }); return out; } @@ -92,7 +95,19 @@ struct Connectivity { } }; +/// What one analysis leaves for the next so a brick that did not change keeps its pieces without a flood fill +struct ConnectivityCache { + glm::uvec3 dims {0}; + /// In slot order like Connectivity::pieces + std::vector pieces; + std::vector faces; +}; + +/** + * @param cache when set its unchanged bricks are reused and it is refilled, the result is the same as without it + * @note One analysis at a time per cache + */ [[nodiscard]] -TOAST_API auto analyseConnectivity(const Volume& volume) -> Connectivity; +TOAST_API auto analyseConnectivity(const Volume& volume, ConnectivityCache* cache = nullptr) -> Connectivity; } diff --git a/engine/src/toast/voxel/mass_accumulator.hpp b/engine/src/toast/voxel/mass_accumulator.hpp index 1fe9b6769..72980e9bd 100644 --- a/engine/src/toast/voxel/mass_accumulator.hpp +++ b/engine/src/toast/voxel/mass_accumulator.hpp @@ -5,8 +5,11 @@ */ #pragma once +#include "brick.hpp" #include "voxel_constants.hpp" +#include +#include #include #include #include @@ -150,6 +153,54 @@ struct MassMoments { } }; +/** + * Moments of the set voxels of a brick at density 1, in brick local coordinates + * @note Sums of x, x * x and x * y come from popcounts of the bits of each coordinate so a dense mask costs no voxel walk + */ +[[nodiscard]] +constexpr auto maskMoments(const BrickOccupancy& mask) noexcept -> MassMoments { + // slice bit index is y * 8 + x, these pick the bits whose x or y has bit k set + constexpr std::array x_bit {0xAAAAAAAAAAAAAAAAull, 0xCCCCCCCCCCCCCCCCull, 0xF0F0F0F0F0F0F0F0ull}; + constexpr std::array y_bit {0xFF00FF00FF00FF00ull, 0xFFFF0000FFFF0000ull, 0xFFFFFFFF00000000ull}; + + MassMoments out; + for (uint32_t z = 0; z < k_brick_dim; ++z) { + const uint64_t word = mask[z]; + if (word == 0ull) { + continue; + } + const auto count = [word](uint64_t bits) { return static_cast(std::popcount(word & bits)); }; + int64_t sx = 0; + int64_t sy = 0; + int64_t sxx = 0; + int64_t syy = 0; + int64_t sxy = 0; + for (uint32_t j = 0; j < 3; ++j) { + sx += count(x_bit[j]) << j; + sy += count(y_bit[j]) << j; + // a * b is the sum over bit pairs of 2^(j + k) when both bits are set + for (uint32_t k = 0; k < 3; ++k) { + sxx += count(x_bit[j] & x_bit[k]) << (j + k); + syy += count(y_bit[j] & y_bit[k]) << (j + k); + sxy += count(x_bit[j] & y_bit[k]) << (j + k); + } + } + const auto n = static_cast(std::popcount(word)); + const auto lz = static_cast(z); + out.mass += n; + out.m_x += sx; + out.m_y += sy; + out.m_z += lz * n; + out.m_xx += sxx; + out.m_yy += syy; + out.m_zz += lz * lz * n; + out.m_xy += sxy; + out.m_xz += lz * sx; + out.m_yz += lz * sy; + } + return out; +} + struct MassProperties { /// kg float mass = 0.0f; diff --git a/engine/src/toast/voxel/surface.cpp b/engine/src/toast/voxel/surface.cpp index 0583cda10..47d6da497 100644 --- a/engine/src/toast/voxel/surface.cpp +++ b/engine/src/toast/voxel/surface.cpp @@ -4,16 +4,6 @@ namespace voxel { -namespace { - -/// @brief Arithmetic shift so voxel -1 lands in brick -1 -[[nodiscard]] -auto brickContaining(glm::ivec3 voxel) noexcept -> glm::ivec3 { - return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; -} - -} - auto VolumeSurface::contains(glm::ivec3 brick) const noexcept -> bool { return brick.x >= 0 && brick.y >= 0 && brick.z >= 0 && std::cmp_less(brick.x, m_brick_dims.x) && std::cmp_less(brick.y, m_brick_dims.y) && std::cmp_less(brick.z, m_brick_dims.z); @@ -30,13 +20,7 @@ void VolumeSurface::rebuild(const Volume& volume) { m_brick_dims = volume.brickDims(); m_bricks.clear(); - for (int32_t z = 0; std::cmp_less(z, m_brick_dims.z); ++z) { - for (int32_t y = 0; std::cmp_less(y, m_brick_dims.y); ++y) { - for (int32_t x = 0; std::cmp_less(x, m_brick_dims.x); ++x) { - rebuildBrick(volume, glm::ivec3 {x, y, z}); - } - } - } + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t) { rebuildBrick(volume, brick); }); } void VolumeSurface::rebuildBrick(const Volume& volume, glm::ivec3 brick) { @@ -52,11 +36,25 @@ void VolumeSurface::rebuildBrick(const Volume& volume, glm::ivec3 brick) { return; } - std::vector& list = m_bricks[slot]; - list.clear(); - buildBrickSurfaceInto(*occupancy, volume.neighbourhoodOf(brick), list); - if (list.empty()) { - m_bricks.erase(slot); + thread_local std::vector scratch; + scratch.clear(); + buildBrickSurfaceInto(*occupancy, volume.neighbourhoodOf(brick), scratch); + const auto it = m_bricks.find(slot); + if (scratch.empty()) { + if (it != m_bricks.end()) { + m_bricks.erase(it); + } + return; + } + // A neighbour repaired for nothing keeps its list, and with it the one every copy of this surface shares + if (it != m_bricks.end() && *it->second == scratch) { + return; + } + auto list = std::make_shared>(scratch); + if (it != m_bricks.end()) { + it->second = std::move(list); + } else { + m_bricks.emplace(slot, std::move(list)); } } @@ -66,7 +64,7 @@ void VolumeSurface::repairAround(const Volume& volume, glm::ivec3 voxel) { return; } - const glm::ivec3 brick = brickContaining(voxel); + const glm::ivec3 brick = brickOf(voxel); const glm::ivec3 local {voxel.x & 7, voxel.y & 7, voxel.z & 7}; const int32_t last = static_cast(k_brick_dim) - 1; @@ -124,13 +122,13 @@ auto VolumeSurface::brickSurface(glm::ivec3 brick) const -> std::spansecond}; + return {*it->second}; } auto VolumeSurface::surfaceVoxelCount() const -> size_t { size_t total = 0; for (const auto& [slot, list] : m_bricks) { - total += list.size(); + total += list->size(); } return total; } diff --git a/engine/src/toast/voxel/surface.hpp b/engine/src/toast/voxel/surface.hpp index cb8e4442f..0b6bb8b3e 100644 --- a/engine/src/toast/voxel/surface.hpp +++ b/engine/src/toast/voxel/surface.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -221,7 +222,8 @@ class TOAST_API VolumeSurface { glm::uvec3 m_brick_dims {0}; - std::unordered_map> m_bricks; + /// Immutable lists shared by every copy, so copying a surface for a query snapshot only bumps reference counts + std::unordered_map>> m_bricks; }; } diff --git a/engine/src/toast/voxel/voxel_edit.cpp b/engine/src/toast/voxel/voxel_edit.cpp index 5e08051bd..c0ec5e51d 100644 --- a/engine/src/toast/voxel/voxel_edit.cpp +++ b/engine/src/toast/voxel/voxel_edit.cpp @@ -8,11 +8,6 @@ namespace { constexpr int32_t k_dim = static_cast(k_brick_dim); -[[nodiscard]] -auto brickOf(glm::ivec3 voxel) noexcept -> glm::ivec3 { - return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; -} - [[nodiscard]] auto centreOf(glm::ivec3 voxel) noexcept -> glm::vec3 { return glm::vec3(voxel) + 0.5f; @@ -220,33 +215,41 @@ auto boundsUnion(const EditBounds& a, const EditBounds& b) noexcept -> EditBound } auto occupiedBounds(const Volume& volume) -> std::optional { + const auto solid_occupancy = [&](glm::ivec3 brick) -> const BrickOccupancy* { + return volume.brickSolidCount(brick) != 0 ? volume.occupancyPointer(brick) : nullptr; + }; + + // Brick-level bounds first: the voxel extreme on each axis can only come from the brick plane at that extreme + glm::ivec3 brick_min {std::numeric_limits::max()}; + glm::ivec3 brick_max {std::numeric_limits::min()}; + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t) { + brick_min = glm::min(brick_min, brick); + brick_max = glm::max(brick_max, brick); + }); + if (glm::any(glm::greaterThan(brick_min, brick_max))) { + return std::nullopt; + } + + // Refine on the six faces of the brick box only, interior bricks cannot move the bounds EditBounds out {glm::ivec3(std::numeric_limits::max()), glm::ivec3(std::numeric_limits::min())}; - bool any = false; - for (uint32_t index = 0; index < volume.brickCount(); ++index) { - const glm::ivec3 brick = volume.brickAtIndex(index); - const BrickOccupancy* occupancy = volume.occupancyPointer(brick); - if (occupancy == nullptr || isEmpty(*occupancy)) { - continue; - } - const glm::ivec3 origin = brick * k_dim; - if (isFull(*occupancy)) { - out.min = glm::min(out.min, origin); - out.max = glm::max(out.max, origin + (k_dim - 1)); - any = true; - continue; - } - for (uint32_t i = 0; i < k_brick_voxel_count; ++i) { - if (!isSolid(*occupancy, i)) { - continue; + for (int32_t z = brick_min.z; z <= brick_max.z; ++z) { + for (int32_t y = brick_min.y; y <= brick_max.y; ++y) { + const bool yz_face = z == brick_min.z || z == brick_max.z || y == brick_min.y || y == brick_max.y; + const int32_t x_step = yz_face ? 1 : std::max(1, brick_max.x - brick_min.x); + for (int32_t x = brick_min.x; x <= brick_max.x; x += x_step) { + const glm::ivec3 brick {x, y, z}; + const BrickOccupancy* occupancy = solid_occupancy(brick); + if (occupancy == nullptr) { + continue; + } + const BrickExtent extent = occupiedExtent(*occupancy); + const glm::ivec3 origin = brick * k_dim; + out.min = glm::min(out.min, origin + glm::ivec3(extent.min.x, extent.min.y, extent.min.z)); + out.max = glm::max(out.max, origin + glm::ivec3(extent.max.x, extent.max.y, extent.max.z)); } - const BrickCoord local = localFromIndex(i); - const glm::ivec3 voxel = origin + glm::ivec3(local.x, local.y, local.z); - out.min = glm::min(out.min, voxel); - out.max = glm::max(out.max, voxel); - any = true; } } - return any ? std::optional {out} : std::nullopt; + return out; } auto fillBox(Volume& volume, glm::ivec3 a, glm::ivec3 b, const WriteBrush& brush) -> EditResult { @@ -1135,21 +1138,17 @@ auto raycast(const Volume& volume, glm::vec3 origin, glm::vec3 direction, float auto idHistogram(const Volume& volume) -> std::array { std::array counts {}; - for (uint32_t index = 0; index < volume.brickCount(); ++index) { - const glm::ivec3 brick = volume.brickAtIndex(index); + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t) { const BrickEntry entry = volume.entryAt(brick); - if (entry.tag() == BrickTag::empty) { - continue; - } if (entry.tag() == BrickTag::uniform) { counts[entry.payload() & 0xFFu] += k_brick_voxel_count; - continue; + return; } const auto material = volume.pool()->material(entry.payload()); for (uint32_t i = 0; i < k_brick_voxel_count; ++i) { ++counts[material[i]]; } - } + }); counts[k_empty_palette_index] = 0; return counts; } diff --git a/engine/src/toast/voxel/voxel_volume.cpp b/engine/src/toast/voxel/voxel_volume.cpp index d67865a1c..82f900abf 100644 --- a/engine/src/toast/voxel/voxel_volume.cpp +++ b/engine/src/toast/voxel/voxel_volume.cpp @@ -6,18 +6,6 @@ namespace voxel { namespace { -static_assert(k_brick_dim == 8, "brickOfVoxel and localOf shift and mask by 3 and 7"); - -[[nodiscard]] -auto brickOfVoxel(glm::ivec3 voxel) noexcept -> glm::ivec3 { - return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; -} - -[[nodiscard]] -auto localOf(glm::ivec3 voxel) noexcept -> BrickCoord { - return BrickCoord {static_cast(voxel.x & 7), static_cast(voxel.y & 7), static_cast(voxel.z & 7)}; -} - [[nodiscard]] auto nextVolumeId() noexcept -> uint64_t { static std::atomic counter {0}; @@ -29,6 +17,8 @@ auto nextVolumeId() noexcept -> uint64_t { Volume::Volume(BrickPool& pool, glm::uvec3 brick_dims) : m_pool(&pool), m_brick_dims(brick_dims), m_id(nextVolumeId()) { const size_t count = static_cast(brick_dims.x) * brick_dims.y * brick_dims.z; m_entries.assign(count, BrickEntry {}); + m_brick_solid.assign(count, 0); + m_solid_mask.assign((count + 63) / 64, 0ull); } Volume::~Volume() { @@ -40,6 +30,9 @@ Volume::Volume(Volume&& other) noexcept m_brick_dims(other.m_brick_dims), m_texture_origin(other.m_texture_origin), m_entries(std::move(other.m_entries)), + m_brick_solid(std::move(other.m_brick_solid)), + m_solid_mask(std::move(other.m_solid_mask)), + m_solid_voxels(other.m_solid_voxels), m_revision(other.m_revision), m_id(other.m_id), m_dirty_mask(std::move(other.m_dirty_mask)), @@ -48,6 +41,9 @@ Volume::Volume(Volume&& other) noexcept other.m_pool = nullptr; other.m_brick_dims = glm::uvec3 {0}; other.m_entries.clear(); + other.m_brick_solid.clear(); + other.m_solid_mask.clear(); + other.m_solid_voxels = 0; other.m_dirty_mask.clear(); other.m_dirty_list.clear(); other.m_id = 0; @@ -60,6 +56,9 @@ auto Volume::operator=(Volume&& other) noexcept -> Volume& { m_brick_dims = other.m_brick_dims; m_texture_origin = other.m_texture_origin; m_entries = std::move(other.m_entries); + m_brick_solid = std::move(other.m_brick_solid); + m_solid_mask = std::move(other.m_solid_mask); + m_solid_voxels = other.m_solid_voxels; m_revision = other.m_revision; m_id = other.m_id; m_dirty_mask = std::move(other.m_dirty_mask); @@ -68,6 +67,9 @@ auto Volume::operator=(Volume&& other) noexcept -> Volume& { other.m_pool = nullptr; other.m_brick_dims = glm::uvec3 {0}; other.m_entries.clear(); + other.m_brick_solid.clear(); + other.m_solid_mask.clear(); + other.m_solid_voxels = 0; other.m_dirty_mask.clear(); other.m_dirty_list.clear(); other.m_id = 0; @@ -75,12 +77,41 @@ auto Volume::operator=(Volume&& other) noexcept -> Volume& { return *this; } +void Volume::syncBrick(uint32_t index) noexcept { + const BrickEntry entry = m_entries[index]; + uint32_t count = 0; + switch (entry.tag()) { + case BrickTag::empty: break; + case BrickTag::uniform: count = k_brick_voxel_count; break; + default: count = popCount(std::as_const(*m_pool).occupancy(entry.payload())); break; + } + m_solid_voxels = m_solid_voxels - m_brick_solid[index] + count; + m_brick_solid[index] = static_cast(count); + uint64_t& word = m_solid_mask[index >> 6u]; + const uint64_t bit = 1ull << (index & 63u); + word = count != 0 ? (word | bit) : (word & ~bit); +} + +void Volume::recountAll() noexcept { + m_brick_solid.assign(m_entries.size(), 0); + m_solid_mask.assign((m_entries.size() + 63) / 64, 0ull); + m_solid_voxels = 0; + for (uint32_t index = 0; index < m_entries.size(); ++index) { + if (m_entries[index].tag() != BrickTag::empty) { + syncBrick(index); + } + } +} + auto Volume::instanceOf(const Volume& source) -> Volume { assert(source.m_pool != nullptr); Volume out(*source.m_pool, source.m_brick_dims); out.m_texture_origin = source.m_texture_origin; out.m_entries = source.m_entries; + out.m_brick_solid = source.m_brick_solid; + out.m_solid_mask = source.m_solid_mask; + out.m_solid_voxels = source.m_solid_voxels; for (BrickEntry& entry : out.m_entries) { if (entry.isPooled()) { source.m_pool->retain(entry.payload()); @@ -90,6 +121,48 @@ auto Volume::instanceOf(const Volume& source) -> Volume { return out; } +void Volume::reshareFrom(const Volume& source) { + assert(source.m_pool != nullptr); + if (m_pool != source.m_pool || this == &source) { + *this = instanceOf(source); + return; + } + + const auto same_brick = [](BrickEntry a, BrickEntry b) { return a.isPooled() && b.isPooled() && a.payload() == b.payload(); }; + const size_t old_count = m_entries.size(); + const size_t new_count = source.m_entries.size(); + // retain everything new first so a brick that only moved index never drops to zero in between + for (size_t index = 0; index < new_count; ++index) { + const BrickEntry entry = source.m_entries[index]; + if (entry.isPooled() && not(index < old_count && same_brick(m_entries[index], entry))) { + m_pool->retain(entry.payload()); + } + } + for (size_t index = 0; index < old_count; ++index) { + const BrickEntry entry = m_entries[index]; + if (entry.isPooled() && not(index < new_count && same_brick(entry, source.m_entries[index]))) { + m_pool->free(entry.payload()); + } + } + + m_brick_dims = source.m_brick_dims; + m_texture_origin = source.m_texture_origin; + m_entries = source.m_entries; + m_brick_solid = source.m_brick_solid; + m_solid_mask = source.m_solid_mask; + m_solid_voxels = source.m_solid_voxels; + for (BrickEntry& entry : m_entries) { + if (entry.isPooled()) { + entry = BrickEntry::make(BrickTag::shared, entry.payload()); + } + } + m_revision = 0; + m_id = nextVolumeId(); + m_dirty_mask.clear(); + m_dirty_list.clear(); + m_dirty_since = 0; +} + auto Volume::adoptResized(Volume& source, glm::ivec3 brick_offset, glm::uvec3 brick_dims) -> Volume { assert(source.m_pool != nullptr); Volume out(*source.m_pool, brick_dims); @@ -115,6 +188,7 @@ auto Volume::adoptResized(Volume& source, glm::ivec3 brick_offset, glm::uvec3 br entry = BrickEntry::make(BrickTag::shared, entry.payload()); } } + out.recountAll(); return out; } @@ -130,57 +204,6 @@ void Volume::releaseOwned() { } } -auto Volume::containsBrick(glm::ivec3 brick) const noexcept -> bool { - return brick.x >= 0 && brick.y >= 0 && brick.z >= 0 && std::cmp_less(brick.x, m_brick_dims.x) && - std::cmp_less(brick.y, m_brick_dims.y) && std::cmp_less(brick.z, m_brick_dims.z); -} - -auto Volume::containsVoxel(glm::ivec3 voxel) const noexcept -> bool { - return containsBrick(brickOfVoxel(voxel)); -} - -auto Volume::entryIndex(glm::ivec3 brick) const noexcept -> uint32_t { - assert(containsBrick(brick)); - return static_cast(brick.x) + (static_cast(brick.y) * m_brick_dims.x) + - (static_cast(brick.z) * m_brick_dims.x * m_brick_dims.y); -} - -auto Volume::entryAt(glm::ivec3 brick) const noexcept -> BrickEntry { - if (!containsBrick(brick)) { - return BrickEntry {}; - } - return m_entries[entryIndex(brick)]; -} - -auto Volume::materialAt(glm::ivec3 voxel) const noexcept -> uint8_t { - if (!containsVoxel(voxel)) { - return k_empty_palette_index; - } - - const BrickEntry entry = m_entries[entryIndex(brickOfVoxel(voxel))]; - switch (entry.tag()) { - case BrickTag::empty: return k_empty_palette_index; - case BrickTag::uniform: return static_cast(entry.payload()); - default: break; - } - - const BrickCoord local = localOf(voxel); - return m_pool->material(entry.payload())[localIndex(local.x, local.y, local.z)]; -} - -auto Volume::isSolidAt(glm::ivec3 voxel) const noexcept -> bool { - return materialAt(voxel) != k_empty_palette_index; -} - -auto Volume::occupancyPointer(glm::ivec3 brick) const noexcept -> const BrickOccupancy* { - const BrickEntry entry = entryAt(brick); - switch (entry.tag()) { - case BrickTag::empty: return nullptr; - case BrickTag::uniform: return &k_full_brick; - default: return &m_pool->occupancy(entry.payload()); - } -} - auto Volume::neighbourhoodOf(glm::ivec3 brick) const noexcept -> BrickNeighbourhood { return BrickNeighbourhood { occupancyPointer(brick + glm::ivec3 {-1, 0, 0}), @@ -198,7 +221,8 @@ auto Volume::makeWritable(uint32_t entry_index) -> uint32_t { return entry.payload(); } - const uint32_t id = m_pool->allocate(); + // uniform and pooled sources overwrite every byte below, only an empty one needs the clear + const uint32_t id = m_pool->allocate(entry.tag() == BrickTag::empty); if (id == k_invalid_brick) { return k_invalid_brick; } @@ -242,7 +266,7 @@ auto Volume::setVoxel(glm::ivec3 voxel, uint8_t material) -> VoxelWrite { return result; } - const uint32_t index = entryIndex(brickOfVoxel(voxel)); + const uint32_t index = entryIndex(brickOf(voxel)); const bool was_occupied = m_entries[index].tag() != BrickTag::empty; const uint32_t id = makeWritable(index); @@ -256,7 +280,7 @@ auto Volume::setVoxel(glm::ivec3 voxel, uint8_t material) -> VoxelWrite { result.changed = true; ++m_revision; - markDirty(brickOfVoxel(voxel)); + markDirty(brickOf(voxel)); if (material != k_empty_palette_index) { result.brick_became_occupied = !was_occupied; @@ -265,6 +289,7 @@ auto Volume::setVoxel(glm::ivec3 voxel, uint8_t material) -> VoxelWrite { m_entries[index] = BrickEntry {}; result.brick_became_empty = true; } + syncBrick(index); return result; } @@ -284,6 +309,7 @@ void Volume::setBrickUniform(glm::ivec3 brick, uint8_t material) { } m_entries[index] = next; + syncBrick(index); ++m_revision; markDirty(brick); } @@ -315,6 +341,7 @@ auto Volume::tryCollapseUniform(glm::ivec3 brick) -> bool { m_pool->free(id); m_entries[index] = BrickEntry::make(BrickTag::uniform, first); + syncBrick(index); ++m_revision; markDirty(brick); return true; @@ -331,7 +358,8 @@ auto Volume::setBrickMaterial(glm::ivec3 brick, std::spanoccupancy(id) = occupancy; + syncBrick(index); ++m_revision; markDirty(brick); return true; @@ -366,6 +395,7 @@ auto Volume::takeBrick(glm::ivec3 brick) -> BrickEntry { } m_entries[index] = BrickEntry {}; + syncBrick(index); ++m_revision; markDirty(brick); return entry; @@ -383,6 +413,7 @@ void Volume::adoptBrick(glm::ivec3 brick, BrickEntry entry) { } m_entries[index] = entry; + syncBrick(index); ++m_revision; markDirty(brick); } @@ -404,6 +435,7 @@ auto Volume::clearVoxels(glm::ivec3 brick, const BrickOccupancy& mask) -> bool { m_pool->free(m_entries[index].payload()); } m_entries[index] = BrickEntry {}; + syncBrick(index); ++m_revision; markDirty(brick); return true; @@ -416,14 +448,11 @@ auto Volume::clearVoxels(glm::ivec3 brick, const BrickOccupancy& mask) -> bool { std::span bytes = m_pool->material(id); BrickOccupancy& stored = m_pool->occupancy(id); - for (uint32_t z = 0; z < k_brick_dim; ++z) { - uint64_t word = affected[z]; - stored[z] &= ~word; - while (word != 0ull) { - bytes[(z * k_brick_dim * k_brick_dim) + static_cast(std::countr_zero(word))] = k_empty_palette_index; - word &= word - 1ull; - } - } + forEachSetVoxel(affected, [&](uint32_t local_index, uint32_t, uint32_t, uint32_t) { + bytes[local_index] = k_empty_palette_index; + }); + stored = stored & ~affected; + syncBrick(index); ++m_revision; markDirty(brick); @@ -454,6 +483,7 @@ auto Volume::copyBrickFrom(glm::ivec3 brick, const Volume& source, glm::ivec3 so } std::ranges::copy(bytes, m_pool->material(id).begin()); m_pool->occupancy(id) = std::as_const(*source.m_pool).occupancy(from.payload()); + syncBrick(index); ++m_revision; markDirty(brick); return true; @@ -485,6 +515,8 @@ void Volume::finishBrickWrite(glm::ivec3 brick, bool changed) { } else if (changed) { tryCollapseUniform(brick); } + // the caller wrote the occupancy itself so recount whether or not it says it changed + syncBrick(index); if (changed) { ++m_revision; markDirty(brick); @@ -529,18 +561,6 @@ auto Volume::brickAtIndex(uint32_t index) const noexcept -> glm::ivec3 { }; } -auto Volume::solidVoxelCount() const -> uint32_t { - uint32_t total = 0; - for (const BrickEntry& entry : m_entries) { - switch (entry.tag()) { - case BrickTag::empty: break; - case BrickTag::uniform: total += k_brick_voxel_count; break; - default: total += popCount(m_pool->occupancy(entry.payload())); break; - } - } - return total; -} - auto Volume::ownedBrickCount() const -> uint32_t { return static_cast(std::count_if(m_entries.begin(), m_entries.end(), [](const BrickEntry& entry) { return entry.tag() == BrickTag::owned; diff --git a/engine/src/toast/voxel/voxel_volume.hpp b/engine/src/toast/voxel/voxel_volume.hpp index 0497c20ef..56ef9b6ad 100644 --- a/engine/src/toast/voxel/voxel_volume.hpp +++ b/engine/src/toast/voxel/voxel_volume.hpp @@ -9,15 +9,30 @@ #include "brick_pool.hpp" #include "voxel_constants.hpp" +#include #include #include #include #include #include +#include #include namespace voxel { +static_assert(k_brick_dim == 8, "brickOf and localOf shift and mask by 3 and 7"); + +/// @brief Arithmetic shift so voxel -1 lands in brick -1 +[[nodiscard]] +inline auto brickOf(glm::ivec3 voxel) noexcept -> glm::ivec3 { + return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; +} + +[[nodiscard]] +inline auto localOf(glm::ivec3 voxel) noexcept -> BrickCoord { + return BrickCoord {static_cast(voxel.x & 7), static_cast(voxel.y & 7), static_cast(voxel.z & 7)}; +} + class TOAST_API Volume { public: struct VoxelWrite { @@ -43,6 +58,9 @@ class TOAST_API Volume { [[nodiscard]] static auto instanceOf(const Volume& source) -> Volume; + /// @brief Same result as assigning instanceOf(source) but only retains and frees the bricks that differ + void reshareFrom(const Volume& source); + [[nodiscard]] static auto adoptResized(Volume& source, glm::ivec3 brick_offset, glm::uvec3 brick_dims) -> Volume; @@ -70,19 +88,44 @@ class TOAST_API Volume { } [[nodiscard]] - auto containsBrick(glm::ivec3 brick) const noexcept -> bool; + auto containsBrick(glm::ivec3 brick) const noexcept -> bool { + return brick.x >= 0 && brick.y >= 0 && brick.z >= 0 && std::cmp_less(brick.x, m_brick_dims.x) && + std::cmp_less(brick.y, m_brick_dims.y) && std::cmp_less(brick.z, m_brick_dims.z); + } [[nodiscard]] - auto containsVoxel(glm::ivec3 voxel) const noexcept -> bool; + auto containsVoxel(glm::ivec3 voxel) const noexcept -> bool { + return containsBrick(brickOf(voxel)); + } [[nodiscard]] - auto entryAt(glm::ivec3 brick) const noexcept -> BrickEntry; + auto entryAt(glm::ivec3 brick) const noexcept -> BrickEntry { + if (!containsBrick(brick)) { + return BrickEntry {}; + } + return m_entries[entryIndex(brick)]; + } [[nodiscard]] - auto materialAt(glm::ivec3 voxel) const noexcept -> uint8_t; + auto materialAt(glm::ivec3 voxel) const noexcept -> uint8_t { + if (!containsVoxel(voxel)) { + return k_empty_palette_index; + } + + const BrickEntry entry = m_entries[entryIndex(brickOf(voxel))]; + switch (entry.tag()) { + case BrickTag::empty: return k_empty_palette_index; + case BrickTag::uniform: return static_cast(entry.payload()); + default: break; + } + const BrickCoord local = localOf(voxel); + return m_pool->material(entry.payload())[localIndex(local.x, local.y, local.z)]; + } [[nodiscard]] - auto isSolidAt(glm::ivec3 voxel) const noexcept -> bool; + auto isSolidAt(glm::ivec3 voxel) const noexcept -> bool { + return materialAt(voxel) != k_empty_palette_index; + } auto setVoxel(glm::ivec3 voxel, uint8_t material) -> VoxelWrite; @@ -119,13 +162,44 @@ class TOAST_API Volume { /// @brief Null when the brick holds nothing [[nodiscard]] - auto occupancyPointer(glm::ivec3 brick) const noexcept -> const BrickOccupancy*; + auto occupancyPointer(glm::ivec3 brick) const noexcept -> const BrickOccupancy* { + const BrickEntry entry = entryAt(brick); + switch (entry.tag()) { + case BrickTag::empty: return nullptr; + case BrickTag::uniform: return &k_full_brick; + default: return &std::as_const(*m_pool).occupancy(entry.payload()); + } + } [[nodiscard]] auto neighbourhoodOf(glm::ivec3 brick) const noexcept -> BrickNeighbourhood; [[nodiscard]] - auto solidVoxelCount() const -> uint32_t; + auto solidVoxelCount() const noexcept -> uint32_t { + return m_solid_voxels; + } + + /// Solid voxels of one brick, 0 outside the volume + [[nodiscard]] + auto brickSolidCount(glm::ivec3 brick) const noexcept -> uint32_t { + return containsBrick(brick) ? m_brick_solid[entryIndex(brick)] : 0u; + } + + /** + * Calls visit(brick, slot) for every brick that holds a solid voxel in slot order, which is z then y then x + * @note Skips empty space 64 bricks at a time so a sparse volume costs what is in it + */ + template + void forEachSolidBrick(Visit&& visit) const { + for (size_t word_index = 0; word_index < m_solid_mask.size(); ++word_index) { + uint64_t word = m_solid_mask[word_index]; + while (word != 0ull) { + const auto slot = static_cast((word_index << 6u) + static_cast(std::countr_zero(word))); + word &= word - 1ull; + visit(brickAtIndex(slot), slot); + } + } + } [[nodiscard]] auto ownedBrickCount() const -> uint32_t; @@ -164,18 +238,31 @@ class TOAST_API Volume { void markDirty(glm::ivec3 brick); [[nodiscard]] - auto entryIndex(glm::ivec3 brick) const noexcept -> uint32_t; + auto entryIndex(glm::ivec3 brick) const noexcept -> uint32_t { + assert(containsBrick(brick)); + return static_cast(brick.x) + (static_cast(brick.y) * m_brick_dims.x) + + (static_cast(brick.z) * m_brick_dims.x * m_brick_dims.y); + } auto makeWritable(uint32_t entry_index) -> uint32_t; void releaseOwned(); + void syncBrick(uint32_t index) noexcept; + + void recountAll() noexcept; + BrickPool* m_pool = nullptr; glm::uvec3 m_brick_dims {0}; glm::ivec3 m_texture_origin {0}; std::vector m_entries; + std::vector m_brick_solid; + /// One bit per slot that holds a solid voxel + std::vector m_solid_mask; + uint32_t m_solid_voxels = 0; + uint32_t m_revision = 0; uint64_t m_id = 0; diff --git a/engine/src/toast/world/world.cpp b/engine/src/toast/world/world.cpp index 6a1365330..3b2519b7e 100644 --- a/engine/src/toast/world/world.cpp +++ b/engine/src/toast/world/world.cpp @@ -1186,6 +1186,19 @@ auto testNodeInfos() -> std::unordered_map& { } void WorldTestAccess::WorldDeleter::operator()(World* world) const noexcept { + // A Box never frees its node, so nodes a test left behind would keep their script runtimes and Lua placements alive + std::vector> roots; + { + std::scoped_lock lock(world->nodes_mutex); + world->forEachNode([&roots](const ControlBox& control) { + if (control.node != nullptr && !control.node->m_parent.exists()) { + roots.emplace_back(control.node->box()); + } + }); + } + world->trees = {}; + world->trees.destroy_queue = std::move(roots); + world->drainDestroyQueue(); delete world; } diff --git a/tests/voxel/01-volume_sharing.cpp b/tests/voxel/01-volume_sharing.cpp new file mode 100644 index 000000000..a59c9f342 --- /dev/null +++ b/tests/voxel/01-volume_sharing.cpp @@ -0,0 +1,41 @@ +#include "test_registry.hpp" + +#include +#include +#include +#include + +TOAST_TEST_NAMED("voxel", "voxel/01-reshare_touches_only_changed_bricks", test_voxel_01_reshare_touches_only_changed_bricks) { + voxel::BrickPool pool(16); + voxel::Volume source(pool, glm::uvec3 {3, 1, 1}); + source.setVoxel({1, 1, 1}, 3); + source.setVoxel({9, 1, 1}, 4); + const uint32_t kept = source.entryAt({0, 0, 0}).payload(); + const uint32_t replaced = source.entryAt({1, 0, 0}).payload(); + + voxel::Volume copy = voxel::Volume::instanceOf(source); + assert(pool.referenceCount(kept) == 2 && pool.referenceCount(replaced) == 2); + + // copy on write gives brick 1 a new id while the copy still holds the old one + source.setVoxel({10, 1, 1}, 4); + const uint32_t written = source.entryAt({1, 0, 0}).payload(); + assert(written != replaced); + + copy.reshareFrom(source); + assert(pool.referenceCount(kept) == 2); + assert(pool.referenceCount(written) == 2); + assert(pool.allocatedCount() == 2); // the old brick 1 went back to the pool + assert(copy.materialAt({10, 1, 1}) == 4 && copy.materialAt({1, 1, 1}) == 3); + assert(copy.entryAt({0, 0, 0}).tag() == voxel::BrickTag::shared); + + // writing into a uniform brick reuses the freed slot uncleared, every byte must still come from the fill + source.setBrickUniform({2, 0, 0}, 5); + source.setVoxel({16, 0, 0}, 6); + for (int32_t z = 0; z < 8; ++z) { + for (int32_t y = 0; y < 8; ++y) { + for (int32_t x = 16; x < 24; ++x) { + assert(source.materialAt({x, y, z}) == (x == 16 && y == 0 && z == 0 ? 6 : 5)); + } + } + } +} diff --git a/tests/voxel/02-solid_tracking.cpp b/tests/voxel/02-solid_tracking.cpp new file mode 100644 index 000000000..633aa1dac --- /dev/null +++ b/tests/voxel/02-solid_tracking.cpp @@ -0,0 +1,154 @@ +#include "test_registry.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +/// The cached counts and the solid brick walk against a recount from the occupancy +void checkTracking(const voxel::Volume& volume) { + uint32_t total = 0; + std::vector solid_slots; + for (uint32_t slot = 0; slot < volume.brickCount(); ++slot) { + const glm::ivec3 brick = volume.brickAtIndex(slot); + const voxel::BrickOccupancy* occupancy = volume.occupancyPointer(brick); + const uint32_t count = occupancy != nullptr ? voxel::popCount(*occupancy) : 0u; + assert(volume.brickSolidCount(brick) == count); + total += count; + if (count != 0) { + solid_slots.push_back(slot); + } + } + assert(volume.solidVoxelCount() == total); + + std::vector walked; + volume.forEachSolidBrick([&](glm::ivec3 brick, uint32_t slot) { + assert(volume.brickAtIndex(slot) == brick); + walked.push_back(slot); + }); + assert(walked == solid_slots); +} + +void checkSameConnectivity(const voxel::Connectivity& a, const voxel::Connectivity& b) { + assert(a.component_count == b.component_count); + assert(a.pieces.size() == b.pieces.size()); + for (size_t i = 0; i < a.pieces.size(); ++i) { + assert(a.pieces[i].brick == b.pieces[i].brick); + assert(a.pieces[i].voxels == b.pieces[i].voxels); + assert(a.pieces[i].component == b.pieces[i].component); + } +} + +} + +TOAST_TEST_NAMED("voxel", "voxel/02-solid_counts_follow_every_write", test_voxel_02_solid_counts_follow_every_write) { + voxel::BrickPool pool(64); + voxel::Volume volume(pool, glm::uvec3 {4, 2, 2}); + checkTracking(volume); + + // single voxels into empty, then out again so the brick frees + volume.setVoxel({1, 1, 1}, 3); + volume.setVoxel({2, 1, 1}, 3); + volume.setVoxel({9, 3, 12}, 5); + checkTracking(volume); + volume.setVoxel({2, 1, 1}, 0); + checkTracking(volume); + + // uniform bricks, written into and collapsed back + volume.setBrickUniform({3, 1, 1}, 7); + volume.setBrickUniform({2, 0, 0}, 4); + checkTracking(volume); + volume.setVoxel({16, 0, 0}, 0); + checkTracking(volume); + volume.setVoxel({16, 0, 0}, 4); + assert(volume.tryCollapseUniform({2, 0, 0})); + checkTracking(volume); + + // a mixed brick from bytes + std::array bytes {}; + for (size_t i = 0; i < bytes.size(); i += 3) { + bytes[i] = 2; + } + assert(volume.setBrickMaterial({0, 1, 0}, bytes)); + checkTracking(volume); + + // partial and whole clears + voxel::BrickOccupancy half {}; + for (uint32_t z = 0; z < 4; ++z) { + half[z] = ~0ull; + } + assert(volume.clearVoxels({3, 1, 1}, half)); + checkTracking(volume); + assert(volume.clearVoxels({0, 1, 0}, voxel::k_full_brick)); + checkTracking(volume); + + // a write the caller does itself + if (auto writable = volume.beginBrickWrite({1, 0, 1})) { + writable->occupancy->slices[2] = 0xFFull; + for (uint32_t x = 0; x < 8; ++x) { + writable->material[(2 * 64) + x] = 6; + } + } + volume.finishBrickWrite({1, 0, 1}, true); + checkTracking(volume); + + // bricks moved between volumes and copied across + voxel::Volume other(pool, glm::uvec3 {4, 2, 2}); + other.adoptBrick({0, 0, 0}, volume.takeBrick({1, 0, 1})); + checkTracking(volume); + checkTracking(other); + assert(other.copyBrickFrom({1, 1, 1}, volume, {3, 1, 1})); + assert(other.copyBrickFrom({2, 1, 1}, volume, {2, 0, 0})); + checkTracking(other); + + // instances, reshare and resize keep the counts of what they copy + voxel::Volume copy = voxel::Volume::instanceOf(volume); + checkTracking(copy); + volume.setVoxel({30, 15, 15}, 9); + copy.reshareFrom(volume); + checkTracking(copy); + voxel::Volume resized = voxel::Volume::adoptResized(volume, {1, 0, 0}, glm::uvec3 {3, 2, 2}); + checkTracking(resized); + checkTracking(volume); + + // the cache gives the same answer as a fresh analysis before and after a carve + voxel::ConnectivityCache cache; + checkSameConnectivity(voxel::analyseConnectivity(volume, &cache), voxel::analyseConnectivity(volume)); + volume.setVoxel({1, 1, 1}, 0); + volume.setVoxel({25, 9, 9}, 0); + 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/tools/crash_reporter/CrashReport.cs b/tools/crash_reporter/CrashReport.cs index 673727f36..a303e0ed0 100644 --- a/tools/crash_reporter/CrashReport.cs +++ b/tools/crash_reporter/CrashReport.cs @@ -163,7 +163,7 @@ public static List Walk(CrashTarget target, ulong contextAddress } Native.SymSetOptions(Native.SymOptions); - if (!Native.SymInitializeW(target.ProcessHandle, null, true)) { + if (!Native.SymInitializeW(target.ProcessHandle, SymbolSearchPath(target), true)) { error = $"SymInitialize failed (error {Marshal.GetLastPInvokeError()})"; return frames; } @@ -208,6 +208,19 @@ public static List Walk(CrashTarget target, ulong contextAddress return frames; } + /// An export ships the game DLL and its PDB next to the exe, which the PDB path baked into the DLL does not point to + /// on another machine; a non-null path replaces the default one, so the environment paths are added back + private static string SymbolSearchPath(CrashTarget target) { + var parts = new List(); + var exe = stackalloc char[1024]; + var length = Native.K32GetModuleFileNameExW(target.ProcessHandle, IntPtr.Zero, exe, 1024); + if (length > 0 && Path.GetDirectoryName(new string(exe, 0, (int)length)) is { } directory) parts.Add(directory); + foreach (var variable in new[] { "_NT_SYMBOL_PATH", "_NT_ALTERNATE_SYMBOL_PATH" }) { + if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } value) parts.Add(value); + } + return string.Join(';', parts); + } + private static StackFrameInfo Describe(IntPtr process, ulong pc, bool exact) { // A return address points after its call so one byte back is inside it var lookup = exact ? pc : pc - 1; diff --git a/tools/crash_reporter/CrashTarget.cs b/tools/crash_reporter/CrashTarget.cs index 9701b052e..e6cf83932 100644 --- a/tools/crash_reporter/CrashTarget.cs +++ b/tools/crash_reporter/CrashTarget.cs @@ -26,9 +26,11 @@ internal sealed class CrashArgs { ulong? pointers = null, message = null; CrashKind? kind = null; string? dumpDir = null; + ulong? handoff = null; for (var i = 0; i < args.Length - 1; ++i) { switch (args[i]) { + case "--handoff": handoff = ParseAddress(args[++i]); break; case "--pid": pid = uint.Parse(args[++i], CultureInfo.InvariantCulture); break; case "--tid": tid = uint.Parse(args[++i], CultureInfo.InvariantCulture); break; case "--pointers": pointers = ParseAddress(args[++i]); break; @@ -38,10 +40,34 @@ internal sealed class CrashArgs { } } + if (pid is not null && handoff is not null) return ReadHandoff(pid.Value, handoff.Value); if (pid is null || tid is null || pointers is null || message is null || kind is null) return null; return new CrashArgs { Pid = pid.Value, Tid = tid.Value, Pointers = pointers.Value, Message = message.Value, Kind = kind.Value, DumpDir = dumpDir }; } + /// The engine starts this process suspended before any crash and resumes it with ReporterHandoff filled in + /// (engine/src/toast/crash_handler.cpp): tid u32, kind i32, pointers u64, message u64, dump directory wchar[260] + private static unsafe CrashArgs? ReadHandoff(uint pid, ulong address) { + const int size = 24 + 260 * sizeof(char); + var process = Native.OpenProcess(Native.ProcessVmRead | Native.ProcessQueryInformation, false, pid); + if (process == IntPtr.Zero) return null; + try { + var block = stackalloc byte[size]; + if (!Native.ReadProcessMemory(process, address, block, size, out _)) return null; + var dumpDir = new string((char*)(block + 24)); + return new CrashArgs { + Pid = pid, + Tid = *(uint*)block, + Kind = (CrashKind)(*(int*)(block + 4)), + Pointers = *(ulong*)(block + 8), + Message = *(ulong*)(block + 16), + DumpDir = dumpDir.Length > 0 ? dumpDir : null, + }; + } finally { + Native.CloseHandle(process); + } + } + private static ulong ParseAddress(string text) { return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? ulong.Parse(text.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) diff --git a/tools/crash_reporter/Native.cs b/tools/crash_reporter/Native.cs index 09a16585f..790ca3b56 100644 --- a/tools/crash_reporter/Native.cs +++ b/tools/crash_reporter/Native.cs @@ -5,6 +5,8 @@ namespace crash_reporter; internal static unsafe class Native { public const uint ProcessAllAccess = 0x001F0FFF; + public const uint ProcessVmRead = 0x0010; + public const uint ProcessQueryInformation = 0x0400; public const uint ThreadAllAccess = 0x001FFFFF; public const uint MachineAmd64 = 0x8664; public const uint AddrModeFlat = 3; @@ -31,6 +33,9 @@ internal static unsafe class Native { [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint K32GetModuleBaseNameW(IntPtr process, IntPtr module, char* name, uint size); + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern uint K32GetModuleFileNameExW(IntPtr process, IntPtr module, char* name, uint size); + [DllImport("ntdll.dll")] public static extern int NtSuspendProcess(IntPtr process); diff --git a/tools/crash_reporter/Program.cs b/tools/crash_reporter/Program.cs index bcadd4395..a1990376e 100644 --- a/tools/crash_reporter/Program.cs +++ b/tools/crash_reporter/Program.cs @@ -9,6 +9,7 @@ public static int Main(string[] args) { if (crash is null) { Console.Error.WriteLine( "usage: crash_reporter --pid --tid --pointers
--message
--kind [--dump-dir ]\n" + + " crash_reporter --pid --handoff
\n" + "Launched by the engine's crash handler (engine/src/toast/crash_handler.cpp), not by hand" ); return 2; diff --git a/tools/player/CMakeLists.txt b/tools/player/CMakeLists.txt index ae3f7da0c..885dbcf30 100644 --- a/tools/player/CMakeLists.txt +++ b/tools/player/CMakeLists.txt @@ -27,10 +27,15 @@ add_custom_target(player ALL -DSRC_DIR=$ -DDST_DIR=${OUTPUT_ROOT}/$/player -P "${CMAKE_SOURCE_DIR}/cmake/link_or_copy_dir.cmake" + # The crash handler looks in crash_reporter/ next to toast_engine.dll; recursive since runtimes/ holds native libs + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${OUTPUT_ROOT}/$/crash_reporter" + "${OUTPUT_ROOT}/$/player/crash_reporter" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "[dotnet] Building ${CSHARP_ASSEMBLY_NAME} (${DOTNET_CONFIG})..." VERBATIM ) add_dependencies(player toast_engine) -add_dependencies(player dummy_game) \ No newline at end of file +add_dependencies(player dummy_game) +add_dependencies(player crash_reporter) \ No newline at end of file diff --git a/tools/player/player.csproj b/tools/player/player.csproj index 8efb70474..282b68408 100644 --- a/tools/player/player.csproj +++ b/tools/player/player.csproj @@ -1,7 +1,8 @@  - Exe + + WinExe net8.0 enable enable diff --git a/tools/player/program.cs b/tools/player/program.cs index 00496fdf7..deb80843b 100644 --- a/tools/player/program.cs +++ b/tools/player/program.cs @@ -1,10 +1,18 @@ using System.Diagnostics; +using System.Runtime.InteropServices; using System.Threading; namespace player; internal class Program { + [DllImport("SDL3", CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.U1)] + private static extern bool SDL_ShowSimpleMessageBox(uint flags, [MarshalAs(UnmanagedType.LPUTF8Str)] string title, + [MarshalAs(UnmanagedType.LPUTF8Str)] string message, IntPtr window); + public static void Main() { + // Read by the mimalloc inside slang-compiler.dll when the engine loads, so it hands freed compile memory back at once + if (Environment.GetEnvironmentVariable("MIMALLOC_PURGE_DELAY") is null) Environment.SetEnvironmentVariable("MIMALLOC_PURGE_DELAY", "0"); var engine = new ToastEngine(); var game = new ApplicationLayer(); @@ -23,7 +31,10 @@ public static void Main() { engine.SetLoadMode(gameMode: true); var databasePath = Path.Combine(basePath, "game.db"); if (!engine.OpenAssetDatabase(databasePath)) { - Console.Error.WriteLine($"Could not load the game's asset database: {databasePath} (or a pak it lists) is missing"); + var message = $"Could not load the game's asset database: {databasePath} (or a pak it lists) is missing"; + Console.Error.WriteLine(message); + // WinExe has no console to show the line above + try { SDL_ShowSimpleMessageBox(0x10 /* SDL_MESSAGEBOX_ERROR */, "Toast Engine", message, IntPtr.Zero); } catch (DllNotFoundException) { } engine.Dispose(); return; } From d799ab931e5647a23b5f82dd8fc0a86dabcf4900 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 14:45:24 +0100 Subject: [PATCH 02/15] game pass season 2 --- engine/src/toast/crash_handler.cpp | 14 +- engine/src/toast/engine.cpp | 2 +- .../toast/renderer/passes/game/game_pass.cpp | 240 +++++++++++++++++- .../toast/renderer/passes/game/game_pass.hpp | 28 ++ .../passes/game/game_view_texture.hpp | 26 ++ .../renderer/passes/render_pass_base.hpp | 2 + .../toast/renderer/vulkan_renderer_record.cpp | 6 + .../src/toast/ui/render/rmlui_renderer_vk.cpp | 77 +++++- .../src/toast/ui/render/rmlui_renderer_vk.h | 14 + tools/crash_reporter/CrashReport.cs | 3 +- tools/crash_reporter/CrashTarget.cs | 3 +- tools/player/CMakeLists.txt | 2 +- tools/player/program.cs | 2 +- 13 files changed, 393 insertions(+), 26 deletions(-) create mode 100644 engine/src/toast/renderer/passes/game/game_view_texture.hpp diff --git a/engine/src/toast/crash_handler.cpp b/engine/src/toast/crash_handler.cpp index 1f99857ab..a4936c60d 100644 --- a/engine/src/toast/crash_handler.cpp +++ b/engine/src/toast/crash_handler.cpp @@ -45,7 +45,7 @@ SharedState g_shared; Kind g_kind = Kind::exception; DWORD g_crashed_thread = 0; -/// Read by the reporter started ahead of time, layout mirrored by CrashArgs.ReadHandoff in tools/crash_reporter +/// Read by the pre-started reporter, mirrors CrashArgs.ReadHandoff struct ReporterHandoff { DWORD tid = 0; int32_t kind = 0; @@ -57,7 +57,7 @@ struct ReporterHandoff { static_assert(offsetof(ReporterHandoff, dump_directory) == 24); ReporterHandoff g_handoff; -/// Started suspended at install, since a crash can hold the heap lock CreateProcess needs +/// Started suspended, since a crash can hold the heap lock CreateProcess needs PROCESS_INFORMATION g_standby {}; std::array g_reporter_path {}; @@ -116,7 +116,6 @@ auto resolveReporter() noexcept -> bool { } std::array candidate {}; - // Dev layout, the player and exports, then older exports that put it flat next to the engine for (const wchar_t* relative : {L"\\..\\..\\crash_reporter\\crash_reporter.exe", L"\\crash_reporter\\crash_reporter.exe", L"\\crash_reporter.exe"}) { if (swprintf_s(candidate.data(), candidate.size(), L"%ls%ls", directory.data(), relative) < 0) { @@ -126,7 +125,7 @@ auto resolveReporter() noexcept -> bool { !fileExists(g_reporter_path.data())) { continue; } - // Old exports copied only the exe and dll, and without its runtimeconfig .NET shows an install dialog instead + // Old exports lack the runtimeconfig, so .NET shows an install dialog std::array config {}; const size_t stem = wcslen(g_reporter_path.data()) - 4; if (swprintf_s(config.data(), config.size(), L"%.*ls.runtimeconfig.json", static_cast(stem), g_reporter_path.data()) > @@ -168,7 +167,7 @@ auto WINAPI launchReporter(LPVOID) -> DWORD { return 0; } -/// The job kills the waiting reporter with this process when nothing crashed +/// Kills the waiting reporter with this process when nothing crashed void startStandbyReporter() noexcept { g_handoff.pointers = reinterpret_cast(&g_shared.pointers); g_handoff.message = reinterpret_cast(g_shared.message.data()); @@ -201,7 +200,6 @@ void startStandbyReporter() noexcept { return; } if (!AssignProcessToJobObject(job, process.hProcess)) { - // Without the job it would outlive this process, so report the old way instead TerminateProcess(process.hProcess, 0); CloseHandle(process.hThread); CloseHandle(process.hProcess); @@ -279,7 +277,7 @@ void report(Kind kind, const EXCEPTION_POINTERS* pointers, const char* message) flushLogs(pointers, message); - // Resuming allocates nothing, so this works while the crash holds the heap lock + // Resuming allocates nothing, so it works under the heap lock if (g_standby.hProcess != nullptr) { g_handoff.tid = g_crashed_thread; g_handoff.kind = static_cast(g_kind); @@ -287,7 +285,7 @@ void report(Kind kind, const EXCEPTION_POINTERS* pointers, const char* message) ResumeThread(g_standby.hThread); WaitForSingleObject(g_standby.hProcess, INFINITE); } else if (HANDLE thread = CreateThread(nullptr, 256 * 1024, launchReporter, nullptr, 0, nullptr)) { - // Fresh thread since after a stack overflow this one has too little stack to start a process + // Fresh thread, a stack overflow leaves this one too little stack WaitForSingleObject(thread, INFINITE); CloseHandle(thread); } diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 3238d9fcc..0d5c7119b 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -409,7 +409,7 @@ Engine::~Engine() noexcept { m->input_system.reset(); m->physics_simulator.reset(); m->audio_system.reset(); - // lua_close runs userdata finalizers, and an Asset proxy releases its asset, which must still exist + // lua_close finalizers release assets, which must still exist m->lua_state.reset(); m->renderer.reset(); m->asset_manager.reset(); diff --git a/engine/src/toast/renderer/passes/game/game_pass.cpp b/engine/src/toast/renderer/passes/game/game_pass.cpp index 6fd935523..926acc6f7 100644 --- a/engine/src/toast/renderer/passes/game/game_pass.cpp +++ b/engine/src/toast/renderer/passes/game/game_pass.cpp @@ -1,5 +1,7 @@ #include "toast/renderer/passes/game/game_pass.hpp" +#include "toast/renderer/core/depth_convention.hpp" +#include "toast/renderer/passes/game/game_view_texture.hpp" #include "toast/renderer/passes/render_pass_base.hpp" #include "toast/renderer/shaders/shader_cache.hpp" #include "toast/renderer/shaders/shader_layout.hpp" @@ -8,6 +10,7 @@ #include #include +#include #include #include #include @@ -15,22 +18,62 @@ namespace renderer { +namespace { + +constexpr vk::Format k_view_color_format = vk::Format::eR8G8B8A8Unorm; + +} + +/// Shared by the view pass, its draw passes and RmlUi textures +struct GameViewTarget { + std::string name; + vk::Extent2D extent; + std::array clear_color {}; + std::optional color; + std::optional color_view; + sync::ImageState color_state; + std::optional depth_format; + std::optional depth; + std::optional depth_view; + sync::ImageState depth_state; + + std::mutex mutex; + std::vector passes; +}; + +namespace { + +std::mutex g_views_mutex; +std::map, std::less<>> g_views; + +} + class GamePass final : public IRenderPass { public: - GamePass(const GamePassDesc& desc, std::shared_ptr shader) + GamePass(const GamePassDesc& desc, std::shared_ptr shader, std::shared_ptr view) : m_desc(desc), m_name(desc.name != nullptr ? desc.name : "Game pass"), - m_shader(std::move(shader)) { + m_shader(std::move(shader)), + m_view(std::move(view)) { m_desc.name = nullptr; m_desc.shader_uri = nullptr; + m_desc.view = nullptr; m_pending.resize(static_cast(m_desc.instance_stride) * m_desc.max_instances); } [[nodiscard]] auto stage() const -> RenderStage override { + if (m_view) { + return RenderStage::view; + } return m_desc.stage == GamePassStage::overlay ? RenderStage::overlay : RenderStage::world; } + [[nodiscard]] + auto view() const -> const std::shared_ptr& { + return m_view; + } + [[nodiscard]] auto name() const -> std::string_view override { return m_name; @@ -56,6 +99,13 @@ class GamePass final : public IRenderPass { void record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) override { (void)image_index; + // The view records it inside its own scope + if (!m_view) { + draw(cmd, frame_index); + } + } + + void draw(vk::CommandBuffer cmd, uint32_t frame_index) { if (!m_pipeline.isReady() || frame_index >= m_sets.size()) { return; } @@ -95,22 +145,28 @@ class GamePass final : public IRenderPass { return; } - const bool world = m_desc.stage == GamePassStage::world; + const bool world = !m_view && m_desc.stage == GamePassStage::world; VulkanPipeline::Config config; config.debug_name = m_name; - config.color_format = world ? renderer->getSceneColorFormat() : renderer->getOutputTarget().getColorFormat(); + if (m_view) { + config.color_format = k_view_color_format; + config.depth_format = m_view->depth_format; + config.extent = m_view->extent; + } else { + config.color_format = world ? renderer->getSceneColorFormat() : renderer->getOutputTarget().getColorFormat(); + config.depth_format = VulkanRenderer::selectDepthFormat(core); + config.extent = renderer->renderExtent(); + } if (world) { config.extra_color_formats = worldStageExtraColorFormats(); config.write_extra_color = m_desc.reactive && m_desc.blend != GamePassBlend::opaque; config.extra_blend_mask = config.write_extra_color ? 0b111u : 0u; } - config.depth_format = VulkanRenderer::selectDepthFormat(core); - config.extent = renderer->renderExtent(); config.shader_spirv = m_shader->spirv; config.pipeline_layout = *m_layout.getPipelineLayout(); config.cull_mode = vk::CullModeFlagBits::eNone; - config.depth_test = m_desc.depth_test; - config.depth_write = m_desc.depth_write; + config.depth_test = m_desc.depth_test && config.depth_format.has_value(); + config.depth_write = m_desc.depth_write && config.depth_format.has_value(); config.blend_enable = m_desc.blend != GamePassBlend::opaque; config.blend_preset = VulkanPipeline::BlendPreset::none; if (m_desc.blend == GamePassBlend::additive) { @@ -155,6 +211,7 @@ class GamePass final : public IRenderPass { GamePassDesc m_desc; std::string m_name; std::shared_ptr m_shader; + std::shared_ptr m_view; bool m_built = false; ShaderLayout m_layout; @@ -167,6 +224,162 @@ class GamePass final : public IRenderPass { uint32_t m_count = 0; }; +class GameView final : public IRenderPass { +public: + explicit GameView(std::shared_ptr target) : m_target(std::move(target)) { } + + [[nodiscard]] + auto stage() const -> RenderStage override { + return RenderStage::view; + } + + [[nodiscard]] + auto name() const -> std::string_view override { + return m_target->name; + } + + [[nodiscard]] + auto target() const -> const std::shared_ptr& { + return m_target; + } + + void record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) override { + (void)image_index; + auto& target = *m_target; + + sync::BarrierBatch begin; + begin.image(target.color_state, sync::Usage::color_attachment); + if (target.depth) { + begin.image(target.depth_state, sync::Usage::depth_attachment); + } + begin.flush(cmd); + + vk::RenderingAttachmentInfo color {}; + color.imageView = **target.color_view; + color.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + color.loadOp = vk::AttachmentLoadOp::eClear; + color.storeOp = vk::AttachmentStoreOp::eStore; + color.clearValue = vk::ClearValue(vk::ClearColorValue(target.clear_color)); + + vk::RenderingAttachmentInfo depth {}; + if (target.depth) { + depth.imageView = **target.depth_view; + depth.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal; + depth.loadOp = vk::AttachmentLoadOp::eClear; + depth.storeOp = vk::AttachmentStoreOp::eDontCare; + depth.clearValue = vk::ClearValue(vk::ClearDepthStencilValue(depth::k_far, 0)); + } + + vk::RenderingInfo info {}; + info.renderArea = vk::Rect2D({0, 0}, target.extent); + info.layerCount = 1; + info.colorAttachmentCount = 1; + info.pColorAttachments = &color; + info.pDepthAttachment = target.depth ? &depth : nullptr; + + cmd.beginRendering(info); + cmd.setViewport( + 0, vk::Viewport(0.0f, 0.0f, static_cast(target.extent.width), static_cast(target.extent.height), 0.0f, 1.0f) + ); + cmd.setScissor(0, info.renderArea); + { + const std::lock_guard lock(target.mutex); + for (GamePass* pass : target.passes) { + if (pass->isEnabled()) { + pass->draw(cmd, frame_index); + } + } + } + cmd.endRendering(); + + sync::transition(cmd, target.color_state, sync::Usage::shader_sampled); + } + +private: + std::shared_ptr m_target; +}; + +auto createGameView(const GameViewDesc& desc) -> GameView* { + if (VulkanRenderer::instance == nullptr || desc.name == nullptr || desc.width == 0 || desc.height == 0) { + return nullptr; + } + const std::string_view name = desc.name; + if (name.empty() || name.contains('/')) { + TOAST_ERROR("Render", "Game view name '{}' must be non empty and without '/'", name); + return nullptr; + } + + const auto& core = VulkanRenderer::instance->getCore(); + auto target = std::make_shared(); + target->name = name; + target->extent = vk::Extent2D {desc.width, desc.height}; + std::ranges::copy(desc.clear_color, target->clear_color.begin()); + + vma::AllocationCreateInfo allocation_ci {}; + allocation_ci.usage = vma::MemoryUsage::eAutoPreferDevice; + + target->color.emplace( + core.getAllocator().createImage(colorTargetImageInfo(target->extent, k_view_color_format), allocation_ci) + ); + setDebugName(core, **target->color, std::format("GameView {} color", name)); + vk::ImageViewCreateInfo view_ci {}; + view_ci.image = **target->color; + view_ci.viewType = vk::ImageViewType::e2D; + view_ci.format = k_view_color_format; + view_ci.subresourceRange = colorSubresourceRange(); + target->color_view.emplace(core.getDevice(), view_ci); + target->color_state.reset(**target->color, colorSubresourceRange()); + + if (desc.depth) { + const vk::Format format = VulkanRenderer::selectDepthFormat(core); + auto image_ci = colorTargetImageInfo(target->extent, format); + image_ci.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eSampled; + target->depth.emplace(core.getAllocator().createImage(image_ci, allocation_ci)); + setDebugName(core, **target->depth, std::format("GameView {} depth", name)); + const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1}; + view_ci.image = **target->depth; + view_ci.format = format; + view_ci.subresourceRange = range; + target->depth_view.emplace(core.getDevice(), view_ci); + target->depth_state.reset(**target->depth, range); + target->depth_format = format; + } + + const std::lock_guard lock(g_views_mutex); + if (g_views.contains(name)) { + TOAST_ERROR("Render", "Game view '{}' already exists", name); + return nullptr; + } + auto pass = std::make_unique(target); + GameView* raw = pass.get(); + VulkanRenderer::instance->addRenderPass(std::move(pass)); + g_views.emplace(target->name, target); + return raw; +} + +void destroyGameView(GameView* view) { + if (view == nullptr || VulkanRenderer::instance == nullptr) { + return; + } + { + const std::lock_guard lock(g_views_mutex); + const auto it = g_views.find(view->target()->name); + if (it != g_views.end() && it->second == view->target()) { + g_views.erase(it); + } + } + VulkanRenderer::instance->removeRenderPass(view); +} + +auto findGameViewTexture(std::string_view name) -> std::optional { + const std::lock_guard lock(g_views_mutex); + const auto it = g_views.find(name); + if (it == g_views.end()) { + return std::nullopt; + } + return GameViewTexture {.view = **it->second->color_view, .extent = it->second->extent, .keepalive = it->second}; +} + auto createGamePass(const GamePassDesc& desc) -> GamePass* { if (VulkanRenderer::instance == nullptr || desc.shader_uri == nullptr || desc.instance_stride == 0) { return nullptr; @@ -177,9 +390,14 @@ auto createGamePass(const GamePassDesc& desc) -> GamePass* { TOAST_ERROR("Render", "Game pass shader {} unavailable", desc.shader_uri); return nullptr; } - auto pass = std::make_unique(desc, std::move(shader)); + auto view = desc.view != nullptr ? desc.view->target() : nullptr; + auto pass = std::make_unique(desc, std::move(shader), view); GamePass* raw = pass.get(); VulkanRenderer::instance->addRenderPass(std::move(pass)); + if (view) { + const std::lock_guard lock(view->mutex); + view->passes.push_back(raw); + } return raw; } @@ -191,6 +409,10 @@ void setGamePassInstances(GamePass* pass, const void* data, uint32_t count) { void destroyGamePass(GamePass* pass) { if (pass != nullptr && VulkanRenderer::instance != nullptr) { + if (const auto& view = pass->view()) { + const std::lock_guard lock(view->mutex); + std::erase(view->passes, pass); + } VulkanRenderer::instance->removeRenderPass(pass); } } diff --git a/engine/src/toast/renderer/passes/game/game_pass.hpp b/engine/src/toast/renderer/passes/game/game_pass.hpp index e5a9c1a0b..30830f5be 100644 --- a/engine/src/toast/renderer/passes/game/game_pass.hpp +++ b/engine/src/toast/renderer/passes/game/game_pass.hpp @@ -35,6 +35,14 @@ * // end(), also before the game module unloads * renderer::destroyGamePass(std::exchange(m_pass, nullptr)); * @endcode + * + * To draw into a texture, create a view and point passes at it. RmlUi shows it with + * @code + * m_view = renderer::createGameView({.name = "Minimap", .width = 256, .height = 256, .depth = true}); + * m_pass = renderer::createGamePass({.name = "Blips", .shader_uri = "...", .view = m_view, .instance_stride = 16}); + * renderer::destroyGamePass(std::exchange(m_pass, nullptr)); + * renderer::destroyGameView(std::exchange(m_view, nullptr)); + * @endcode */ namespace renderer { @@ -54,9 +62,29 @@ enum class GamePassBlend : uint8_t { additive, }; +class GameView; + +/// RGBA8 unorm with premultiplied alpha +struct GameViewDesc { + /// Unique and without / + const char* name = nullptr; + uint32_t width = 256; + uint32_t height = 256; + float clear_color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + /// Own depth attachment cleared every frame + bool depth = false; +}; + +auto TOAST_API createGameView(const GameViewDesc& desc) -> GameView*; + +/// Passes still pointing at the view stop drawing +void TOAST_API destroyGameView(GameView* view); + struct GamePassDesc { const char* name = "Game pass"; const char* shader_uri = nullptr; + /// Draws into this view instead of the scene, ignoring stage and reactive + GameView* view = nullptr; GamePassStage stage = GamePassStage::world; GamePassBlend blend = GamePassBlend::additive; bool depth_test = true; diff --git a/engine/src/toast/renderer/passes/game/game_view_texture.hpp b/engine/src/toast/renderer/passes/game/game_view_texture.hpp new file mode 100644 index 000000000..dde5d4f92 --- /dev/null +++ b/engine/src/toast/renderer/passes/game/game_view_texture.hpp @@ -0,0 +1,26 @@ +/// @file game_view_texture.hpp +/// @author dario +/// @date 23/11/2026 + +#pragma once + +#include "toast/renderer/core/vulkan_common.hpp" + +#include +#include +#include + +namespace renderer { + +/// In eShaderReadOnlyOptimal once the view pass ran +struct GameViewTexture { + vk::ImageView view; + vk::Extent2D extent; + /// Keeps the image alive + std::shared_ptr keepalive; +}; + +/// Any thread +auto findGameViewTexture(std::string_view name) -> std::optional; + +} diff --git a/engine/src/toast/renderer/passes/render_pass_base.hpp b/engine/src/toast/renderer/passes/render_pass_base.hpp index b56db3b48..bb021b6d5 100644 --- a/engine/src/toast/renderer/passes/render_pass_base.hpp +++ b/engine/src/toast/renderer/passes/render_pass_base.hpp @@ -14,6 +14,8 @@ enum class RenderStage : uint8_t { overlay, /// Recorded by VulkanRenderer in its own scope ahead of the world scope voxel_gbuffer, + /// Runs outside any rendering scope before recordPre + view, }; class IRenderPass { diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 46cc0a2de..82f1cbc7e 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -963,6 +963,12 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex { const GpuScope offscreen_scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, "Off-screen"); std::lock_guard lock(m_pass_mutex); + // Game views first since UIPass::recordPre executes the UI that samples them + for (auto& pass : m_render_passes) { + if (pass->isEnabled() && pass->stage() == RenderStage::view) { + pass->record(*frame.command_buffer, m_current_frame, image_index); + } + } for (auto& pass : m_render_passes) { const GpuScope scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, pass->name()); pass->recordPre(*frame.command_buffer, m_current_frame, image_index); diff --git a/engine/src/toast/ui/render/rmlui_renderer_vk.cpp b/engine/src/toast/ui/render/rmlui_renderer_vk.cpp index d1f16864b..d3ca93b02 100644 --- a/engine/src/toast/ui/render/rmlui_renderer_vk.cpp +++ b/engine/src/toast/ui/render/rmlui_renderer_vk.cpp @@ -4,6 +4,7 @@ #include "../tga_decode.hpp" #include "shaders_compiled_spv.h" +#include "toast/renderer/passes/game/game_view_texture.hpp" #include #include @@ -166,7 +167,11 @@ void RenderInterface_VK::RenderGeometry( } VkDescriptorImageInfo info_descriptor_image = {}; - if (p_texture && p_texture->m_p_vk_descriptor_set == nullptr) { + if (p_texture && !p_texture->m_view_name.empty()) { + if (!BindViewTexture(*p_texture)) { + return; + } + } else if (p_texture && p_texture->m_p_vk_descriptor_set == nullptr) { VkDescriptorSet p_texture_set = nullptr; if (!m_manager_descriptors.Alloc_Descriptor(m_p_device, &m_p_descriptor_set_layout_texture, &p_texture_set)) { Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to allocate an RmlUi texture descriptor set."); @@ -222,7 +227,8 @@ void RenderInterface_VK::RenderGeometry( VkDescriptorSet p_texture_descriptor_set = nullptr; if (p_texture) { - p_texture_descriptor_set = p_texture->m_p_vk_descriptor_set; + p_texture_descriptor_set = + p_texture->m_view_binding ? p_texture->m_view_binding->m_p_vk_descriptor_set : p_texture->m_p_vk_descriptor_set; } VkDescriptorSet p_sets[] = {p_current_descriptor_set, p_texture_descriptor_set}; @@ -328,6 +334,11 @@ void RenderInterface_VK::SetScissorRegion(Rml::Rectanglei region) { } Rml::TextureHandle RenderInterface_VK::LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) { + constexpr std::string_view view_scheme = "view://"; + if (source.starts_with(view_scheme)) { + return LoadViewTexture(texture_dimensions, source.substr(view_scheme.size())); + } + Rml::FileInterface* file_interface = Rml::GetFileInterface(); Rml::FileHandle file_handle = file_interface->Open(source); if (!file_handle) { @@ -370,6 +381,68 @@ Rml::TextureHandle RenderInterface_VK::LoadTexture(Rml::Vector2i& texture_dimens return GenerateTexture({pixels, pixel_count * 4}, texture_dimensions); } +// toast-engine adaptation: view:// samples a renderer::GameView, the handle survives a missing or recreated view +Rml::TextureHandle RenderInterface_VK::LoadViewTexture(Rml::Vector2i& texture_dimensions, const Rml::String& view_name) { + const auto view = renderer::findGameViewTexture(view_name); + if (view) { + texture_dimensions = {int(view->extent.width), int(view->extent.height)}; + } else { + Rml::Log::Message(Rml::Log::LT_WARNING, "Game view '%s' does not exist yet, it draws once created.", view_name.c_str()); + texture_dimensions = {1, 1}; + } + + auto texture = std::make_unique(); + texture->m_view_name = view_name; + auto owner = std::shared_ptr(texture.release(), [this](texture_data_t* resource) { + Destroy_Texture(*resource); + delete resource; + }); + texture_data_t* handle = owner.get(); + m_live_resources.emplace(handle, std::move(owner)); + return reinterpret_cast(handle); +} + +bool RenderInterface_VK::BindViewTexture(texture_data_t& texture) { + auto view = renderer::findGameViewTexture(texture.m_view_name); + if (!view) { + return false; + } + + if (!texture.m_view_binding || texture.m_view_binding->m_keepalive != view->keepalive) { + VkDescriptorSet p_set = nullptr; + if (!m_manager_descriptors.Alloc_Descriptor(m_p_device, &m_p_descriptor_set_layout_texture, &p_set)) { + Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to allocate an RmlUi view texture descriptor set."); + return false; + } + + VkDescriptorImageInfo info_image = {}; + info_image.imageView = static_cast(view->view); + info_image.sampler = m_p_sampler_linear; + info_image.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + VkWriteDescriptorSet info_write = {}; + info_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + info_write.dstSet = p_set; + info_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + info_write.dstBinding = 2; + info_write.pImageInfo = &info_image; + info_write.descriptorCount = 1; + vkUpdateDescriptorSets(m_p_device, 1, &info_write, 0, nullptr); + + // The old binding stays alive in the command buffers still using it + texture.m_view_binding = std::shared_ptr( + new view_binding_t {.m_p_vk_descriptor_set = p_set, .m_keepalive = std::move(view->keepalive)}, + [this](view_binding_t* binding) { + m_manager_descriptors.Free_Descriptors(m_p_device, &binding->m_p_vk_descriptor_set); + delete binding; + } + ); + } + + m_command_buffer_ring.AddCurrentSlotResource(texture.m_view_binding); + return true; +} + Rml::TextureHandle RenderInterface_VK::GenerateTexture(Rml::Span source_data, Rml::Vector2i source_dimensions) { RMLUI_ASSERT(source_data.data() && source_data.size() == size_t(source_dimensions.x * source_dimensions.y * 4)); Rml::String source_name = "generated-texture"; diff --git a/engine/src/toast/ui/render/rmlui_renderer_vk.h b/engine/src/toast/ui/render/rmlui_renderer_vk.h index 90b451425..ccc05bf44 100644 --- a/engine/src/toast/ui/render/rmlui_renderer_vk.h +++ b/engine/src/toast/ui/render/rmlui_renderer_vk.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -195,12 +196,22 @@ class RenderInterface_VK : public Rml::RenderInterface { Rml::Vector2f m_translate; }; + /// Descriptor set of a view:// texture, retained by the command buffers that bind it + struct view_binding_t { + VkDescriptorSet m_p_vk_descriptor_set = nullptr; + std::shared_ptr m_keepalive; + }; + struct texture_data_t { VkImage m_p_vk_image; VkImageView m_p_vk_image_view; VkSampler m_p_vk_sampler; VkDescriptorSet m_p_vk_descriptor_set; VmaAllocation m_p_vma_allocation; + + /// Set for view:// textures, looked up on every draw + std::string m_view_name; + std::shared_ptr m_view_binding; }; struct geometry_handle_t { @@ -665,6 +676,9 @@ class RenderInterface_VK : public Rml::RenderInterface { void DestroyResource_StagingBuffer(const buffer_data_t& data) noexcept; void Destroy_Texture(const texture_data_t& p_texture) noexcept; + Rml::TextureHandle LoadViewTexture(Rml::Vector2i& texture_dimensions, const Rml::String& view_name); + /// False while the view does not exist, the geometry is then skipped + bool BindViewTexture(texture_data_t& texture); bool RetainResource(const void* resource); void ReleaseResource(const void* resource); diff --git a/tools/crash_reporter/CrashReport.cs b/tools/crash_reporter/CrashReport.cs index a303e0ed0..17cd02c73 100644 --- a/tools/crash_reporter/CrashReport.cs +++ b/tools/crash_reporter/CrashReport.cs @@ -208,8 +208,7 @@ public static List Walk(CrashTarget target, ulong contextAddress return frames; } - /// An export ships the game DLL and its PDB next to the exe, which the PDB path baked into the DLL does not point to - /// on another machine; a non-null path replaces the default one, so the environment paths are added back + /// Exports ship the PDB next to the exe; a non-null path replaces the default, so the environment paths are added back private static string SymbolSearchPath(CrashTarget target) { var parts = new List(); var exe = stackalloc char[1024]; diff --git a/tools/crash_reporter/CrashTarget.cs b/tools/crash_reporter/CrashTarget.cs index e6cf83932..6fea5cde7 100644 --- a/tools/crash_reporter/CrashTarget.cs +++ b/tools/crash_reporter/CrashTarget.cs @@ -45,8 +45,7 @@ internal sealed class CrashArgs { return new CrashArgs { Pid = pid.Value, Tid = tid.Value, Pointers = pointers.Value, Message = message.Value, Kind = kind.Value, DumpDir = dumpDir }; } - /// The engine starts this process suspended before any crash and resumes it with ReporterHandoff filled in - /// (engine/src/toast/crash_handler.cpp): tid u32, kind i32, pointers u64, message u64, dump directory wchar[260] + /// Resumed by the engine with ReporterHandoff filled in (crash_handler.cpp) private static unsafe CrashArgs? ReadHandoff(uint pid, ulong address) { const int size = 24 + 260 * sizeof(char); var process = Native.OpenProcess(Native.ProcessVmRead | Native.ProcessQueryInformation, false, pid); diff --git a/tools/player/CMakeLists.txt b/tools/player/CMakeLists.txt index 885dbcf30..a67700bab 100644 --- a/tools/player/CMakeLists.txt +++ b/tools/player/CMakeLists.txt @@ -27,7 +27,7 @@ add_custom_target(player ALL -DSRC_DIR=$ -DDST_DIR=${OUTPUT_ROOT}/$/player -P "${CMAKE_SOURCE_DIR}/cmake/link_or_copy_dir.cmake" - # The crash handler looks in crash_reporter/ next to toast_engine.dll; recursive since runtimes/ holds native libs + # The crash handler looks for crash_reporter/ next to toast_engine.dll COMMAND ${CMAKE_COMMAND} -E copy_directory "${OUTPUT_ROOT}/$/crash_reporter" "${OUTPUT_ROOT}/$/player/crash_reporter" diff --git a/tools/player/program.cs b/tools/player/program.cs index deb80843b..55fac9590 100644 --- a/tools/player/program.cs +++ b/tools/player/program.cs @@ -11,7 +11,7 @@ private static extern bool SDL_ShowSimpleMessageBox(uint flags, [MarshalAs(Unman [MarshalAs(UnmanagedType.LPUTF8Str)] string message, IntPtr window); public static void Main() { - // Read by the mimalloc inside slang-compiler.dll when the engine loads, so it hands freed compile memory back at once + // Makes slang's mimalloc return freed compile memory at once if (Environment.GetEnvironmentVariable("MIMALLOC_PURGE_DELAY") is null) Environment.SetEnvironmentVariable("MIMALLOC_PURGE_DELAY", "0"); var engine = new ToastEngine(); var game = new ApplicationLayer(); From faa7f3d524155854cf8459edee7d0969c360facb 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 16:39:32 +0100 Subject: [PATCH 03/15] finished post process data driven --- .../Assets/Types/PostProcessProfileAsset.cs | 29 + .../assets/schemas/post_process.schema.json | 509 ++++++++++++++++++ .../schemas/post_process.schema.json.meta | 4 + engine/src/toast/assets/asset_registry.cpp | 5 + .../renderer/settings/post_process_params.cpp | 389 +++++++++++++ .../renderer/settings/post_process_params.hpp | 119 ++++ .../settings/post_process_profile.cpp | 11 + .../settings/post_process_profile.hpp | 35 ++ .../settings/post_process_settings.cpp | 94 ---- .../settings/post_process_settings.hpp | 29 +- engine/src/toast/renderer/vulkan_renderer.hpp | 27 +- .../toast/renderer/vulkan_renderer_scene.cpp | 42 +- .../src/toast/world/post_process_volume.cpp | 133 +++-- .../src/toast/world/post_process_volume.hpp | 174 ++---- tests/postprocess/01-blend.cpp | 107 ++-- 15 files changed, 1332 insertions(+), 375 deletions(-) create mode 100644 editor/Assets/Types/PostProcessProfileAsset.cs create mode 100644 engine/assets/schemas/post_process.schema.json create mode 100644 engine/assets/schemas/post_process.schema.json.meta create mode 100644 engine/src/toast/renderer/settings/post_process_params.cpp create mode 100644 engine/src/toast/renderer/settings/post_process_params.hpp create mode 100644 engine/src/toast/renderer/settings/post_process_profile.cpp create mode 100644 engine/src/toast/renderer/settings/post_process_profile.hpp delete mode 100644 engine/src/toast/renderer/settings/post_process_settings.cpp diff --git a/editor/Assets/Types/PostProcessProfileAsset.cs b/editor/Assets/Types/PostProcessProfileAsset.cs new file mode 100644 index 000000000..b1b95363a --- /dev/null +++ b/editor/Assets/Types/PostProcessProfileAsset.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Lucide.Avalonia; + +namespace editor.Assets.Types; + +public class PostProcessProfileAsset : BaseAsset { + public override string Type => "post_process_profile"; + public override string Extension => ".tpp"; + public override string DisplayName => "Post Process Profile"; + public override string ChipText => "POST"; + public override string ChipColor => "Purple"; + public override LucideIconKind Icon => LucideIconKind.Sun; + public override bool CanBeCreated => true; + public override string Category => "Rendering"; + public override bool HasThumbnail => false; + public override bool CanBeEdited => true; + public override string EditorTool => "GenericEditor"; + public override string SchemaPath => "core://schemas/post_process.schema.json"; + + public override IReadOnlyList CppTypeNames => ["PostProcessProfile"]; + + public override Task CreateAsync(string path) { + const string schemaUid = "PostProcSc4"; + File.WriteAllText(path, $"# Toast Post Process Profile\nschema = \"{schemaUid}\"\n"); + return Task.CompletedTask; + } +} diff --git a/engine/assets/schemas/post_process.schema.json b/engine/assets/schemas/post_process.schema.json new file mode 100644 index 000000000..de01a30a4 --- /dev/null +++ b/engine/assets/schemas/post_process.schema.json @@ -0,0 +1,509 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "core://schemas/post_process.schema.json", + "title": "Post Process Profile (.tpp)", + "type": "object", + "properties": { + "bloom": { + "x-toast-type": "bloom" + }, + "lens_flare": { + "x-toast-type": "lens_flare" + }, + "tonemap": { + "x-toast-type": "tonemap" + }, + "fxaa": { + "x-toast-type": "fxaa" + }, + "ssr": { + "x-toast-type": "ssr" + }, + "ssao": { + "x-toast-type": "ssao" + }, + "fog": { + "x-toast-type": "fog" + } + }, + "definitions": { + "bloom": { + "type": "object", + "properties": { + "threshold": { + "type": "number", + "x-toast-type": "float", + "description": "Luminance above which pixels bloom", + "default": 1.0, + "minimum": 0, + "maximum": 10 + }, + "knee": { + "type": "number", + "x-toast-type": "float", + "description": "Softness of the threshold edge", + "default": 0.5, + "minimum": 0, + "maximum": 1 + }, + "filter_radius": { + "type": "number", + "x-toast-type": "float", + "description": "Blur radius of the upsample chain", + "default": 1.0, + "minimum": 0, + "maximum": 4 + }, + "strength": { + "type": "number", + "x-toast-type": "float", + "description": "Share of the bloom added to the image", + "default": 0.05, + "minimum": 0, + "maximum": 1 + } + } + }, + "lens_flare": { + "type": "object", + "properties": { + "intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Overall flare strength", + "default": 0.009, + "minimum": 0, + "maximum": 2 + }, + "threshold": { + "type": "number", + "x-toast-type": "float", + "description": "Luminance a pixel needs to flare", + "default": 1.0, + "minimum": 0, + "maximum": 20 + }, + "threshold_range": { + "type": "number", + "x-toast-type": "float", + "description": "Width of the threshold ramp", + "default": 1.0, + "minimum": 0.01, + "maximum": 10 + }, + "ghost_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Ghost copies strength", + "default": 2.0, + "minimum": 0, + "maximum": 4 + }, + "chroma_shift": { + "type": "number", + "x-toast-type": "float", + "description": "Colour split between ghosts", + "default": 0.015, + "minimum": 0, + "maximum": 0.1 + }, + "halo_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Halo ring strength", + "default": 1.0, + "minimum": 0, + "maximum": 4 + }, + "halo_width": { + "type": "number", + "x-toast-type": "float", + "description": "Halo radius", + "default": 0.41, + "minimum": 0, + "maximum": 2 + }, + "halo_mask": { + "type": "number", + "x-toast-type": "float", + "description": "Where the halo starts to fade", + "default": 0.124, + "minimum": 0, + "maximum": 1 + }, + "halo_compression": { + "type": "number", + "x-toast-type": "float", + "description": "Halo fisheye", + "default": 1.0, + "minimum": 0.05, + "maximum": 4 + }, + "glare_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Glare strength", + "default": 0.2, + "minimum": 0, + "maximum": 2 + }, + "glare_divider": { + "type": "number", + "x-toast-type": "float", + "description": "Glare falloff divider", + "default": 162.0, + "minimum": 1, + "maximum": 200 + }, + "anamorphic_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Anamorphic streak strength", + "default": 1.0, + "minimum": 0, + "maximum": 4 + }, + "anamorphic_tint": { + "type": "number", + "x-toast-type": "float", + "description": "Share of the streak pulled toward blue", + "default": 0.6, + "minimum": 0, + "maximum": 1 + }, + "dirt_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Lens dirt strength", + "default": 0.0, + "minimum": 0, + "maximum": 2 + }, + "halo_thickness": { + "type": "number", + "x-toast-type": "float", + "description": "Spread of the ring along its radius", + "default": 0.09, + "minimum": 0, + "maximum": 4 + }, + "halo_dispersion": { + "type": "number", + "x-toast-type": "float", + "description": "Colour split across the halo", + "default": 0.056, + "minimum": 0, + "maximum": 0.1 + }, + "halo_tint": { + "type": "array", + "x-toast-type": "color3", + "description": "Halo colour", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "dirt_texture": { + "type": "string", + "x-toast-type": "asset", + "description": "Lens dirt texture", + "x-toast-asset-type": "texture" + } + } + }, + "tonemap": { + "type": "object", + "properties": { + "exposure": { + "type": "number", + "x-toast-type": "float", + "description": "Exposure multiplier, a compensation when auto exposure is on", + "default": 1.0, + "minimum": 0, + "maximum": 8 + }, + "mode": { + "type": "string", + "x-toast-type": "enum", + "description": "Tonemap curve, switches at the halfway point of a blend", + "enum": [ + "Reinhard", + "ACES", + "GT7" + ], + "default": "GT7" + }, + "gt_contrast_dip": { + "type": "number", + "x-toast-type": "float", + "description": "GT7 toe exponent under the grey point", + "default": 1.28, + "minimum": 1, + "maximum": 2 + }, + "chromatic_aberration": { + "type": "number", + "x-toast-type": "float", + "description": "Colour fringing toward the edges", + "default": 0.0, + "minimum": 0, + "maximum": 0.05 + }, + "gamma": { + "type": "number", + "x-toast-type": "float", + "description": "Output gamma", + "default": 2.2, + "minimum": 1, + "maximum": 3 + }, + "contrast": { + "type": "number", + "x-toast-type": "float", + "description": "Contrast", + "default": 1.0, + "minimum": 0, + "maximum": 2 + }, + "saturation": { + "type": "number", + "x-toast-type": "float", + "description": "Saturation", + "default": 1.0, + "minimum": 0, + "maximum": 2 + }, + "vignette": { + "type": "number", + "x-toast-type": "float", + "description": "Corner darkening", + "default": 0.0, + "minimum": 0, + "maximum": 1 + }, + "grain": { + "type": "number", + "x-toast-type": "float", + "description": "Film grain", + "default": 0.0, + "minimum": 0, + "maximum": 1 + }, + "auto_exposure": { + "type": "boolean", + "x-toast-type": "bool", + "description": "Meter the scene and adapt exposure", + "default": true + }, + "auto_exposure_min": { + "type": "number", + "x-toast-type": "float", + "description": "log2 of the dimmest average scene luminance the meter may settle on", + "default": -5.0, + "minimum": -16, + "maximum": 16 + }, + "auto_exposure_max": { + "type": "number", + "x-toast-type": "float", + "description": "log2 of the brightest average scene luminance the meter may settle on", + "default": 8.0, + "minimum": -16, + "maximum": 16 + }, + "adapt_speed_up": { + "type": "number", + "x-toast-type": "float", + "description": "Per second toward a brighter scene", + "default": 3.0, + "minimum": 0, + "maximum": 20 + }, + "adapt_speed_down": { + "type": "number", + "x-toast-type": "float", + "description": "Per second toward a darker scene", + "default": 1.0, + "minimum": 0, + "maximum": 20 + } + } + }, + "fxaa": { + "type": "object", + "properties": { + "contrast_threshold": { + "type": "number", + "x-toast-type": "float", + "description": "Minimum local contrast to smooth", + "default": 0.0312, + "minimum": 0, + "maximum": 0.2 + }, + "relative_threshold": { + "type": "number", + "x-toast-type": "float", + "description": "Contrast relative to the brightest neighbour", + "default": 0.125, + "minimum": 0, + "maximum": 0.5 + }, + "subpixel_blending": { + "type": "number", + "x-toast-type": "float", + "description": "Sub-pixel smoothing", + "default": 0.75, + "minimum": 0, + "maximum": 1 + } + } + }, + "ssr": { + "type": "object", + "properties": { + "intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Reflection strength", + "default": 1.0, + "minimum": 0, + "maximum": 2 + }, + "max_roughness": { + "type": "number", + "x-toast-type": "float", + "description": "Roughest surface that still reflects", + "default": 0.6, + "minimum": 0, + "maximum": 1 + }, + "thickness": { + "type": "number", + "x-toast-type": "float", + "description": "Surface thickness in meters", + "default": 0.5, + "minimum": 0.01, + "maximum": 5 + }, + "stride": { + "type": "number", + "x-toast-type": "float", + "description": "March step in meters", + "default": 0.15, + "minimum": 0.01, + "maximum": 1 + }, + "max_steps": { + "type": "integer", + "x-toast-type": "int", + "description": "Maximum march steps", + "default": 48, + "minimum": 1, + "maximum": 256 + } + } + }, + "ssao": { + "type": "object", + "properties": { + "radius": { + "type": "number", + "x-toast-type": "float", + "description": "Sampling radius in meters", + "default": 0.5, + "minimum": 0.01, + "maximum": 10 + }, + "strength": { + "type": "number", + "x-toast-type": "float", + "description": "Occlusion strength", + "default": 1.0, + "minimum": 0, + "maximum": 4 + }, + "range_cutoff": { + "type": "number", + "x-toast-type": "float", + "description": "Occluders further than this are ignored, in meters", + "default": 1.0, + "minimum": 0.01, + "maximum": 10 + }, + "sample_count": { + "type": "integer", + "x-toast-type": "int", + "description": "Samples per pixel", + "default": 16, + "minimum": 1, + "maximum": 64 + } + } + }, + "fog": { + "type": "object", + "properties": { + "density": { + "type": "number", + "x-toast-type": "float", + "description": "Extinction per meter at the base height, 0 turns volumetrics off", + "default": 0.005, + "minimum": 0, + "maximum": 1 + }, + "height": { + "type": "number", + "x-toast-type": "float", + "description": "Base height in meters", + "default": 0.0, + "minimum": -1000, + "maximum": 1000 + }, + "height_falloff": { + "type": "number", + "x-toast-type": "float", + "description": "Per meter above the base height, 0 is uniform", + "default": 0.0, + "minimum": 0, + "maximum": 2 + }, + "albedo": { + "type": "array", + "x-toast-type": "color3", + "description": "Scattering colour", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "anisotropy": { + "type": "number", + "x-toast-type": "float", + "description": "Henyey Greenstein g, above 0 scatters forward", + "default": 0.3, + "minimum": -0.9, + "maximum": 0.9 + }, + "ambient": { + "type": "number", + "x-toast-type": "float", + "description": "Ambient light scattered by the fog", + "default": 1.0, + "minimum": 0, + "maximum": 4 + }, + "distance": { + "type": "number", + "x-toast-type": "float", + "description": "Meters a view ray marches before the sky", + "default": 64.0, + "minimum": 1, + "maximum": 1000 + } + } + } + } +} diff --git a/engine/assets/schemas/post_process.schema.json.meta b/engine/assets/schemas/post_process.schema.json.meta new file mode 100644 index 000000000..6e506619a --- /dev/null +++ b/engine/assets/schemas/post_process.schema.json.meta @@ -0,0 +1,4 @@ +uid = "PostProcSc4" +type = "schema" +created_at = "2026-11-24T14:00:00.0000000Z" +modified_at = "2026-11-24T14:00:00.0000000Z" diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 487c77c35..790a08bea 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -4,6 +4,7 @@ #include #include +#include #include namespace assets { @@ -86,6 +87,9 @@ void AssetRegistry::init() { s_schema_toml["destruction_material"] = [](const toml::table& t, Handle s) { return std::make_unique(t, std::move(s)); }; + s_schema_toml["post_process_profile"] = [](const toml::table& t, Handle s) { + return std::make_unique(t, std::move(s)); + }; // Lua global names s_lua_names["mesh"] = "Mesh"; @@ -121,6 +125,7 @@ void AssetRegistry::init() { s_lua_names["detail_texture"] = "DetailTexture"; s_lua_names["animation"] = "Animation"; s_lua_names["physics_material"] = "PhysicsMaterial"; + s_lua_names["post_process_profile"] = "PostProcessProfile"; } void AssetRegistry::registerLuaName(std::string_view type, std::string_view lua_name) { diff --git a/engine/src/toast/renderer/settings/post_process_params.cpp b/engine/src/toast/renderer/settings/post_process_params.cpp new file mode 100644 index 000000000..a086909c7 --- /dev/null +++ b/engine/src/toast/renderer/settings/post_process_params.cpp @@ -0,0 +1,389 @@ +#include "toast/renderer/settings/post_process_params.hpp" + +#include +#include +#include +#include +#include +#include + +namespace renderer { +namespace { + +using Kind = PostProcessParams::Kind; +using Slot = PostProcessParams::Slot; +using ParamValue = PostProcessParams::ParamValue; + +constexpr std::string_view k_core_schema = "core://schemas/post_process.schema.json"; + +auto normalize(const Slot& slot, float x) -> float { + switch (slot.kind) { + case Kind::boolean: return x != 0.0f ? 1.0f : 0.0f; + case Kind::enumeration: + return std::clamp(std::round(x), 0.0f, static_cast(std::max(slot.options.size(), 1) - 1)); + case Kind::integer: return std::clamp(std::round(x), slot.min, slot.max); + default: return std::clamp(x, slot.min, slot.max); + } +} + +auto optionIndex(const Slot& slot, std::string_view option) -> std::optional { + const auto it = std::ranges::find(slot.options, option); + return it == slot.options.end() ? std::nullopt : std::optional {static_cast(it - slot.options.begin())}; +} + +auto lookup(const assets::DataValue& root, std::string_view path) -> const assets::DataValue* { + const assets::DataValue* node = &root; + while (true) { + const auto dot = path.find('.'); + const auto key = path.substr(0, dot); + if (!node->isObject() || !node->contains(key)) { + return nullptr; + } + node = &(*node)[key]; + if (dot == std::string_view::npos) { + return node; + } + path.remove_prefix(dot + 1); + } +} + +auto readValue(const Slot& slot, const assets::DataValue& value) -> std::optional { + using assets::DataType; + ParamValue out; + switch (slot.kind) { + case Kind::number: + case Kind::integer: + if (value.type() == DataType::float_t) { + out.v.x = value.as(); + } else if (value.type() == DataType::int_t) { + out.v.x = static_cast(value.as()); + } else { + return std::nullopt; + } + break; + case Kind::boolean: + if (value.type() != DataType::bool_t) { + return std::nullopt; + } + out.v.x = value.as() ? 1.0f : 0.0f; + break; + case Kind::enumeration: { + if (value.type() != DataType::string_t) { + return std::nullopt; + } + const auto index = optionIndex(slot, value.as()); + if (!index) { + return std::nullopt; + } + out.v.x = static_cast(*index); + break; + } + case Kind::color: + if (value.type() != DataType::color3_t && value.type() != DataType::vec3_t) { + return std::nullopt; + } + out.v = value.as(); + break; + case Kind::asset: + if (value.type() != DataType::asset_t) { + return std::nullopt; + } + out.asset = value.as(); + break; + } + if (slot.kind != Kind::color && slot.kind != Kind::asset) { + out.v.x = normalize(slot, out.v.x); + } + return out; +} + +void collectSlots(const std::vector& fields, const std::string& prefix, PostProcessParams::Layout& layout) { + using assets::DataType; + for (const auto& field : fields) { + const std::string name = prefix.empty() ? field.name : prefix + "." + field.name; + if (field.type == DataType::object_t) { + collectSlots(field.children, name, layout); + continue; + } + + Slot slot; + slot.name = name; + switch (field.type) { + case DataType::float_t: slot.kind = Kind::number; break; + case DataType::int_t: slot.kind = Kind::integer; break; + case DataType::bool_t: slot.kind = Kind::boolean; break; + case DataType::string_t: + if (field.enum_options.empty()) { + continue; + } + slot.kind = Kind::enumeration; + slot.options = field.enum_options; + break; + case DataType::color3_t: + case DataType::vec3_t: slot.kind = Kind::color; break; + case DataType::asset_t: slot.kind = Kind::asset; break; + default: continue; + } + if (field.min) { + slot.min = static_cast(*field.min); + } + if (field.max) { + slot.max = static_cast(*field.max); + } + if (field.default_value) { + if (const auto value = readValue(slot, *field.default_value)) { + slot.fallback = *value; + } + } + layout.add(std::move(slot)); + } +} + +} + +auto PostProcessParams::Layout::find(std::string_view name) const -> std::optional { + const auto it = m_index.find(name); + return it == m_index.end() ? std::nullopt : std::optional {it->second}; +} + +void PostProcessParams::Layout::add(Slot slot) { + m_index.emplace(slot.name, static_cast(slots.size())); + slots.push_back(std::move(slot)); +} + +auto PostProcessParams::Layout::fromSchema(const assets::Schema& schema) -> std::shared_ptr { + auto layout = std::make_shared(); + collectSlots(schema.fields(), {}, *layout); + return layout; +} + +auto PostProcessParams::coreLayout() -> std::shared_ptr { + static std::mutex mutex; + static std::shared_ptr cached; + static const auto empty = std::make_shared(); + + const std::lock_guard lock(mutex); + if (cached) { + return cached; + } + if (!assets::AssetManager::isInitialized()) { + return empty; + } + + const auto schema = assets::load(k_core_schema); + if (!schema.hasValue() || !schema->isValid()) { + static bool warned = false; + if (!std::exchange(warned, true)) { + TOAST_ERROR("PostProcess", "Could not load {}, post-process parameters fall back to struct defaults", k_core_schema); + } + return empty; + } + cached = Layout::fromSchema(*schema); + return cached; +} + +PostProcessParams::PostProcessParams(std::shared_ptr layout) : m_layout(std::move(layout)) { + reset(); +} + +void PostProcessParams::reset() { + // In place, so a thread reading while this runs never sees the vector change size + m_values.resize(m_layout->slots.size()); + for (size_t i = 0; i < m_values.size(); ++i) { + m_values[i] = m_layout->slots[i].fallback; + } +} + +void PostProcessParams::loadFrom(const assets::Data& profile) { + reset(); + for (size_t i = 0; i < m_layout->slots.size(); ++i) { + const auto& slot = m_layout->slots[i]; + if (const auto* value = lookup(profile.root(), slot.name)) { + if (const auto parsed = readValue(slot, *value)) { + m_values[i] = *parsed; + } + } + } +} + +void PostProcessParams::blend(const PostProcessParams& source, float weight) { + if (m_layout != source.m_layout) { + return; + } + const float t = std::clamp(weight, 0.0f, 1.0f); + if (t <= 0.0f) { + return; + } + + for (size_t i = 0; i < m_values.size(); ++i) { + const auto& slot = m_layout->slots[i]; + auto& target = m_values[i]; + const auto& from = source.m_values[i]; + switch (slot.kind) { + case Kind::number: + case Kind::color: target.v = glm::mix(target.v, from.v, t); break; + case Kind::integer: target.v.x = std::round(glm::mix(target.v.x, from.v.x, t)); break; + case Kind::boolean: + case Kind::enumeration: + case Kind::asset: + if (t >= 0.5f) { + target = from; + } + break; + } + } +} + +auto PostProcessParams::setNumber(std::string_view name, float value) -> bool { + const auto index = m_layout->find(name); + if (!index) { + return false; + } + const auto& slot = m_layout->slots[*index]; + if (slot.kind == Kind::color || slot.kind == Kind::asset) { + return false; + } + m_values[*index].v.x = normalize(slot, value); + return true; +} + +auto PostProcessParams::setColor(std::string_view name, const glm::vec3& value) -> bool { + const auto index = m_layout->find(name); + if (!index || m_layout->slots[*index].kind != Kind::color) { + return false; + } + m_values[*index].v = value; + return true; +} + +auto PostProcessParams::setOption(std::string_view name, std::string_view option) -> bool { + const auto index = m_layout->find(name); + if (!index || m_layout->slots[*index].kind != Kind::enumeration) { + return false; + } + const auto choice = optionIndex(m_layout->slots[*index], option); + if (!choice) { + return false; + } + m_values[*index].v.x = static_cast(*choice); + return true; +} + +auto PostProcessParams::number(std::string_view name) const -> std::optional { + const auto index = m_layout->find(name); + if (!index || m_layout->slots[*index].kind == Kind::color || m_layout->slots[*index].kind == Kind::asset) { + return std::nullopt; + } + return m_values[*index].v.x; +} + +auto PostProcessParams::color(std::string_view name) const -> std::optional { + const auto index = m_layout->find(name); + if (!index || m_layout->slots[*index].kind != Kind::color) { + return std::nullopt; + } + return m_values[*index].v; +} + +auto PostProcessParams::assetUid(std::string_view name) const -> std::optional { + const auto index = m_layout->find(name); + if (!index || m_layout->slots[*index].kind != Kind::asset) { + return std::nullopt; + } + return m_values[*index].asset; +} + +auto PostProcessParams::resolve() const -> PostProcessSettings { + PostProcessSettings s; + + const auto f = [this](std::string_view name, float& out) { + if (const auto v = number(name)) { + out = *v; + } + }; + const auto u = [this](std::string_view name, uint32_t& out) { + if (const auto v = number(name)) { + out = static_cast(std::max(*v, 0.0f)); + } + }; + const auto b = [this](std::string_view name, bool& out) { + if (const auto v = number(name)) { + out = *v != 0.0f; + } + }; + const auto c = [this](std::string_view name, float& r, float& g, float& bl) { + if (const auto v = color(name)) { + r = v->r; + g = v->g; + bl = v->b; + } + }; + + f("bloom.threshold", s.bloom.threshold); + f("bloom.knee", s.bloom.knee); + f("bloom.filter_radius", s.bloom.filter_radius); + f("bloom.strength", s.bloom.strength); + + f("lens_flare.intensity", s.lens_flare.intensity); + f("lens_flare.threshold", s.lens_flare.threshold); + f("lens_flare.threshold_range", s.lens_flare.threshold_range); + f("lens_flare.ghost_intensity", s.lens_flare.ghost_intensity); + f("lens_flare.chroma_shift", s.lens_flare.chroma_shift); + f("lens_flare.halo_intensity", s.lens_flare.halo_intensity); + f("lens_flare.halo_width", s.lens_flare.halo_width); + f("lens_flare.halo_mask", s.lens_flare.halo_mask); + f("lens_flare.halo_compression", s.lens_flare.halo_compression); + f("lens_flare.glare_intensity", s.lens_flare.glare_intensity); + f("lens_flare.glare_divider", s.lens_flare.glare_divider); + f("lens_flare.anamorphic_intensity", s.lens_flare.anamorphic_intensity); + f("lens_flare.anamorphic_tint", s.lens_flare.anamorphic_tint); + f("lens_flare.dirt_intensity", s.lens_flare.dirt_intensity); + f("lens_flare.halo_thickness", s.lens_flare.halo_thickness); + f("lens_flare.halo_dispersion", s.lens_flare.halo_dispersion); + c("lens_flare.halo_tint", s.lens_flare.halo_tint_r, s.lens_flare.halo_tint_g, s.lens_flare.halo_tint_b); + if (const auto uid = assetUid("lens_flare.dirt_texture"); uid && uid->data() != 0) { + s.lens_flare.dirt_texture = assets::load(*uid); + } + + f("tonemap.exposure", s.tonemap.exposure); + u("tonemap.mode", s.tonemap.mode); + f("tonemap.gt_contrast_dip", s.tonemap.gt_contrast_dip); + f("tonemap.chromatic_aberration", s.tonemap.chromatic_aberration); + f("tonemap.gamma", s.tonemap.gamma); + f("tonemap.contrast", s.tonemap.contrast); + f("tonemap.saturation", s.tonemap.saturation); + f("tonemap.vignette", s.tonemap.vignette); + f("tonemap.grain", s.tonemap.grain); + b("tonemap.auto_exposure", s.tonemap.auto_exposure); + f("tonemap.auto_exposure_min", s.tonemap.auto_exposure_min); + f("tonemap.auto_exposure_max", s.tonemap.auto_exposure_max); + f("tonemap.adapt_speed_up", s.tonemap.adapt_speed_up); + f("tonemap.adapt_speed_down", s.tonemap.adapt_speed_down); + + f("fxaa.contrast_threshold", s.fxaa.contrast_threshold); + f("fxaa.relative_threshold", s.fxaa.relative_threshold); + f("fxaa.subpixel_blending", s.fxaa.subpixel_blending); + + f("ssr.intensity", s.ssr.intensity); + f("ssr.max_roughness", s.ssr.max_roughness); + f("ssr.thickness", s.ssr.thickness); + f("ssr.stride", s.ssr.stride); + u("ssr.max_steps", s.ssr.max_steps); + + f("ssao.radius", s.ssao.radius); + f("ssao.strength", s.ssao.strength); + f("ssao.range_cutoff", s.ssao.range_cutoff); + u("ssao.sample_count", s.ssao.sample_count); + + f("fog.density", s.fog.density); + f("fog.height", s.fog.height); + f("fog.height_falloff", s.fog.height_falloff); + c("fog.albedo", s.fog.albedo_r, s.fog.albedo_g, s.fog.albedo_b); + f("fog.anisotropy", s.fog.anisotropy); + f("fog.ambient", s.fog.ambient); + f("fog.distance", s.fog.distance); + + return s; +} + +} diff --git a/engine/src/toast/renderer/settings/post_process_params.hpp b/engine/src/toast/renderer/settings/post_process_params.hpp new file mode 100644 index 000000000..7c482a2e3 --- /dev/null +++ b/engine/src/toast/renderer/settings/post_process_params.hpp @@ -0,0 +1,119 @@ +/** + * @file post_process_params.hpp + * @author dario + * @date 24/11/2026 + * + * @brief Post-process knobs as data, laid out by core://schemas/post_process.schema.json + */ + +#pragma once +#include "post_process_settings.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace renderer { + +/** + * @brief A flat set of named post-process values + */ +class TOAST_API PostProcessParams { +public: + enum class Kind : uint8_t { + number, + integer, ///< stored as a float + boolean, + enumeration, ///< index into Slot::options + color, + asset ///< UID in ParamValue::asset + }; + + struct ParamValue { + glm::vec3 v {0.0f}; + toast::UID asset {uint64_t {0}}; + }; + + struct Slot { + std::string name; + Kind kind {Kind::number}; + float min {-std::numeric_limits::infinity()}; + float max {std::numeric_limits::infinity()}; + ParamValue fallback; + std::vector options; ///< enumeration only + }; + + /// Immutable and shared between every params object built from the same schema + struct TOAST_API Layout { + std::vector slots; + + [[nodiscard]] + auto find(std::string_view name) const -> std::optional; + + void add(Slot slot); + + /// Walks nested objects + static auto fromSchema(const assets::Schema& schema) -> std::shared_ptr; + + private: + struct NameHash { + using is_transparent = void; + + auto operator()(std::string_view s) const noexcept -> size_t { return std::hash {}(s); } + }; + + std::unordered_map> m_index; + }; + + static auto coreLayout() -> std::shared_ptr; + + PostProcessParams() : PostProcessParams(coreLayout()) { } + + explicit PostProcessParams(std::shared_ptr layout); + + void reset(); + + /// Defaults first + void loadFrom(const assets::Data& profile); + + void blend(const PostProcessParams& source, float weight); + + auto setNumber(std::string_view name, float value) -> bool; + + auto setColor(std::string_view name, const glm::vec3& value) -> bool; + + auto setOption(std::string_view name, std::string_view option) -> bool; + + [[nodiscard]] + auto number(std::string_view name) const -> std::optional; + + [[nodiscard]] + auto color(std::string_view name) const -> std::optional; + + [[nodiscard]] + auto assetUid(std::string_view name) const -> std::optional; + + [[nodiscard]] + auto layout() const noexcept -> const std::shared_ptr& { + return m_layout; + } + + [[nodiscard]] + auto resolve() const -> PostProcessSettings; + +private: + std::shared_ptr m_layout; + std::vector m_values; +}; + +} diff --git a/engine/src/toast/renderer/settings/post_process_profile.cpp b/engine/src/toast/renderer/settings/post_process_profile.cpp new file mode 100644 index 000000000..8b5a71629 --- /dev/null +++ b/engine/src/toast/renderer/settings/post_process_profile.cpp @@ -0,0 +1,11 @@ +#include "toast/renderer/settings/post_process_profile.hpp" + +namespace assets { + +PostProcessProfile::PostProcessProfile(const toml::table& table, Handle schema) : Data(table, std::move(schema)) { } + +void PostProcessProfile::onReloaded() { + m_version.fetch_add(1, std::memory_order_relaxed); +} + +} diff --git a/engine/src/toast/renderer/settings/post_process_profile.hpp b/engine/src/toast/renderer/settings/post_process_profile.hpp new file mode 100644 index 000000000..5726e83c2 --- /dev/null +++ b/engine/src/toast/renderer/settings/post_process_profile.hpp @@ -0,0 +1,35 @@ +/** + * @file post_process_profile.hpp + * @author dario + * @date 24/11/2026 + */ + +#pragma once +#include +#include + +namespace assets { + +class TOAST_API PostProcessProfile : public Data { +public: + explicit PostProcessProfile(const toml::table& table, Handle schema = {}); + + [[nodiscard]] + auto type() const -> std::string_view override { + return "post_process_profile"; + } + + /// Bumps whenever the file is re-read + [[nodiscard]] + auto version() const noexcept -> uint32_t { + return m_version.load(std::memory_order_relaxed); + } + +protected: + void onReloaded() override; + +private: + std::atomic m_version {0}; +}; + +} diff --git a/engine/src/toast/renderer/settings/post_process_settings.cpp b/engine/src/toast/renderer/settings/post_process_settings.cpp deleted file mode 100644 index a7222f12f..000000000 --- a/engine/src/toast/renderer/settings/post_process_settings.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "toast/renderer/settings/post_process_settings.hpp" - -namespace renderer { -namespace { - -auto mix(float a, float b, float t) -> float { - return a + ((b - a) * t); -} - -auto pick(uint32_t a, uint32_t b, float t) -> uint32_t { - return t >= 0.5f ? b : a; -} - -auto mixCount(uint32_t a, uint32_t b, float t) -> uint32_t { - return static_cast(std::lround(mix(static_cast(a), static_cast(b), t))); -} - -} - -void blendPostProcess(PostProcessSettings& target, const PostProcessSettings& source, float weight) { - const float t = std::clamp(weight, 0.0f, 1.0f); - if (t <= 0.0f) { - return; - } - - target.bloom.threshold = mix(target.bloom.threshold, source.bloom.threshold, t); - target.bloom.knee = mix(target.bloom.knee, source.bloom.knee, t); - target.bloom.filter_radius = mix(target.bloom.filter_radius, source.bloom.filter_radius, t); - target.bloom.strength = mix(target.bloom.strength, source.bloom.strength, t); - - target.lens_flare.intensity = mix(target.lens_flare.intensity, source.lens_flare.intensity, t); - target.lens_flare.threshold = mix(target.lens_flare.threshold, source.lens_flare.threshold, t); - target.lens_flare.threshold_range = mix(target.lens_flare.threshold_range, source.lens_flare.threshold_range, t); - target.lens_flare.ghost_intensity = mix(target.lens_flare.ghost_intensity, source.lens_flare.ghost_intensity, t); - target.lens_flare.chroma_shift = mix(target.lens_flare.chroma_shift, source.lens_flare.chroma_shift, t); - target.lens_flare.halo_intensity = mix(target.lens_flare.halo_intensity, source.lens_flare.halo_intensity, t); - target.lens_flare.halo_width = mix(target.lens_flare.halo_width, source.lens_flare.halo_width, t); - target.lens_flare.halo_mask = mix(target.lens_flare.halo_mask, source.lens_flare.halo_mask, t); - target.lens_flare.halo_compression = mix(target.lens_flare.halo_compression, source.lens_flare.halo_compression, t); - target.lens_flare.glare_intensity = mix(target.lens_flare.glare_intensity, source.lens_flare.glare_intensity, t); - target.lens_flare.glare_divider = mix(target.lens_flare.glare_divider, source.lens_flare.glare_divider, t); - target.lens_flare.anamorphic_intensity = mix(target.lens_flare.anamorphic_intensity, source.lens_flare.anamorphic_intensity, t); - target.lens_flare.anamorphic_tint = mix(target.lens_flare.anamorphic_tint, source.lens_flare.anamorphic_tint, t); - target.lens_flare.dirt_intensity = mix(target.lens_flare.dirt_intensity, source.lens_flare.dirt_intensity, t); - target.lens_flare.halo_thickness = mix(target.lens_flare.halo_thickness, source.lens_flare.halo_thickness, t); - target.lens_flare.halo_dispersion = mix(target.lens_flare.halo_dispersion, source.lens_flare.halo_dispersion, t); - target.lens_flare.halo_tint_r = mix(target.lens_flare.halo_tint_r, source.lens_flare.halo_tint_r, t); - target.lens_flare.halo_tint_g = mix(target.lens_flare.halo_tint_g, source.lens_flare.halo_tint_g, t); - target.lens_flare.halo_tint_b = mix(target.lens_flare.halo_tint_b, source.lens_flare.halo_tint_b, t); - // Textures switch at the halfway point - target.lens_flare.dirt_texture = t >= 0.5f ? source.lens_flare.dirt_texture : target.lens_flare.dirt_texture; - - target.tonemap.exposure = mix(target.tonemap.exposure, source.tonemap.exposure, t); - target.tonemap.mode = pick(target.tonemap.mode, source.tonemap.mode, t); - target.tonemap.gt_contrast_dip = mix(target.tonemap.gt_contrast_dip, source.tonemap.gt_contrast_dip, t); - target.tonemap.chromatic_aberration = mix(target.tonemap.chromatic_aberration, source.tonemap.chromatic_aberration, t); - target.tonemap.gamma = mix(target.tonemap.gamma, source.tonemap.gamma, t); - target.tonemap.contrast = mix(target.tonemap.contrast, source.tonemap.contrast, t); - target.tonemap.saturation = mix(target.tonemap.saturation, source.tonemap.saturation, t); - target.tonemap.vignette = mix(target.tonemap.vignette, source.tonemap.vignette, t); - target.tonemap.grain = mix(target.tonemap.grain, source.tonemap.grain, t); - target.tonemap.auto_exposure = t >= 0.5f ? source.tonemap.auto_exposure : target.tonemap.auto_exposure; - target.tonemap.auto_exposure_min = mix(target.tonemap.auto_exposure_min, source.tonemap.auto_exposure_min, t); - target.tonemap.auto_exposure_max = mix(target.tonemap.auto_exposure_max, source.tonemap.auto_exposure_max, t); - target.tonemap.adapt_speed_up = mix(target.tonemap.adapt_speed_up, source.tonemap.adapt_speed_up, t); - target.tonemap.adapt_speed_down = mix(target.tonemap.adapt_speed_down, source.tonemap.adapt_speed_down, t); - - target.fxaa.contrast_threshold = mix(target.fxaa.contrast_threshold, source.fxaa.contrast_threshold, t); - target.fxaa.relative_threshold = mix(target.fxaa.relative_threshold, source.fxaa.relative_threshold, t); - target.fxaa.subpixel_blending = mix(target.fxaa.subpixel_blending, source.fxaa.subpixel_blending, t); - - target.ssr.intensity = mix(target.ssr.intensity, source.ssr.intensity, t); - target.ssr.max_roughness = mix(target.ssr.max_roughness, source.ssr.max_roughness, t); - target.ssr.thickness = mix(target.ssr.thickness, source.ssr.thickness, t); - target.ssr.stride = mix(target.ssr.stride, source.ssr.stride, t); - target.ssr.max_steps = mixCount(target.ssr.max_steps, source.ssr.max_steps, t); - - target.ssao.radius = mix(target.ssao.radius, source.ssao.radius, t); - target.ssao.strength = mix(target.ssao.strength, source.ssao.strength, t); - target.ssao.range_cutoff = mix(target.ssao.range_cutoff, source.ssao.range_cutoff, t); - target.ssao.sample_count = mixCount(target.ssao.sample_count, source.ssao.sample_count, t); - - target.fog.density = mix(target.fog.density, source.fog.density, t); - target.fog.height = mix(target.fog.height, source.fog.height, t); - target.fog.height_falloff = mix(target.fog.height_falloff, source.fog.height_falloff, t); - target.fog.albedo_r = mix(target.fog.albedo_r, source.fog.albedo_r, t); - target.fog.albedo_g = mix(target.fog.albedo_g, source.fog.albedo_g, t); - target.fog.albedo_b = mix(target.fog.albedo_b, source.fog.albedo_b, t); - target.fog.anisotropy = mix(target.fog.anisotropy, source.fog.anisotropy, t); - target.fog.ambient = mix(target.fog.ambient, source.fog.ambient, t); - target.fog.distance = mix(target.fog.distance, source.fog.distance, t); -} - -} diff --git a/engine/src/toast/renderer/settings/post_process_settings.hpp b/engine/src/toast/renderer/settings/post_process_settings.hpp index f89aa628e..714c502c6 100644 --- a/engine/src/toast/renderer/settings/post_process_settings.hpp +++ b/engine/src/toast/renderer/settings/post_process_settings.hpp @@ -11,7 +11,6 @@ namespace renderer { -/// @note Every member must be handled in blendPostProcess() struct PostProcessSettings { struct Bloom { float threshold = 1.0f; @@ -21,24 +20,24 @@ struct PostProcessSettings { } bloom; struct LensFlare { - float intensity = 0.1f; + float intensity = 0.009f; float threshold = 1.0f; float threshold_range = 1.0f; - float ghost_intensity = 1.0f; + float ghost_intensity = 2.0f; float chroma_shift = 0.015f; float halo_intensity = 1.0f; - float halo_width = 0.6f; - float halo_mask = 0.5f; - float halo_compression = 0.65f; + float halo_width = 0.41f; + float halo_mask = 0.124f; + float halo_compression = 1.0f; float glare_intensity = 0.2f; - float glare_divider = 60.0f; + float glare_divider = 162.0f; float anamorphic_intensity = 1.0f; /// Share of the streak pulled toward blue float anamorphic_tint = 0.6f; float dirt_intensity = 0.0f; /// Spread of the ring along its radius - float halo_thickness = 0.3f; - float halo_dispersion = 0.015f; + float halo_thickness = 0.09f; + float halo_dispersion = 0.056f; float halo_tint_r = 1.0f; float halo_tint_g = 1.0f; float halo_tint_b = 1.0f; @@ -48,7 +47,7 @@ struct PostProcessSettings { struct Tonemap { float exposure = 1.0f; /// 0 Reinhard 1 ACES 2 GT7 - uint32_t mode = 0; + uint32_t mode = 2; float gt_contrast_dip = 1.28f; float chromatic_aberration = 0.0f; float gamma = 2.2f; @@ -57,10 +56,10 @@ struct PostProcessSettings { float vignette = 0.0f; float grain = 0.0f; - bool auto_exposure = false; + bool auto_exposure = true; /// log2 of the average scene luminance the meter may settle on - float auto_exposure_min = -8.0f; - float auto_exposure_max = 4.0f; + float auto_exposure_min = -5.0f; + float auto_exposure_max = 8.0f; /// Per second toward a brighter scene float adapt_speed_up = 3.0f; float adapt_speed_down = 1.0f; @@ -96,7 +95,7 @@ struct PostProcessSettings { struct Fog { /// Extinction per meter at the base height and 0 turns volumetrics off - float density = 0.0f; + float density = 0.005f; float height = 0.0f; /// Per meter above the base height and 0 is uniform float height_falloff = 0.0f; @@ -111,6 +110,4 @@ struct PostProcessSettings { } fog; }; -TOAST_API void blendPostProcess(PostProcessSettings& target, const PostProcessSettings& source, float weight); - } diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 4758b7410..b10e300e7 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -21,6 +21,7 @@ #include "toast/renderer/resources/vulkan_mesh.hpp" #include "toast/renderer/resources/vulkan_texture.hpp" #include "toast/renderer/settings/gi_settings.hpp" +#include "toast/renderer/settings/post_process_params.hpp" #include "toast/renderer/settings/post_process_settings.hpp" #include "toast/renderer/shaders/shader_layout.hpp" #include "toast/renderer/shaders/vulkan_pipeline.hpp" @@ -1271,18 +1272,12 @@ class VulkanRenderer { return m_taa_history_weight.load(std::memory_order_relaxed); } - void setPostProcessSettings(const PostProcessSettings& settings) noexcept { m_post_process_settings = settings; } + /// Sets a knob of the base grade that post process volumes blend over, by its path in post_process.schema.json + /// ("bloom.strength"), clamped to the schema range. Safe from any thread + /// @returns false when the name is unknown or not a scalar + auto setPostProcessNumber(std::string_view name, float value) -> bool; - [[nodiscard]] - auto getPostProcessSettings() const noexcept -> const PostProcessSettings& { - return m_post_process_settings; - } - - /// Safe from any thread - void requestPostProcessSettings(const PostProcessSettings& settings) { - const std::lock_guard lock(m_pending_post_settings_mutex); - m_pending_post_settings = settings; - } + auto setPostProcessColor(std::string_view name, const glm::vec3& value) -> bool; /// nullptr renders every owner. Main thread only void setRenderOwnerFilter(const toast::INodeOwner* owner) { @@ -1692,7 +1687,12 @@ class VulkanRenderer { void gatherFogVolumes(RenderFrame& frame, const glm::vec3& camera_position); - PostProcessSettings m_post_process_settings; + PostProcessParams m_base_params; + std::mutex m_base_params_mutex; + /// Scratch for the per-frame blend, tick thread only + PostProcessParams m_blend_params; + void repairBaseParamsLocked(); + void copyBaseParams(PostProcessParams& out); std::atomic_bool m_traced_shadows_enabled {false}; /// Logs once each time the fallback starts @@ -1725,9 +1725,6 @@ class VulkanRenderer { void beginDebugLineCollection(RenderFrame& frame); void endDebugLineCollection(); - std::mutex m_pending_post_settings_mutex; - std::optional m_pending_post_settings; - const toast::INodeOwner* m_render_owner_filter = nullptr; const toast::INodeOwner* m_secondary_owner = nullptr; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index f75c433d3..aa2a7fef7 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -255,7 +255,8 @@ auto VulkanRenderer::ownerTransform(const toast::Node& node) const -> const glm: auto VulkanRenderer::blendPostProcessVolumes(const glm::vec3& camera_position) -> PostProcessSettings { ZoneScoped; - PostProcessSettings result = m_post_process_settings; + PostProcessParams& result = m_blend_params; + copyBaseParams(result); auto& volumes = m_tick_post_volumes; { @@ -280,10 +281,35 @@ auto VulkanRenderer::blendPostProcessVolumes(const glm::vec3& camera_position) - if (influence <= 0.0f) { continue; } - blendPostProcess(result, volume->settings(), influence); + result.blend(volume->params(), influence); } - return result; + return result.resolve(); +} + +void VulkanRenderer::repairBaseParamsLocked() { + // Built before the asset manager could load the schema, so it holds no slots + if (m_base_params.layout()->slots.empty()) { + m_base_params = PostProcessParams {}; + } +} + +void VulkanRenderer::copyBaseParams(PostProcessParams& out) { + const std::lock_guard lock(m_base_params_mutex); + repairBaseParamsLocked(); + out = m_base_params; +} + +auto VulkanRenderer::setPostProcessNumber(std::string_view name, float value) -> bool { + const std::lock_guard lock(m_base_params_mutex); + repairBaseParamsLocked(); + return m_base_params.setNumber(name, value); +} + +auto VulkanRenderer::setPostProcessColor(std::string_view name, const glm::vec3& value) -> bool { + const std::lock_guard lock(m_base_params_mutex); + repairBaseParamsLocked(); + return m_base_params.setColor(name, value); } void VulkanRenderer::gatherFogVolumes(RenderFrame& frame, const glm::vec3& camera_position) { @@ -604,14 +630,8 @@ void VulkanRenderer::resetFrameBuild(RenderFrame& frame) { frame.sequence = ++m_frame_sequence_counter; frame.render_mode = m_render_mode; - { - const std::lock_guard lock(m_pending_post_settings_mutex); - if (m_pending_post_settings.has_value()) { - m_post_process_settings = *m_pending_post_settings; - m_pending_post_settings.reset(); - } - } - frame.post_process = m_post_process_settings; + copyBaseParams(m_blend_params); + frame.post_process = m_blend_params.resolve(); } void VulkanRenderer::gatherMeshProxies(RenderFrame& frame) { diff --git a/engine/src/toast/world/post_process_volume.cpp b/engine/src/toast/world/post_process_volume.cpp index 2481591ca..9e39403fa 100644 --- a/engine/src/toast/world/post_process_volume.cpp +++ b/engine/src/toast/world/post_process_volume.cpp @@ -24,77 +24,68 @@ void PostProcessVolume::destroy() { end(); } -void PostProcessVolume::syncSettings() const { - m_settings.bloom.threshold = m_bloom_threshold; - m_settings.bloom.knee = m_bloom_knee; - m_settings.bloom.filter_radius = m_bloom_filter_radius; - m_settings.bloom.strength = m_bloom_strength; - - m_settings.lens_flare.intensity = m_lens_flare_intensity; - m_settings.lens_flare.threshold = m_lens_flare_threshold; - m_settings.lens_flare.ghost_intensity = m_ghost_intensity; - m_settings.lens_flare.halo_intensity = m_halo_intensity; - m_settings.lens_flare.halo_width = m_halo_width; - m_settings.lens_flare.halo_mask = m_halo_mask; - m_settings.lens_flare.halo_compression = m_halo_compression; - m_settings.lens_flare.halo_thickness = m_halo_thickness; - m_settings.lens_flare.halo_dispersion = m_halo_dispersion; - m_settings.lens_flare.halo_tint_r = m_halo_tint.r; - m_settings.lens_flare.halo_tint_g = m_halo_tint.g; - m_settings.lens_flare.halo_tint_b = m_halo_tint.b; - m_settings.lens_flare.chroma_shift = m_flare_chroma_shift; - m_settings.lens_flare.threshold_range = m_lens_flare_threshold_range; - m_settings.lens_flare.glare_divider = m_glare_divider; - m_settings.lens_flare.glare_intensity = m_glare_intensity; - m_settings.lens_flare.anamorphic_intensity = m_anamorphic_intensity; - m_settings.lens_flare.anamorphic_tint = m_anamorphic_tint; - m_settings.lens_flare.dirt_intensity = m_dirt_intensity; - m_settings.lens_flare.dirt_texture = m_lens_dirt_texture; - - m_settings.tonemap.exposure = m_exposure; - m_settings.tonemap.mode = static_cast(std::max(m_tonemap_mode, 0)); - m_settings.tonemap.gt_contrast_dip = m_gt_contrast_dip; - m_settings.tonemap.chromatic_aberration = m_chromatic_aberration; - m_settings.tonemap.gamma = m_gamma; - m_settings.tonemap.contrast = m_contrast; - m_settings.tonemap.saturation = m_saturation; - m_settings.tonemap.vignette = m_vignette; - m_settings.tonemap.grain = m_grain; - m_settings.tonemap.auto_exposure = m_auto_exposure; - m_settings.tonemap.auto_exposure_min = m_auto_exposure_min; - m_settings.tonemap.auto_exposure_max = m_auto_exposure_max; - m_settings.tonemap.adapt_speed_up = m_adapt_speed_up; - m_settings.tonemap.adapt_speed_down = m_adapt_speed_down; - - m_settings.fxaa.contrast_threshold = m_fxaa_contrast_threshold; - m_settings.fxaa.relative_threshold = m_fxaa_relative_threshold; - m_settings.fxaa.subpixel_blending = m_fxaa_subpixel_blending; - - m_settings.ssr.intensity = m_ssr_intensity; - m_settings.ssr.max_roughness = m_ssr_max_roughness; - m_settings.ssr.thickness = m_ssr_thickness; - m_settings.ssr.stride = m_ssr_stride; - m_settings.ssr.max_steps = static_cast(std::max(m_ssr_max_steps, 1)); - - m_settings.ssao.radius = m_ssao_radius; - m_settings.ssao.strength = m_ssao_strength; - m_settings.ssao.range_cutoff = m_ssao_range_cutoff; - m_settings.ssao.sample_count = static_cast(std::max(m_ssao_sample_count, 1)); - - m_settings.fog.density = std::max(m_fog_density, 0.0f); - m_settings.fog.height = m_fog_height; - m_settings.fog.height_falloff = std::max(m_fog_height_falloff, 0.0f); - m_settings.fog.albedo_r = m_fog_albedo.r; - m_settings.fog.albedo_g = m_fog_albedo.g; - m_settings.fog.albedo_b = m_fog_albedo.b; - m_settings.fog.anisotropy = std::clamp(m_fog_anisotropy, -0.9f, 0.9f); - m_settings.fog.ambient = std::max(m_fog_ambient, 0.0f); - m_settings.fog.distance = std::max(m_fog_distance, 1.0f); -} - -auto PostProcessVolume::settings() const -> const renderer::PostProcessSettings& { - syncSettings(); - return m_settings; +void PostProcessVolume::syncParams() const { + // Built before the asset manager could load the schema, so it holds no slots and cannot take a value + const bool rebuild = m_params.layout()->slots.empty(); + if (rebuild) { + m_params = renderer::PostProcessParams {}; + } + + const assets::PostProcessProfile* profile = m_profile.hasValue() ? &*m_profile : nullptr; + const uint32_t version = profile != nullptr ? profile->version() : 0; + if (!rebuild && profile == m_synced_profile && version == m_synced_version) { + return; + } + + m_synced_profile = profile; + m_synced_version = version; + if (profile != nullptr) { + m_params.loadFrom(*profile); + } else { + m_params.reset(); + } +} + +auto PostProcessVolume::params() const -> const renderer::PostProcessParams& { + syncParams(); + return m_params; +} + +auto PostProcessVolume::setParam(std::string_view name, float value) -> bool { + syncParams(); + return m_params.setNumber(name, value); +} + +auto PostProcessVolume::setParamColor(std::string_view name, glm::vec3 value) -> bool { + syncParams(); + return m_params.setColor(name, value); +} + +auto PostProcessVolume::setParamOption(std::string_view name, std::string_view option) -> bool { + syncParams(); + return m_params.setOption(name, option); +} + +auto PostProcessVolume::getParam(std::string_view name) const -> float { + syncParams(); + return m_params.number(name).value_or(0.0f); +} + +auto PostProcessVolume::getParamColor(std::string_view name) const -> glm::vec3 { + syncParams(); + return m_params.color(name).value_or(glm::vec3(0.0f)); +} + +auto PostProcessVolume::hasParam(std::string_view name) const -> bool { + syncParams(); + return m_params.layout()->find(name).has_value(); +} + +void PostProcessVolume::resetParams() { + // A version no profile reports forces the next sync to load again + m_synced_profile = nullptr; + m_synced_version = ~0u; + syncParams(); } auto PostProcessVolume::closestPointOnBounds(glm::vec3 point) const -> glm::vec3 { diff --git a/engine/src/toast/world/post_process_volume.hpp b/engine/src/toast/world/post_process_volume.hpp index f9f32dc0a..23dec3729 100644 --- a/engine/src/toast/world/post_process_volume.hpp +++ b/engine/src/toast/world/post_process_volume.hpp @@ -10,7 +10,8 @@ #include "volume.hpp" #include -#include +#include +#include namespace toast { @@ -49,11 +50,34 @@ class [[ToastNode, Icon("WorldEnvironment")]] TOAST_API PostProcessVolume : publ } /// @returns the grade this volume contributes, at full weight - /// - /// Rebuilt from the reflected fields on each call, so an inspector edit is visible on the next frame - /// without the node needing to know it was edited [[nodiscard]] - auto settings() const -> const renderer::PostProcessSettings&; + auto params() const -> const renderer::PostProcessParams&; + + /// @returns false when the name is unknown or not a scalar + [[Reflect]] + auto setParam(std::string_view name, float value) -> bool; + + [[Reflect]] + auto setParamColor(std::string_view name, glm::vec3 value) -> bool; + + /// Sets an enumeration by option name, like setParamOption("tonemap.mode", "ACES") + /// @returns false when the name is unknown, not an enumeration, or the option does not exist + [[Reflect]] + auto setParamOption(std::string_view name, std::string_view option) -> bool; + + /// @returns 0 when the name is unknown, see hasParam() + [[Reflect]] + auto getParam(std::string_view name) const -> float; + + /// @returns black when the name is unknown, see hasParam() + [[Reflect]] + auto getParamColor(std::string_view name) const -> glm::vec3; + + [[Reflect]] + auto hasParam(std::string_view name) const -> bool; + + [[Reflect]] + void resetParams(); /** * @brief How strongly this volume applies with the camera at @p camera_position @@ -89,139 +113,15 @@ class [[ToastNode, Icon("WorldEnvironment")]] TOAST_API PostProcessVolume : publ /// Volume supplies Is Global, Priority, Weight and Blend Distance; only the box shape is ours [[Reflect, Name("Extents"), Unit("m"), Group("Shape")]] alignas(16) glm::vec3 m_extents = glm::vec3(10.0f); - [[Reflect, Name("Bloom Threshold"), Range(0.0, 10.0), Group("Bloom")]] - float m_bloom_threshold = 1.0f; - [[Reflect, Name("Bloom Knee"), Range(0.0, 1.0), Group("Bloom")]] - float m_bloom_knee = 0.5f; - [[Reflect, Name("Bloom Filter Radius"), Range(0.0, 4.0), Group("Bloom")]] - float m_bloom_filter_radius = 1.0f; - [[Reflect, Name("Bloom Strength"), Range(0.0, 1.0), Group("Bloom")]] - float m_bloom_strength = 0.05f; - - [[Reflect, Name("Lens Flare Intensity"), Range(0.0, 2.0), Group("Lens Flare")]] - float m_lens_flare_intensity = 0.1f; - [[Reflect, Name("Lens Flare Threshold"), Range(0.0, 20.0), Group("Lens Flare")]] - float m_lens_flare_threshold = 1.0f; - [[Reflect, Name("Ghost Intensity"), Range(0.0, 4.0), Group("Lens Flare")]] - float m_ghost_intensity = 1.0f; - [[Reflect, Name("Halo Intensity"), Range(0.0, 4.0), Group("Lens Flare")]] - float m_halo_intensity = 1.0f; - [[Reflect, Name("Halo Radius"), Range(0.0, 2.0), Group("Lens Flare")]] - float m_halo_width = 0.6f; - [[Reflect, Name("Halo Fade Start"), Range(0.0, 1.0), Group("Lens Flare")]] - float m_halo_mask = 0.5f; - [[Reflect, Name("Halo Fisheye"), Range(0.05, 4.0), Group("Lens Flare")]] - float m_halo_compression = 0.65f; - [[Reflect, Name("Halo Thickness"), Range(0.0, 4.0), Group("Lens Flare")]] - float m_halo_thickness = 0.3f; - [[Reflect, Name("Halo Dispersion"), Range(0.0, 0.1), Group("Lens Flare")]] - float m_halo_dispersion = 0.015f; - [[Reflect, Name("Halo Tint"), Color, Group("Lens Flare")]] - glm::vec3 m_halo_tint = glm::vec3(1.0f); - [[Reflect, Name("Flare Chroma Shift"), Range(0.0, 0.1), Group("Lens Flare")]] - float m_flare_chroma_shift = 0.015f; - [[Reflect, Name("Threshold Range"), Range(0.01, 10.0), Group("Lens Flare")]] - float m_lens_flare_threshold_range = 1.0f; - [[Reflect, Name("Glare Divider"), Range(1.0, 200.0), Group("Lens Flare")]] - float m_glare_divider = 60.0f; - [[Reflect, Name("Glare Intensity"), Range(0.0, 2.0), Group("Lens Flare")]] - float m_glare_intensity = 0.2f; - [[Reflect, Name("Anamorphic Streak"), Range(0.0, 4.0), Group("Lens Flare")]] - float m_anamorphic_intensity = 1.0f; - [[Reflect, Name("Streak Blue Tint"), Range(0.0, 1.0), Group("Lens Flare")]] - float m_anamorphic_tint = 0.6f; - [[Reflect, Name("Lens Dirt"), Range(0.0, 2.0), Group("Lens Flare")]] - float m_dirt_intensity = 0.5f; - [[Reflect, Name("Lens Dirt Texture"), Group("Lens Flare")]] - assets::Handle m_lens_dirt_texture {nullptr}; - - [[Reflect, Name("Exposure"), Range(0.0, 8.0), Group("Tonemap")]] - float m_exposure = 1.0f; - /// Switches at the halfway point of a blend rather than interpolating - there is no curve in between - [[Reflect, Name("Tonemap Curve"), Enum("Reinhard", "ACES", "GT7"), Group("Tonemap")]] - int32_t m_tonemap_mode = 0; - /// GT7 toe exponent under the grey point, 1 is linear and higher darkens the shadows - [[Reflect, Name("GT7 Contrast Dip"), Range(1.0, 2.0), Group("Tonemap")]] - float m_gt_contrast_dip = 1.28f; - [[Reflect, Name("Chromatic Aberration"), Range(0.0, 0.05), Group("Tonemap")]] - float m_chromatic_aberration = 0.0f; - [[Reflect, Name("Gamma"), Range(1.0, 3.0), Group("Tonemap")]] - float m_gamma = 2.2f; - [[Reflect, Name("Contrast"), Range(0.0, 2.0), Group("Tonemap")]] - float m_contrast = 1.0f; - [[Reflect, Name("Saturation"), Range(0.0, 2.0), Group("Tonemap")]] - float m_saturation = 1.0f; - [[Reflect, Name("Vignette"), Range(0.0, 1.0), Group("Tonemap")]] - float m_vignette = 0.0f; - [[Reflect, Name("Film Grain"), Range(0.0, 1.0), Group("Tonemap")]] - float m_grain = 0.0f; - - /// Exposure above becomes a compensation on the metered value - [[Reflect, Name("Auto Exposure"), Group("Auto Exposure")]] - bool m_auto_exposure = false; - /// log2 of the average scene luminance so one step is one stop - [[Reflect, Name("Min Brightness"), Range(-16.0, 16.0), Group("Auto Exposure")]] - float m_auto_exposure_min = -8.0f; - [[Reflect, Name("Max Brightness"), Range(-16.0, 16.0), Group("Auto Exposure")]] - float m_auto_exposure_max = 4.0f; - /// Per second toward a brighter scene - [[Reflect, Name("Adapt Speed Up"), Range(0.0, 20.0), Group("Auto Exposure")]] - float m_adapt_speed_up = 3.0f; - [[Reflect, Name("Adapt Speed Down"), Range(0.0, 20.0), Group("Auto Exposure")]] - float m_adapt_speed_down = 1.0f; - - [[Reflect, Name("FXAA Contrast Threshold"), Range(0.0, 0.2), Group("FXAA")]] - float m_fxaa_contrast_threshold = 0.0312f; - [[Reflect, Name("FXAA Relative Threshold"), Range(0.0, 0.5), Group("FXAA")]] - float m_fxaa_relative_threshold = 0.125f; - [[Reflect, Name("FXAA Subpixel Blending"), Range(0.0, 1.0), Group("FXAA")]] - float m_fxaa_subpixel_blending = 0.75f; - - [[Reflect, Name("SSR Intensity"), Range(0.0, 2.0), Group("Screen Space Reflections")]] - float m_ssr_intensity = 1.0f; - [[Reflect, Name("SSR Max Roughness"), Range(0.0, 1.0), Group("Screen Space Reflections")]] - float m_ssr_max_roughness = 0.6f; - [[Reflect, Name("SSR Thickness"), Unit("m"), Range(0.01, 5.0), Group("Screen Space Reflections")]] - float m_ssr_thickness = 0.5f; - [[Reflect, Name("SSR Stride"), Unit("m"), Range(0.01, 1.0), Group("Screen Space Reflections")]] - float m_ssr_stride = 0.15f; - [[Reflect, Name("SSR Max Steps"), Range(1, 256), Group("Screen Space Reflections")]] - int32_t m_ssr_max_steps = 48; - - [[Reflect, Name("AO Radius"), Unit("m"), Range(0.01, 10.0), Group("Ambient Occlusion")]] - float m_ssao_radius = 0.5f; - [[Reflect, Name("AO Strength"), Range(0.0, 4.0), Group("Ambient Occlusion")]] - float m_ssao_strength = 1.0f; - [[Reflect, Name("AO Range Cutoff"), Unit("m"), Range(0.01, 10.0), Group("Ambient Occlusion")]] - float m_ssao_range_cutoff = 1.0f; - [[Reflect, Name("AO Samples"), Range(1, 64), Group("Ambient Occlusion")]] - int32_t m_ssao_sample_count = 16; - - /// 0 turns volumetrics off - [[Reflect, Name("Fog Density"), Unit("1/m"), Range(0.0, 1.0), Group("Fog")]] - float m_fog_density = 0.0f; - [[Reflect, Name("Fog Height"), Unit("m"), Range(-1000.0, 1000.0), Group("Fog")]] - float m_fog_height = 0.0f; - /// 0 is uniform fog - [[Reflect, Name("Fog Height Falloff"), Unit("1/m"), Range(0.0, 2.0), Group("Fog")]] - float m_fog_height_falloff = 0.0f; - [[Reflect, Name("Fog Albedo"), Color, Group("Fog")]] - glm::vec3 m_fog_albedo = glm::vec3(1.0f); - /// Above 0 scatters forward so shafts brighten toward the light - [[Reflect, Name("Fog Anisotropy"), Range(-0.9, 0.9), Group("Fog")]] - float m_fog_anisotropy = 0.3f; - [[Reflect, Name("Fog Ambient"), Range(0.0, 4.0), Group("Fog")]] - float m_fog_ambient = 1.0f; - [[Reflect, Name("Fog Distance"), Unit("m"), Range(1.0, 1000.0), Group("Fog")]] - float m_fog_distance = 64.0f; - - /// @brief Rebuilt from the reflected fields each time the renderer asks - /// - /// The fields are separate rather than a nested PostProcessSettings because reflection describes flat - /// members with their own range and group metadata, which is what gives the inspector usable sliders - mutable renderer::PostProcessSettings m_settings; + /// Empty grades with the schema defaults + [[Reflect, Name("Profile")]] + assets::Handle m_profile; + + void syncParams() const; - void syncSettings() const; + mutable renderer::PostProcessParams m_params; + mutable const assets::PostProcessProfile* m_synced_profile = nullptr; + mutable uint32_t m_synced_version = 0; /// Last value evaluateTarget() computed; see the note there for why the renderer bypasses it float m_influence = 0.0f; diff --git a/tests/postprocess/01-blend.cpp b/tests/postprocess/01-blend.cpp index ff1b886d3..c3095bdc1 100644 --- a/tests/postprocess/01-blend.cpp +++ b/tests/postprocess/01-blend.cpp @@ -2,56 +2,101 @@ #include #include -#include +#include +#include +#include namespace { +/// assert() is compiled out in release builds, and the writes must still happen there +void must(bool ok) { + assert(ok); + (void)ok; +} + auto near(float a, float b) -> bool { return std::fabs(a - b) < 1e-4f; } +auto coreSchemaLayout() -> std::shared_ptr { + std::ifstream file(std::string(TOAST_CORE_ASSETS_DIR) + "/schemas/post_process.schema.json"); + std::stringstream text; + text << file.rdbuf(); + const assets::Schema schema(text.str()); + assert(schema.isValid()); + return renderer::PostProcessParams::Layout::fromSchema(schema); +} + } -/// A volume's blend distance is only a visible fade if the fields actually interpolate; the integer ones -/// cannot, so they switch at the halfway point instead +/// A volume's blend distance is only a visible fade if the values actually interpolate; the ones that cannot +/// switch at the halfway point instead. The layout comes from the shipped schema, so this also proves the schema +/// parses and that its defaults still match the struct the passes fall back to TOAST_TEST_NAMED("postprocess", "postprocess/01-blend", test_postprocess_01_blend) { - renderer::PostProcessSettings target {}; - renderer::PostProcessSettings source {}; + using renderer::PostProcessParams; + const auto layout = coreSchemaLayout(); + assert(layout->slots.size() > 50); + + // Schema defaults are the struct defaults, so a missing profile and a missing schema grade the same + const renderer::PostProcessSettings fallback {}; + const auto defaults = PostProcessParams(layout).resolve(); + assert(near(defaults.bloom.strength, fallback.bloom.strength)); + assert(near(defaults.lens_flare.dirt_intensity, fallback.lens_flare.dirt_intensity)); + assert(near(defaults.lens_flare.halo_tint_g, fallback.lens_flare.halo_tint_g)); + assert(near(defaults.tonemap.gamma, fallback.tonemap.gamma)); + assert(defaults.tonemap.mode == fallback.tonemap.mode); + assert(defaults.ssr.max_steps == fallback.ssr.max_steps); + assert(defaults.ssao.sample_count == fallback.ssao.sample_count); + assert(near(defaults.fog.distance, fallback.fog.distance)); + assert(near(defaults.fog.albedo_b, fallback.fog.albedo_b)); - target.tonemap.exposure = 1.0f; - source.tonemap.exposure = 3.0f; - target.ssao.sample_count = 16; - source.ssao.sample_count = 32; - target.tonemap.mode = 0; - source.tonemap.mode = 1; + PostProcessParams target(layout); + PostProcessParams source(layout); + must(target.setNumber("tonemap.exposure", 1.0f)); + must(source.setNumber("tonemap.exposure", 3.0f)); + must(target.setNumber("ssao.sample_count", 16.0f)); + must(source.setNumber("ssao.sample_count", 32.0f)); + must(target.setOption("tonemap.mode", "Reinhard")); + must(source.setOption("tonemap.mode", "ACES")); + must(source.setColor("fog.albedo", {0.0f, 1.0f, 0.5f})); // Weight 0 leaves the target exactly as it was - a volume the camera cannot reach contributes nothing - renderer::PostProcessSettings zero = target; - renderer::blendPostProcess(zero, source, 0.0f); - assert(near(zero.tonemap.exposure, 1.0f)); - assert(zero.tonemap.mode == 0); + PostProcessParams zero = target; + zero.blend(source, 0.0f); + assert(near(zero.resolve().tonemap.exposure, 1.0f)); + assert(zero.resolve().tonemap.mode == 0); - // Half way is half way for a float - renderer::PostProcessSettings half = target; - renderer::blendPostProcess(half, source, 0.5f); - assert(near(half.tonemap.exposure, 2.0f)); - assert(half.ssao.sample_count == 24); + // Half way is half way for a float, and for a color + PostProcessParams half = target; + half.blend(source, 0.5f); + assert(near(half.resolve().tonemap.exposure, 2.0f)); + assert(half.resolve().ssao.sample_count == 24); + assert(near(half.resolve().fog.albedo_r, 0.5f)); // And the curve switches at exactly that point rather than landing between two curves that do not exist - assert(half.tonemap.mode == 1); + assert(half.resolve().tonemap.mode == 1); - renderer::PostProcessSettings just_under = target; - renderer::blendPostProcess(just_under, source, 0.49f); - assert(just_under.tonemap.mode == 0); + PostProcessParams just_under = target; + just_under.blend(source, 0.49f); + assert(just_under.resolve().tonemap.mode == 0); // Full weight replaces - renderer::PostProcessSettings full = target; - renderer::blendPostProcess(full, source, 1.0f); - assert(near(full.tonemap.exposure, 3.0f)); - assert(full.ssao.sample_count == 32); + PostProcessParams full = target; + full.blend(source, 1.0f); + assert(near(full.resolve().tonemap.exposure, 3.0f)); + assert(full.resolve().ssao.sample_count == 32); // Out-of-range weights are clamped rather than extrapolating past the source - renderer::PostProcessSettings over = target; - renderer::blendPostProcess(over, source, 4.0f); - assert(near(over.tonemap.exposure, 3.0f)); + PostProcessParams over = target; + over.blend(source, 4.0f); + assert(near(over.resolve().tonemap.exposure, 3.0f)); + + // Runtime writes are clamped to the schema range and refused for names or kinds that do not fit + must(target.setNumber("bloom.strength", 5.0f)); + assert(near(target.resolve().bloom.strength, 1.0f)); + assert(!target.setNumber("bloom.nonsense", 1.0f)); + assert(!target.setNumber("fog.albedo", 1.0f)); + assert(!target.setColor("bloom.strength", {1.0f, 1.0f, 1.0f})); + assert(!target.setOption("tonemap.mode", "Filmic")); + assert(target.number("bloom.strength").value_or(0.0f) == 1.0f); } From f017cda68adb58efa0b32dfd71f5b8a893640ff8 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 19:30:23 +0100 Subject: [PATCH 04/15] dlss and shit stuff like git locks fixes server is down --- .../nvidia-dlss/nvidia-dlss-config.cmake | 17 + cmake/vcpkg-ports/nvidia-dlss/portfile.cmake | 53 +++ cmake/vcpkg-ports/nvidia-dlss/vcpkg.json | 8 + editor/Git/GitLockGuard.cs | 23 +- editor/Workspace/WorkspaceViewModel.cs | 3 +- engine/CMakeLists.txt | 27 ++ engine/assets/shaders/motion_fill.slang | 53 +++ engine/assets/shaders/motion_fill.slang.meta | 4 + engine/assets/shaders/taa.slang | 110 +---- .../src/toast/renderer/core/vulkan_core.cpp | 46 +++ .../src/toast/renderer/core/vulkan_core.hpp | 15 + .../renderer/passes/debug/perf_window.cpp | 12 + .../passes/geometry/material_pass.cpp | 13 + .../passes/geometry/material_pass.hpp | 1 + .../renderer/passes/post/motion_fill.cpp | 145 +++++++ .../renderer/passes/post/motion_fill.hpp | 86 ++++ .../toast/renderer/passes/post/taa_pass.cpp | 136 ++++-- .../toast/renderer/passes/post/taa_pass.hpp | 26 +- .../renderer/resources/material_runtime.cpp | 9 +- .../renderer/resources/material_runtime.hpp | 2 + .../resources/post_process_target.cpp | 36 +- .../resources/post_process_target.hpp | 20 +- .../renderer/settings/renderer_settings.cpp | 12 + .../toast/renderer/upscale/dlss_upscaler.cpp | 389 ++++++++++++++++++ .../toast/renderer/upscale/dlss_upscaler.hpp | 109 +++++ engine/src/toast/renderer/vulkan_renderer.hpp | 50 +++ .../toast/renderer/vulkan_renderer_scene.cpp | 34 +- .../toast/renderer/vulkan_renderer_thread.cpp | 4 + engine/src/toast/world/workspace_voxel.cpp | 111 ++++- vcpkg.json | 9 + 30 files changed, 1413 insertions(+), 150 deletions(-) create mode 100644 cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake create mode 100644 cmake/vcpkg-ports/nvidia-dlss/portfile.cmake create mode 100644 cmake/vcpkg-ports/nvidia-dlss/vcpkg.json create mode 100644 engine/assets/shaders/motion_fill.slang create mode 100644 engine/assets/shaders/motion_fill.slang.meta create mode 100644 engine/src/toast/renderer/passes/post/motion_fill.cpp create mode 100644 engine/src/toast/renderer/passes/post/motion_fill.hpp create mode 100644 engine/src/toast/renderer/upscale/dlss_upscaler.cpp create mode 100644 engine/src/toast/renderer/upscale/dlss_upscaler.hpp diff --git a/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake b/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake new file mode 100644 index 000000000..21dc9af81 --- /dev/null +++ b/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake @@ -0,0 +1,17 @@ +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 + 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" + ) +endif() + +set(NVIDIA_DLSS_RUNTIME_DLL "${_nvidia_dlss_prefix}/bin/nvngx_dlss.dll") +unset(_nvidia_dlss_prefix) diff --git a/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake new file mode 100644 index 000000000..fd78342bb --- /dev/null +++ b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake @@ -0,0 +1,53 @@ +# Binary SDK, every file comes straight from the tagged NVIDIA/DLSS tree and is pinned by its hash +set(_dlss_files + include/nvsdk_ngx.h 007f56bdddd85d8fdc1da81022137afb302bb1c0dba63b5e36f044b63f4d10858bff5f21d80e0d46d156ed34847cca92ec4830deb6ee1424091fbd1a5f4336ed + include/nvsdk_ngx_defs.h 605bbd1465c356516ce02903775306ba61d65a08ec4ba21823dd55486ab71bd75cc15680562946990ba1cc4a7ac1ba78a00c46e8951c9cd3b7565fb4e6f3ee3f + include/nvsdk_ngx_defs_dlssd.h 31d1ba8c8c3abd4601ef34d38f84648ca822226be3fd12e730a7625899f5ce4b137da1b1f90710d17109c886c1868f1d9d51f2498d31df1f508c9b2fda6c06ba + include/nvsdk_ngx_defs_dlssg.h 14ab4cf01c33c52b22f7fb01710913ef40803e47629e2e6af0093f1134ad94dcc4c5ad9d3c85cd81d16d387d9b115937906edbeacfc72f98e3c318e6737b9154 + include/nvsdk_ngx_defs_vk.h 288f450317a64fa92e47e8e54b4981506d1bad6854d41d5b742aabf7536ad9d6240c62faab895b8b2763ce917762899cf267e3f2b1db12b4b5e7bd0364bf4919 + include/nvsdk_ngx_helpers.h 19f9f8c078ed310606aba35405b6b14f3ae4fa2f8c22dfecef3ff193a0498a2ce27a977a6e95287f17447886dea174a1bbfa3f9a9b766943f7bd7dd59ed0c64f + include/nvsdk_ngx_helpers_cuda.h 79b5f682f89f9937ee5598b13cfe957afb459c3c1e48879376806c5fe2c0c82e8d78b6b49765cbc69ad871acf62bc2e563984f21770e21541eef07775b582119 + include/nvsdk_ngx_helpers_d3d.h 274724bf280738a3b3857028c9cea137a92035f14feb2038f9620287d91ba7c0164bf08502b53d60c871c64be6842cbf45618cf925276a698c26dfc88e01c266 + include/nvsdk_ngx_helpers_dlssd.h f845cdfcea7f0b635ae628cf697ea9c3032f4e8fb9ce87f52b3a057fb0303b18ca00733599aa393edb451cf9faf3ddf335bb90bc5571c3d641d5163692310289 + include/nvsdk_ngx_helpers_dlssd_cuda.h 2339c07310350ba5f6a53332d98078b648571e6850d0b7605c3723c9e3d68be75dd153de1d6b2db168d7aa0b0c38b7a55fc17bc42f79ec96e6cd8f36a2eb9e71 + include/nvsdk_ngx_helpers_dlssd_d3d.h db7371481d2f8577fe3e2696eb9d904d7ce7b42dd10ff4523fb4f58f722d22baf1e27d447b13d01761d72f969435508611171e1bfad4200edfbe38c7d65870da + include/nvsdk_ngx_helpers_dlssd_vk.h 338c82cb435304c66585cf3fccd98279d7bf997156b35ff6e8cc95eed6a5ff8a68c0a6b475e7d452811a5649a5fc43776b4029584bb48db48fd1f0ec6f6b4070 + include/nvsdk_ngx_helpers_dlssg.h 59d049ad2ecb8c7ce7573624118871ae709fab3c4944941b5273810ebe715aed0e66cc9d44eec5c3c9238d9d95249e4727407859818ba7e5b821ef851fab3fd7 + include/nvsdk_ngx_helpers_dlssg_d3d.h c549728b24ccea6865e20bde54ca2fb0d2f486a1e941c27fe7516450ab15de1bd7d5d0a675fc2b4d90e37178dbea2d25b9bca76e25f19afe7a6374e20eeef77a + include/nvsdk_ngx_helpers_dlssg_vk.h 00db89e091cf8203e702089611ffe8474359b3125f481523ab3d2a813f105756f1014dcff26aa507519bd7640368adae793dac8fe42ac532a043c9df4a926239 + include/nvsdk_ngx_helpers_vk.h 8051906d9baec8440cfeed0c6b2380cb269622b0a5ece8376e661e22531ade91ae807b4810081cdf4e56dd4aaab1c7a44e0f2eb004be5ef7f572eca10a68307a + include/nvsdk_ngx_loader.h a4661533cccad7db70d589741c0e3c4a8e318c15e9dab5f88cc763f51ae8b959117b11f417d26f1b4b334a25cbeffaf2db24ed0a43b9264b50b42fe1fdcf0302 + include/nvsdk_ngx_params.h f8b58c7e42f1948d17de5dad5c25d8341b5cf5dcb160de06de48fa2ef12ae98171e2aba8e3bd7a8e3b5321937c15f9edce7dd6aafc4dbd3588c946247322d2a4 + include/nvsdk_ngx_params_dlssd.h d9ddbdbe0ba2f3624daf41dcf3185400ee034e7e0a057df4f9080b63bfd8ce074ef0024f34a80aa4b8c15d163fdbeeabca3da319be681dd06e27311cab2c2a53 + include/nvsdk_ngx_params_dlssg.h b446b2594b478cc31fa0d542ee00d83969690075c9c75e8341fc85a3bdad6cad252d52ccaa4ae34f4d673e16f6316bed6ceb69dea1f0085745cd4f758d563dc4 + 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 +) + +while(_dlss_files) + list(POP_FRONT _dlss_files _path _sha512) + get_filename_component(_leaf "${_path}" NAME) + string(REPLACE "/" "-" _name "${_path}") + vcpkg_download_distfile("_dlss_${_leaf}" + URLS "https://raw.githubusercontent.com/NVIDIA/DLSS/v${VERSION}/${_path}" + FILENAME "nvidia-dlss-${VERSION}-${_name}" + SHA512 ${_sha512} + ) + if(_path MATCHES "^include/") + file(INSTALL "${_dlss_${_leaf}}" DESTINATION "${CURRENT_PACKAGES_DIR}/include/ngx" RENAME "${_leaf}") + 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") + +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 new file mode 100644 index 000000000..4e270e176 --- /dev/null +++ b/cmake/vcpkg-ports/nvidia-dlss/vcpkg.json @@ -0,0 +1,8 @@ +{ + "name": "nvidia-dlss", + "version-string": "310.9.16", + "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" +} diff --git a/editor/Git/GitLockGuard.cs b/editor/Git/GitLockGuard.cs index 48076ff69..9ae50a3ef 100644 --- a/editor/Git/GitLockGuard.cs +++ b/editor/Git/GitLockGuard.cs @@ -19,6 +19,13 @@ public enum OpenLockKind { public static class GitLockGuard { private static GitService? Usable => GitService.Current is { IsAvailable: true, HasLfs: true } git ? git : null; + private static readonly TimeSpan s_serverWait = TimeSpan.FromSeconds(8); + + // false when the lock server did not answer in time; the git call keeps running in the background + private static async Task WithinAsync(Task work) { + return await Task.WhenAny(work, Task.Delay(s_serverWait)) == work; + } + public static async Task LockOnOpenAsync(string realPath) { await AcquireOnOpenAsync(realPath); } @@ -28,8 +35,9 @@ public static async Task AcquireOnOpenAsync(string realPath) { var held = git.GetLock(realPath); if (held is null) { - var result = await git.LockAsync(realPath); - if (!result.Ok) Log.Warn($"Git: could not lock {Path.GetFileName(realPath)} on open ({result.Message})"); + var lockTask = git.LockAsync(realPath); + if (!await WithinAsync(lockTask)) Log.Warn($"Git: lock server too slow, opened {Path.GetFileName(realPath)} without a lock"); + else if (!(await lockTask).Ok) Log.Warn($"Git: could not lock {Path.GetFileName(realPath)} on open ({(await lockTask).Message})"); held = git.GetLock(realPath); } @@ -46,7 +54,14 @@ public static async Task CheckSaveAsync(string realPath) { if (held is null) { if (!git.IsLockable(realPath)) return LockedSaveChoice.Proceed; - var result = await git.LockAsync(realPath); + var lockTask = git.LockAsync(realPath); + // A hung server keeps Save disabled until the command ends, so never wait long on it + if (!await WithinAsync(lockTask)) { + Log.Warn($"Git: lock server too slow, saving {Path.GetFileName(realPath)} without a lock"); + return LockedSaveChoice.Proceed; + } + + var result = await lockTask; if (result.Ok) return LockedSaveChoice.Proceed; // The cached locks may be old @@ -60,7 +75,7 @@ public static async Task CheckSaveAsync(string realPath) { if (held.OwnedByMe) return LockedSaveChoice.Proceed; } else { // It may have been released since the last poll - await git.RefreshLocksAsync(); + await WithinAsync(git.RefreshLocksAsync()); // on timeout the cached lock stands held = git.GetLock(realPath); if (held is null) return await CheckSaveAsync(realPath); if (held.OwnedByMe) return LockedSaveChoice.Proceed; diff --git a/editor/Workspace/WorkspaceViewModel.cs b/editor/Workspace/WorkspaceViewModel.cs index fa81601ee..21026f2c2 100644 --- a/editor/Workspace/WorkspaceViewModel.cs +++ b/editor/Workspace/WorkspaceViewModel.cs @@ -248,7 +248,8 @@ private void OnSaveCompleted(WorkspaceSaveCompleted completed) { } private async Task SaveNativeAsync(string target, string path) { - if (m_pendingSave is not null) return false; + // A closed tab dropped its listener, so the completion would never arrive and Save would stay disabled forever + if (m_disposed || m_pendingSave is not null) return false; var request = m_nextSaveRequest++; m_pendingSaveRequest = request; m_pendingSave = diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 587af4228..ee1d6105c 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -138,6 +138,28 @@ 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 +include(CMakeDependentOption) +cmake_dependent_option(TOAST_DLSS "NVIDIA DLSS" ON "WIN32;ARCH STREQUAL x86_64" OFF) +if (TOAST_DLSS) + find_package(nvidia-dlss CONFIG QUIET) + if (nvidia-dlss_FOUND) + target_link_libraries(toast_engine PRIVATE nvidia::dlss) + target_compile_definitions(toast_engine PRIVATE TOAST_DLSS=1) + # The vcpkg DLL glob below only covers the manifest tree, a package found through CMAKE_PREFIX_PATH needs this + # The runtime's license has to ship with it, the port installs it as share/nvidia-dlss/copyright + get_filename_component(_nvidia_dlss_license "${NVIDIA_DLSS_RUNTIME_DLL}/../../share/nvidia-dlss/copyright" ABSOLUTE) + add_custom_command(TARGET toast_engine POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${NVIDIA_DLSS_RUNTIME_DLL}" "${TOAST_ENGINE_BIN_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_nvidia_dlss_license}" "${TOAST_ENGINE_BIN_DIR}/NVIDIA_DLSS_LICENSE.txt" + COMMENT "Copying the DLSS runtime" + VERBATIM + ) + else () + message(STATUS "TOAST_DLSS: nvidia-dlss package not found, building without DLSS") + endif () +endif () + if (WIN32) target_compile_definitions(toast_engine PRIVATE NOMINMAX) target_link_libraries(toast_engine PRIVATE ole32 uuid comctl32 d3d11 dxgi) @@ -301,6 +323,11 @@ if (WIN32) set(_vcpkg_prefix "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}") file(GLOB _vcpkg_dlls_debug CONFIGURE_DEPENDS "${_vcpkg_prefix}/debug/bin/*.dll") file(GLOB _vcpkg_dlls_release CONFIGURE_DEPENDS "${_vcpkg_prefix}/bin/*.dll") + # The manifest always installs nvidia-dlss, so a build without DLSS must not ship its runtime + if (NOT TOAST_DLSS OR NOT nvidia-dlss_FOUND) + list(FILTER _vcpkg_dlls_debug EXCLUDE REGEX "/nvngx_dlss\\.dll$") + list(FILTER _vcpkg_dlls_release EXCLUDE REGEX "/nvngx_dlss\\.dll$") + endif () add_custom_command(TARGET toast_engine POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different $ diff --git a/engine/assets/shaders/motion_fill.slang b/engine/assets/shaders/motion_fill.slang new file mode 100644 index 000000000..c75fdff39 --- /dev/null +++ b/engine/assets/shaders/motion_fill.slang @@ -0,0 +1,53 @@ +// Gives every texel a motion vector so the temporal resolve and upscalers never need their own depth reprojection +// Written motion is kept and the rest is rebuilt from depth + +/// Mirrors renderer::MotionFill::Push +struct MotionFillParams +{ + // Current unjittered clip to previous clip + float4x4 reprojection; + uint2 size; + // 1 rebuilds every texel since written motion is stale after skipped frames + uint ignoreWritten; +}; + +[[vk::push_constant]] +ConstantBuffer gParams; + +[[vk::binding(0, 0)]] +Sampler2D gDepth; + +[[vk::binding(1, 0)]] +Sampler2D gMotion; + +/// xy current minus previous uv, z reactive, w 1 when the scene wrote it +[[vk::binding(2, 0)]] +[[vk::image_format("rgba16f")]] +RWTexture2D gFilledMotion; + +[[vk::binding(3, 0)]] +[[vk::image_format("r8")]] +RWTexture2D gReactive; + +[shader("compute")] +[numthreads(8, 8, 1)] +void computeMain(uint3 id : SV_DispatchThreadID) +{ + if (any(id.xy >= gParams.size)) + { + return; + } + + const float2 uv = (float2(id.xy) + 0.5) / float2(gParams.size); + float4 motion = gMotion.SampleLevel(uv, 0.0); + + if (motion.w < 0.5 || gParams.ignoreWritten != 0u) + { + const float depth = gDepth.SampleLevel(uv, 0.0).r; + const float4 previousClip = mul(gParams.reprojection, float4(uv * 2.0 - 1.0, depth, 1.0)); + motion.xy = uv - (previousClip.xy / previousClip.w * 0.5 + 0.5); + } + + gFilledMotion[id.xy] = motion; + gReactive[id.xy] = saturate(motion.z); +} diff --git a/engine/assets/shaders/motion_fill.slang.meta b/engine/assets/shaders/motion_fill.slang.meta new file mode 100644 index 000000000..7885ac174 --- /dev/null +++ b/engine/assets/shaders/motion_fill.slang.meta @@ -0,0 +1,4 @@ +uid = "m0t10nF1ll3" +type = "shader" +created_at = "2026-11-22T12:00:00.0000000Z" +modified_at = "2026-11-22T12:00:00.0000000Z" diff --git a/engine/assets/shaders/taa.slang b/engine/assets/shaders/taa.slang index 7cdce811d..3da8d1784 100644 --- a/engine/assets/shaders/taa.slang +++ b/engine/assets/shaders/taa.slang @@ -3,16 +3,14 @@ import depth_convention; struct TaaParams { - // Current unjittered clip to previous clip when motion is not written - float4x4 reprojection; // xy 1 over size zw size float4 texel; - // x history weight y 1 resets history z 1 ignores written motion w 1 draws the motion debug view + // x history weight y 1 resets history z unused w 1 draws the motion debug view float4 tuning; // xy render size zw jitter in uv float4 source; - // x 1 when the source is smaller than the output - float4 upscale; + // x output pixels of motion at which the history weight halves + float4 adapt; }; [[vk::push_constant]] @@ -113,7 +111,7 @@ float3 motionColor(float4 motion) } /// Jitter aware Gaussian of the render texels around this output pixel -float4 resolveUpscaled(float2 uv) +float4 resolve(float2 uv) { const float2 renderSize = gParams.source.xy; const float2 renderTexel = 1.0 / renderSize; @@ -165,16 +163,7 @@ float4 resolveUpscaled(float2 uv) return float4(motionColor(motion), 1.0); } - float2 previousUv; - if (motion.w > 0.5 && gParams.tuning.z < 0.5) - { - previousUv = uv - motion.xy; - } - else - { - const float4 previousClip = mul(gParams.reprojection, float4(closestUv * 2.0 - 1.0, closestDepth, 1.0)); - previousUv = uv + previousClip.xy / previousClip.w * 0.5 + 0.5 - closestUv; - } + const float2 previousUv = uv - motion.xy; const bool offscreen = any(previousUv < float2(0.0, 0.0)) || any(previousUv > float2(1.0, 1.0)); [branch] @@ -187,7 +176,10 @@ float4 resolveUpscaled(float2 uv) const float3 sigma = sqrt(max(moment2 / 9.0 - mean * mean, float3(0.0, 0.0, 0.0))); const float3 history = clipToBox(toYCoCg(compress(sampleHistory(previousUv))), mean - sigma, mean + sigma); - const float currentWeight = (1.0 - gParams.tuning.x * (1.0 - saturate(motion.z))) * nearest; + // Fast motion trusts the history less since its reprojection is least reliable + const float speedPx = length(motion.xy * gParams.texel.zw); + const float historyWeight = gParams.tuning.x * gParams.adapt.x / (gParams.adapt.x + speedPx); + const float currentWeight = (1.0 - historyWeight * (1.0 - saturate(motion.z))) * nearest; float3 resolved = lerp(history, filtered, currentWeight); if (any(isnan(resolved))) { @@ -199,87 +191,5 @@ float4 resolveUpscaled(float2 uv) [shader("fragment")] float4 fragmentMain(VSOutput input) : SV_Target0 { - float2 uv = input.uv; - float2 texel = gParams.texel.xy; - - [branch] - if (gParams.upscale.x > 0.5) - { - return resolveUpscaled(uv); - } - - float3 center = float3(0.0, 0.0, 0.0); - float3 moment1 = float3(0.0, 0.0, 0.0); - float3 moment2 = float3(0.0, 0.0, 0.0); - float closestDepth = kFarDepth; - float2 closestUv = uv; - - [unroll] - for (int y = -1; y <= 1; ++y) - { - [unroll] - for (int x = -1; x <= 1; ++x) - { - float2 sampleUv = uv + float2(x, y) * texel; - float3 value = toYCoCg(compress(gCurrent.SampleLevel(sampleUv, 0.0).rgb)); - moment1 += value; - moment2 += value * value; - if (x == 0 && y == 0) - { - center = value; - } - - // Cross pattern for the closest depth saves four fetches - if (abs(x) + abs(y) <= 1) - { - float depth = gDepth.SampleLevel(sampleUv, 0.0).r; - if (isCloserDepth(depth, closestDepth)) - { - closestDepth = depth; - closestUv = sampleUv; - } - } - } - } - - float4 motion = gMotion.SampleLevel(closestUv, 0.0); - - [branch] - if (gParams.tuning.w > 0.5) - { - return float4(motionColor(motion), 1.0); - } - - float2 previousUv; - if (motion.w > 0.5 && gParams.tuning.z < 0.5) - { - previousUv = uv - motion.xy; - } - else - { - float4 previousClip = mul(gParams.reprojection, float4(closestUv * 2.0 - 1.0, closestDepth, 1.0)); - previousUv = uv + previousClip.xy / previousClip.w * 0.5 + 0.5 - closestUv; - } - - bool offscreen = any(previousUv < float2(0.0, 0.0)) || any(previousUv > float2(1.0, 1.0)); - [branch] - if (gParams.tuning.y > 0.5 || offscreen) - { - return float4(expand(fromYCoCg(center)), 1.0); - } - - float3 mean = moment1 / 9.0; - float3 sigma = sqrt(max(moment2 / 9.0 - mean * mean, float3(0.0, 0.0, 0.0))); - float3 history = toYCoCg(compress(sampleHistory(previousUv))); - history = clipToBox(history, mean - sigma, mean + sigma); - - float historyWeight = gParams.tuning.x * (1.0 - saturate(motion.z)); - float3 resolved = lerp(center, history, historyWeight); - - // A NaN would otherwise live in the history until the next reset - if (any(isnan(resolved))) - { - resolved = center; - } - return float4(expand(fromYCoCg(resolved)), 1.0); + return resolve(input.uv); } diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index 7a0ecdfb0..35f1f3aaa 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -5,6 +5,7 @@ #include "toast/renderer/core/vulkan_core.hpp" #include "toast/renderer/shaders/shader_compiler.hpp" +#include "toast/renderer/upscale/dlss_upscaler.hpp" #include #include @@ -271,6 +272,12 @@ auto selectQueueFamilies(const vk::PhysicalDevice& device) -> QueueFamilySelecti return selection; } +void appendExtension(std::vector& extensions, const char* name) { + if (std::ranges::none_of(extensions, [name](const char* enabled) { return std::string_view(enabled) == name; })) { + extensions.push_back(name); + } +} + auto joinRequiredExtensions(std::span extensions) -> std::string { std::string out; for (size_t i = 0; i < extensions.size(); ++i) { @@ -457,6 +464,21 @@ void VulkanCore::createInstance(std::span required_instance_e extensions.push_back(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME); } + // Requested on every GPU since vkCreateInstance runs before the device is picked; the device step drops DLSS off NVIDIA + m_dlss_reason.clear(); + const auto dlss_extensions = DlssUpscaler::instanceExtensions(); + for (const char* name : dlss_extensions) { + if (!checkInstanceExtensionSupport(name)) { + m_dlss_reason = std::format("the Vulkan loader lacks instance extension {}", name); + break; + } + } + if (m_dlss_reason.empty()) { + for (const char* name : dlss_extensions) { + appendExtension(extensions, name); + } + } + vk::InstanceCreateInfo instance_ci({}, &app_info, layers, extensions); #ifdef TOAST_SYNC_VALIDATION @@ -958,6 +980,30 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re } } + if (m_dlss_reason.empty()) { + constexpr uint32_t k_vendor_nvidia = 0x10DE; + const auto props = m_physical_device.getProperties(); + if (props.vendorID != k_vendor_nvidia) { + m_dlss_reason = std::format("{} is not an NVIDIA GPU", props.deviceName.data()); + } else { + const auto available = m_physical_device.enumerateDeviceExtensionProperties(); + const auto dlss_extensions = DlssUpscaler::deviceExtensions(*m_instance, *m_physical_device); + const auto missing = std::ranges::find_if(dlss_extensions, [&available](std::string_view name) { + return std::ranges::none_of(available, [name](const vk::ExtensionProperties& ext) { + return std::string_view(ext.extensionName.data()) == name; + }); + }); + if (missing != dlss_extensions.end()) { + m_dlss_reason = std::format("the device lacks extension {}", *missing); + } else { + for (const char* name : dlss_extensions) { + appendExtension(device_extensions, name); + } + } + } + } + m_dlss_extensions_enabled = m_dlss_reason.empty(); + vk::DeviceCreateInfo device_ci({}, queue_create_infos, {}, device_extensions, &enabled_features); vk::PhysicalDeviceMeshShaderFeaturesEXT mesh_shader_features {}; diff --git a/engine/src/toast/renderer/core/vulkan_core.hpp b/engine/src/toast/renderer/core/vulkan_core.hpp index 10f6c6f93..11d6e9efc 100644 --- a/engine/src/toast/renderer/core/vulkan_core.hpp +++ b/engine/src/toast/renderer/core/vulkan_core.hpp @@ -140,6 +140,18 @@ class VulkanCore { return m_fragment_shading_rate_supported; } + /// Every instance and device extension NGX asked for is enabled, DlssUpscaler still has to initialise NGX + [[nodiscard]] + auto dlssExtensionsEnabled() const noexcept -> bool { + return m_dlss_extensions_enabled; + } + + /// Why the NGX extensions were left out + [[nodiscard]] + auto dlssReason() const noexcept -> std::string_view { + return m_dlss_reason; + } + [[nodiscard]] auto isDepthClampSupported() const noexcept -> bool { return m_depth_clamp_supported; @@ -321,6 +333,9 @@ class VulkanCore { uint32_t m_mesh_multiview_views = 0; + bool m_dlss_extensions_enabled = false; + std::string m_dlss_reason = "not probed"; + bool m_depth_clamp_supported = false; bool m_dual_source_blend_supported = false; bool m_sampler_anisotropy_supported = false; diff --git a/engine/src/toast/renderer/passes/debug/perf_window.cpp b/engine/src/toast/renderer/passes/debug/perf_window.cpp index a32f1a969..b7cd9ebad 100644 --- a/engine/src/toast/renderer/passes/debug/perf_window.cpp +++ b/engine/src/toast/renderer/passes/debug/perf_window.cpp @@ -1214,6 +1214,17 @@ void PerfWindow::drawQualityTab() { const vk::Extent2D render = renderer->renderExtent(); const vk::Extent2D output = renderer->getOutputTarget().getExtent(); ImGui::TextDisabled("%ux%u of %ux%u", render.width, render.height, output.width, output.height); + + const std::string dlss_reason = renderer->dlssFailureReason(); + if (renderer->dlssActive()) { + ImGui::TextDisabled("AA: DLSS"); + } else if (!renderer->taaEnabled()) { + ImGui::TextDisabled("AA: off"); + } else if (!dlss_reason.empty()) { + ImGui::TextDisabled("AA: TAA (DLSS unavailable: %s)", dlss_reason.c_str()); + } else { + ImGui::TextDisabled("AA: TAA"); + } } ImGui::SeparatorText(custom ? "Preset Custom" : "Set by the preset, editing one switches to Custom"); @@ -1245,6 +1256,7 @@ void PerfWindow::drawQualityTab() { "##perf_quality_always", {"renderer.quality.bloom", "renderer.quality.taa", + "renderer.quality.antialiasing", "renderer.quality.taa_history", "renderer.quality.fxaa", "renderer.quality.lens_flare", diff --git a/engine/src/toast/renderer/passes/geometry/material_pass.cpp b/engine/src/toast/renderer/passes/geometry/material_pass.cpp index 73b84871e..a0bfaa44a 100644 --- a/engine/src/toast/renderer/passes/geometry/material_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/material_pass.cpp @@ -253,6 +253,19 @@ void MaterialPass::update(uint32_t frame_index, float dt) { res.runtime->markValuesDirty(); } } + + // Samplers are baked per slot so a bias change rebakes them and rewrites every set + if (m_built != nullptr) { + if (const float bias = VulkanRenderer::instance->materialMipBias(); bias != m_last_mip_bias) { + m_last_mip_bias = bias; + for (auto& [material, res] : m_built->instances) { + res.runtime->markTexturesDirty(); + for (auto& views : res.bound_views) { + views.assign(views.size(), InstanceResources::BoundView {}); + } + } + } + } } void MaterialPass::finishPendingBuild() { diff --git a/engine/src/toast/renderer/passes/geometry/material_pass.hpp b/engine/src/toast/renderer/passes/geometry/material_pass.hpp index f654557de..a0ec3e6f7 100644 --- a/engine/src/toast/renderer/passes/geometry/material_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/material_pass.hpp @@ -160,6 +160,7 @@ class MaterialPass : public IRenderPass { std::atomic_bool m_rebuild_pending {false}; std::atomic_bool m_values_dirty {false}; + float m_last_mip_bias = 0.0f; }; } diff --git a/engine/src/toast/renderer/passes/post/motion_fill.cpp b/engine/src/toast/renderer/passes/post/motion_fill.cpp new file mode 100644 index 000000000..3fada93d5 --- /dev/null +++ b/engine/src/toast/renderer/passes/post/motion_fill.cpp @@ -0,0 +1,145 @@ +/** + * @file motion_fill.cpp + * @author dario + * @date 22/11/2026 + */ + +#include "toast/renderer/passes/post/motion_fill.hpp" + +#include "toast/renderer/core/descriptor_writer.hpp" +#include "toast/renderer/shaders/shader_cache.hpp" +#include "toast/renderer/vulkan_renderer.hpp" + +namespace renderer { + +namespace { + +constexpr uint32_t k_group_size = 8; + +} + +MotionFill::MotionFill(const VulkanCore& core, vk::Extent2D render_extent) : m_core(&core), m_extent(render_extent) { + ZoneScoped; + static_assert(sizeof(Push) <= 128, "Vulkan guarantees 128 bytes of push constants"); + + const auto uid = assets::resolveURI("core://shaders/motion_fill.slang"); + const auto shader = uid.has_value() ? ShaderCache::get().acquire(*uid) : nullptr; + if (!shader) { + TOAST_ERROR("Render", "MotionFill shader core://shaders/motion_fill.slang unavailable; motion fill is disabled"); + return; + } + + m_shader_layout.rebuild(core, shader->reflection, "MotionFill"); + const auto& layouts = m_shader_layout.getDescriptorSetLayouts(); + if (layouts.empty()) { + TOAST_ERROR("Render", "MotionFill shader layout has no descriptor sets"); + return; + } + + VulkanPipeline::Config config; + config.pipeline_type = VulkanPipeline::PipelineType::compute; + config.debug_name = "MotionFill"; + config.shader_spirv = shader->spirv; + config.pipeline_layout = *m_shader_layout.getPipelineLayout(); + m_pipeline.rebuild(core, config); + + // Nearest since texel-exact reads must not blend across edges + m_point_sampler = vk::raii::Sampler(core.getDevice(), nearestClampSamplerInfo()); + setDebugName(core, *m_point_sampler, "MotionFill Sampler"); + + const vk::DescriptorSetLayout set_layout = *layouts[0]; + const vk::DescriptorPool pool = VulkanRenderer::instance->getDescriptorPoolHandle(); + m_bound_views.resize(VulkanRenderer::k_frames_in_flight); + for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { + auto allocated = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &set_layout)); + m_descriptor_sets.push_back(std::move(allocated[0])); + setDebugName(core, *m_descriptor_sets[i], std::format("MotionFill DescriptorSet[{}]", i)); + } + + onResize(render_extent); +} + +void MotionFill::createTarget(Target& target, vk::Format format, std::string_view debug_name) const { + // View before the image it views + target.view.reset(); + target.image.reset(); + target.state = {}; + + const auto image_ci = colorTargetImageInfo(m_extent, format, vk::ImageUsageFlagBits::eStorage); + vma::AllocationCreateInfo allocation_ci {}; + allocation_ci.usage = vma::MemoryUsage::eAutoPreferDevice; + target.image.emplace(m_core->getAllocator().createImage(image_ci, allocation_ci)); + setDebugName(*m_core, **target.image, std::format("{} Image", debug_name)); + target.state.reset(**target.image, colorSubresourceRange()); + + vk::ImageViewCreateInfo view_ci {}; + view_ci.image = **target.image; + view_ci.viewType = vk::ImageViewType::e2D; + view_ci.format = format; + view_ci.subresourceRange = colorSubresourceRange(); + target.view.emplace(m_core->getDevice(), view_ci); + setDebugName(*m_core, **target.view, std::format("{} View", debug_name)); +} + +void MotionFill::onResize(vk::Extent2D render_extent) { + ZoneScoped; + if (m_core == nullptr || !m_pipeline.isReady()) { + return; + } + m_extent = render_extent; + createTarget(m_motion, vk::Format::eR16G16B16A16Sfloat, "MotionFill Motion"); + createTarget(m_reactive, vk::Format::eR8Unorm, "MotionFill Reactive"); + m_bound_views.invalidate(); +} + +auto MotionFill::record(vk::CommandBuffer cmd, uint32_t frame_index, const glm::mat4& reprojection, bool ignore_written) -> bool { + ZoneScoped; + const vk::ImageView depth_view = VulkanRenderer::instance->getDepthView(); + const vk::ImageView scene_motion = VulkanRenderer::instance->getSceneMotionView(); + if (!m_pipeline.isReady() || frame_index >= m_descriptor_sets.size() || !m_motion.view || !m_reactive.view || !depth_view || + !scene_motion) { + return false; + } + + // The renderer already made depth and scene motion sampleable by compute before the post passes + sync::BarrierBatch barriers; + barriers.image(m_motion.state, sync::Usage::compute_storage_write); + barriers.image(m_reactive.state, sync::Usage::compute_storage_write); + barriers.flush(cmd); + + const std::array wanted {depth_view, scene_motion, **m_motion.view, **m_reactive.view}; + if (m_bound_views.update(frame_index, wanted)) { + const vk::DescriptorSet set = *m_descriptor_sets[frame_index]; + DescriptorWriter writer; + // Depth stays eDepthReadOnlyOptimal for the overlay stage + writer.image( + set, 0, vk::DescriptorType::eCombinedImageSampler, *m_point_sampler, depth_view, vk::ImageLayout::eDepthReadOnlyOptimal + ); + writer.image( + set, 1, vk::DescriptorType::eCombinedImageSampler, *m_point_sampler, scene_motion, vk::ImageLayout::eShaderReadOnlyOptimal + ); + writer.image(set, 2, vk::DescriptorType::eStorageImage, nullptr, **m_motion.view, vk::ImageLayout::eGeneral); + writer.image(set, 3, vk::DescriptorType::eStorageImage, nullptr, **m_reactive.view, vk::ImageLayout::eGeneral); + writer.flush(m_core->getDevice()); + } + + Push push {}; + push.reprojection = reprojection; + push.width = m_extent.width; + push.height = m_extent.height; + push.ignore_written = ignore_written ? 1u : 0u; + + const vk::PipelineLayout layout = *m_shader_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, m_pipeline.getPipeline()); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, layout, 0, std::array {*m_descriptor_sets[frame_index]}, {}); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(Push), &push); + cmd.dispatch((m_extent.width + k_group_size - 1) / k_group_size, (m_extent.height + k_group_size - 1) / k_group_size, 1); + + // Fragment and compute readers both sample these later + barriers.image(m_motion.state, sync::Usage::shader_sampled); + barriers.image(m_reactive.state, sync::Usage::shader_sampled); + barriers.flush(cmd); + return true; +} + +} diff --git a/engine/src/toast/renderer/passes/post/motion_fill.hpp b/engine/src/toast/renderer/passes/post/motion_fill.hpp new file mode 100644 index 000000000..9bd3d59c7 --- /dev/null +++ b/engine/src/toast/renderer/passes/post/motion_fill.hpp @@ -0,0 +1,86 @@ +/** + * @file motion_fill.hpp + * @author dario + * @date 22/11/2026 + */ + +#pragma once + +#include "toast/renderer/core/descriptor_cache.hpp" +#include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/shaders/shader_layout.hpp" +#include "toast/renderer/shaders/vulkan_pipeline.hpp" + +#include +#include +#include +#include + +namespace renderer { +class VulkanCore; + +/// Gives every render texel a motion vector by rebuilding the unwritten ones from depth reprojection +/// @note Render thread only +class MotionFill { +public: + MotionFill(const VulkanCore& core, vk::Extent2D render_extent); + + void onResize(vk::Extent2D render_extent); + + /// False when not ready and nothing was recorded + auto record(vk::CommandBuffer cmd, uint32_t frame_index, const glm::mat4& reprojection, bool ignore_written) -> bool; + + /// RGBA16F xy current minus previous uv, z reactive, w 1 when the scene wrote it + [[nodiscard]] + auto motionView() const -> vk::ImageView { + return m_motion.view.has_value() ? **m_motion.view : vk::ImageView {}; + } + + /// R8 reactive in [0,1] + [[nodiscard]] + auto reactiveView() const -> vk::ImageView { + return m_reactive.view.has_value() ? **m_reactive.view : vk::ImageView {}; + } + + [[nodiscard]] + auto motionImage() const -> vk::Image { + return m_motion.state.image; + } + + [[nodiscard]] + auto reactiveImage() const -> vk::Image { + return m_reactive.state.image; + } + +private: + /// Mirrors motion_fill.slang MotionFillParams + struct Push { + glm::mat4 reprojection {1.0f}; + uint32_t width = 0; + uint32_t height = 0; + uint32_t ignore_written = 0; + }; + + struct Target { + std::optional image; + std::optional view; + mutable sync::ImageState state; + }; + + void createTarget(Target& target, vk::Format format, std::string_view debug_name) const; + + const VulkanCore* m_core = nullptr; + vk::Extent2D m_extent {}; + + ShaderLayout m_shader_layout; + VulkanPipeline m_pipeline; + vk::raii::Sampler m_point_sampler = nullptr; + std::vector m_descriptor_sets; + /// Depth, scene motion, filled motion and reactive last written into each set + DescriptorCache> m_bound_views; + + Target m_motion; + Target m_reactive; +}; + +} diff --git a/engine/src/toast/renderer/passes/post/taa_pass.cpp b/engine/src/toast/renderer/passes/post/taa_pass.cpp index 6187cfb1a..25ddc6e70 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.cpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.cpp @@ -13,7 +13,9 @@ namespace renderer { TaaPass::TaaPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent) : m_core(&core), - m_scene_format(scene_format) { + m_scene_format(scene_format), + m_dlss(core), + m_motion_fill(core, VulkanRenderer::instance->renderExtent()) { ZoneScoped; static_assert(sizeof(Params) <= 128, "Vulkan guarantees 128 bytes of push constants"); @@ -76,15 +78,21 @@ void TaaPass::createResources(const VulkanCore& core) { } void TaaPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { - m_targets[0].create(core, extent, m_scene_format, "TaaPass History A"); - m_targets[1].create(core, extent, m_scene_format, "TaaPass History B"); + // 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 {}; + 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(); m_history_valid = false; } void TaaPass::onResize(vk::Extent2D extent) { if (m_core != nullptr) { + // The renderer waits for the device before resizing so the feature is idle + m_dlss.releaseFeature(); createTargets(*m_core, extent); + // The renderer applies a new render scale before resizing the passes + m_motion_fill.onResize(VulkanRenderer::instance->renderExtent()); } } @@ -97,25 +105,26 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView const bool upscale = frame != nullptr && frame->viewport_extent != output_size && frame->viewport_extent.x > 0.0f; if (!active && !show_motion && !upscale) { m_history_valid = false; + VulkanRenderer::instance->setDlssActive(false); return source_view; } const vk::ImageView depth_view = VulkanRenderer::instance->getDepthView(); - const vk::ImageView motion_view = VulkanRenderer::instance->getSceneMotionView(); + const vk::ImageView motion_view = m_motion_fill.motionView(); if (!m_pipeline.isReady() || frame_index >= m_descriptor_sets.size() || !source_view || !depth_view || !motion_view || !m_targets[0].isReady() || !m_targets[1].isReady()) { m_history_valid = false; + VulkanRenderer::instance->setDlssActive(false); return source_view; } - // A repeated snapshot carries no new sample + // A repeated snapshot carries no new sample and keeps the last resolve's DLSS state if (active && m_history_valid && frame->sequence == m_last_sequence) { return m_targets[m_write ^ 1u].view(); } const PostProcessTarget& target = m_targets[m_write]; const PostProcessTarget& history = m_targets[m_write ^ 1u]; - // Upsample only without TAA const bool reset = !m_history_valid || frame->taa_reset || !active; if (reset) { // Only for a legal layout since a reset frame never reads the history @@ -123,7 +132,7 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView history.endScope(cmd); } - const std::array wanted {source_view, history.view()}; + const std::array wanted {source_view, history.view(), motion_view}; if (m_bound_views.update(frame_index, wanted)) { const std::array image_infos { vk::DescriptorImageInfo(*m_point_sampler, source_view, vk::ImageLayout::eShaderReadOnlyOptimal), @@ -145,33 +154,50 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView const glm::mat4 current_view_projection = frame->frame_data.view_projection; const glm::mat4 previous_view_projection = m_history_valid ? m_last_view_projection : current_view_projection; - // A skipped frame breaks written motion so only depth reprojection is trusted + // A skipped frame breaks written motion so the fill falls back to camera reprojection const bool frames_skipped = m_history_valid && frame->sequence != m_last_sequence + 1; const auto width = static_cast(target.extent().width); const auto height = static_cast(target.extent().height); + const glm::mat4 reprojection = previous_view_projection * glm::inverse(current_view_projection); + Params params {}; - params.reprojection = previous_view_projection * glm::inverse(current_view_projection); params.texel = glm::vec4(1.0f / width, 1.0f / height, width, height); - params.tuning = glm::vec4( - VulkanRenderer::instance->taaHistoryWeight(), reset ? 1.0f : 0.0f, frames_skipped ? 1.0f : 0.0f, show_motion ? 1.0f : 0.0f - ); + params.tuning = glm::vec4(VulkanRenderer::instance->taaHistoryWeight(), reset ? 1.0f : 0.0f, 0.0f, show_motion ? 1.0f : 0.0f); params.source = glm::vec4(frame->viewport_extent, frame->jitter_ndc * 0.5f); - params.upscale = glm::vec4(upscale ? 1.0f : 0.0f, 0.0f, 0.0f, 0.0f); - - target.beginScope(cmd); - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_pipeline.getPipeline()); - cmd.bindDescriptorSets( - vk::PipelineBindPoint::eGraphics, - *m_shader_layout.getPipelineLayout(), - 0, - std::array {*m_descriptor_sets[frame_index]}, - {} - ); - cmd.pushConstants(*m_shader_layout.getPipelineLayout(), vk::ShaderStageFlagBits::eAll, 0, sizeof(Params), ¶ms); - cmd.draw(3, 1, 0, 0); - target.endScope(cmd); + params.adapt = glm::vec4(16.0f, 0.0f, 0.0f, 0.0f); + + if (!m_motion_fill.record(cmd, frame_index, reprojection, frames_skipped)) { + m_history_valid = false; + VulkanRenderer::instance->setDlssActive(false); + return source_view; + } + + // DLSS keeps its own history, so it restarts after any frame it did not resolve + const bool dlss = active && !show_motion && VulkanRenderer::instance->dlssRequested() && m_dlss.available() && + recordDlss( + cmd, + source_view, + target, + frame->jitter_ndc * 0.5f * frame->viewport_extent, + frame->taa_reset || !VulkanRenderer::instance->dlssActive() + ); + if (!dlss) { + target.beginScope(cmd); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + *m_shader_layout.getPipelineLayout(), + 0, + std::array {*m_descriptor_sets[frame_index]}, + {} + ); + cmd.pushConstants(*m_shader_layout.getPipelineLayout(), vk::ShaderStageFlagBits::eAll, 0, sizeof(Params), ¶ms); + cmd.draw(3, 1, 0, 0); + target.endScope(cmd); + } + VulkanRenderer::instance->setDlssActive(dlss); const vk::ImageView output = target.view(); m_write ^= 1u; @@ -183,4 +209,62 @@ auto TaaPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView return output; } +auto TaaPass::recordDlss( + vk::CommandBuffer cmd, vk::ImageView source_view, const PostProcessTarget& target, glm::vec2 jitter_pixels, bool reset +) -> bool { + ZoneScoped; + auto* renderer = VulkanRenderer::instance; + const vk::Image color_image = + 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" + : !depth ? "the depth image is missing" + : !m_motion_fill.motionImage() ? "the motion image is missing" + : "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); + } + return false; + } + + const vk::Extent2D render_extent = renderer->renderExtent(); + m_dlss.ensureFeature(cmd, render_extent, target.extent()); + + // NGX samples the inputs from compute in shader read layouts and writes the output as a storage image + sync::BarrierBatch barriers; + barriers.image(target.state(), sync::Usage::compute_storage_write); + barriers.image(depth.image, depth.range, depth.usage, sync::Usage::shader_sampled); + barriers.flush(cmd); + + DlssInputs inputs {}; + inputs.color = source_view; + inputs.depth = renderer->getDepthView(); + inputs.motion = m_motion_fill.motionView(); + inputs.reactive = m_motion_fill.reactiveView(); + inputs.output = target.view(); + inputs.color_image = color_image; + inputs.depth_image = depth.image; + inputs.motion_image = m_motion_fill.motionImage(); + inputs.reactive_image = m_motion_fill.reactiveImage(); + inputs.output_image = target.state().image; + inputs.color_format = m_scene_format; + inputs.depth_format = renderer->getDepthFormat(); + inputs.render_extent = render_extent; + inputs.output_extent = target.extent(); + inputs.jitter_pixels = jitter_pixels; + inputs.reset = reset; + const bool evaluated = m_dlss.evaluate(cmd, inputs); + + // The overlay and later passes expect the tracked depth layout back + barriers.image(depth.image, depth.range, sync::Usage::shader_sampled, depth.usage); + if (evaluated) { + barriers.image(target.state(), sync::Usage::shader_sampled); + } + barriers.flush(cmd); + return evaluated; +} + } diff --git a/engine/src/toast/renderer/passes/post/taa_pass.hpp b/engine/src/toast/renderer/passes/post/taa_pass.hpp index f9b9cff2b..079caaebf 100644 --- a/engine/src/toast/renderer/passes/post/taa_pass.hpp +++ b/engine/src/toast/renderer/passes/post/taa_pass.hpp @@ -8,13 +8,16 @@ #include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/passes/post/motion_fill.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" #include "toast/renderer/shaders/shader_layout.hpp" #include "toast/renderer/shaders/vulkan_pipeline.hpp" +#include "toast/renderer/upscale/dlss_upscaler.hpp" #include #include +#include #include namespace renderer { @@ -47,24 +50,36 @@ class TaaPass : public IPostProcessPass { return m_history_valid ? m_targets[m_write ^ 1u].view() : vk::ImageView {}; } + /// Empty when DLSS is available + [[nodiscard]] + auto dlssFailureReason() const -> std::string { + return m_dlss.failureReason(); + } + private: /// Mirrors taa.slang TaaParams struct Params { - glm::mat4 reprojection {1.0f}; glm::vec4 texel {0.0f}; glm::vec4 tuning {0.0f}; /// xy render size zw jitter in uv glm::vec4 source {0.0f}; - /// x 1 when the source is smaller than the output - glm::vec4 upscale {0.0f}; + /// x output pixels of motion at which the history weight halves + glm::vec4 adapt {0.0f}; }; void createResources(const VulkanCore& core); void createTargets(const VulkanCore& core, vk::Extent2D extent); + /// Resolves into @p target with DLSS, false when the caller must run the TAA draw instead + auto recordDlss( + vk::CommandBuffer cmd, vk::ImageView source_view, const PostProcessTarget& target, glm::vec2 jitter_pixels, bool reset + ) -> bool; const VulkanCore* m_core = nullptr; vk::Format m_scene_format = vk::Format::eUndefined; + DlssUpscaler m_dlss; + MotionFill m_motion_fill; + ShaderLayout m_shader_layout; VulkanPipeline m_pipeline; @@ -72,14 +87,15 @@ class TaaPass : public IPostProcessPass { vk::raii::Sampler m_point_sampler = nullptr; std::vector m_descriptor_sets; - /// Source then history last written into each set - DescriptorCache> m_bound_views; + /// Source, history and filled motion last written into each set + DescriptorCache> m_bound_views; /// Last frame output is this frame history std::array m_targets; uint32_t m_write = 0; bool m_history_valid = false; + bool m_dlss_source_logged = false; uint64_t m_last_sequence = 0; glm::mat4 m_last_view_projection {1.0f}; }; diff --git a/engine/src/toast/renderer/resources/material_runtime.cpp b/engine/src/toast/renderer/resources/material_runtime.cpp index af0ad1932..3750368c8 100644 --- a/engine/src/toast/renderer/resources/material_runtime.cpp +++ b/engine/src/toast/renderer/resources/material_runtime.cpp @@ -1,5 +1,7 @@ #include "toast/renderer/resources/material_runtime.hpp" +#include "toast/renderer/vulkan_renderer.hpp" + namespace renderer { using assets::DataType; @@ -426,8 +428,9 @@ auto MaterialRuntime::samplerFor(const DataValue* params, std::string_view debug anisotropy = (*params)["anisotropy"].value().value_or(true); } - const std::string state = - repeat_u + "|" + repeat_v + "|" + min_filter + "|" + mag_filter + "|" + mipmap_mode + "|" + (anisotropy ? "1" : "0"); + const float mip_bias = VulkanRenderer::instance->materialMipBias(); + const std::string state = repeat_u + "|" + repeat_v + "|" + min_filter + "|" + mag_filter + "|" + mipmap_mode + "|" + + (anisotropy ? "1" : "0") + "|" + std::to_string(mip_bias); const uint64_t key = ShaderCache::fnv1a(state.data(), state.size()); if (const auto it = m_samplers.find(key); it != m_samplers.end()) { @@ -446,7 +449,7 @@ auto MaterialRuntime::samplerFor(const DataValue* params, std::string_view debug info.compareEnable = vk::False; info.compareOp = vk::CompareOp::eAlways; info.unnormalizedCoordinates = vk::False; - info.mipLodBias = 0.0f; + info.mipLodBias = mip_bias; info.minLod = 0.0f; info.maxLod = VK_LOD_CLAMP_NONE; diff --git a/engine/src/toast/renderer/resources/material_runtime.hpp b/engine/src/toast/renderer/resources/material_runtime.hpp index b46c90cc0..e8db1b88e 100644 --- a/engine/src/toast/renderer/resources/material_runtime.hpp +++ b/engine/src/toast/renderer/resources/material_runtime.hpp @@ -44,6 +44,8 @@ class MaterialRuntime { void markValuesDirty() { m_values_dirty = true; } + void markTexturesDirty() { m_textures_dirty = true; } + struct UboBlob { uint32_t set = 0; uint32_t binding = 0; diff --git a/engine/src/toast/renderer/resources/post_process_target.cpp b/engine/src/toast/renderer/resources/post_process_target.cpp index ce74ee822..cac468317 100644 --- a/engine/src/toast/renderer/resources/post_process_target.cpp +++ b/engine/src/toast/renderer/resources/post_process_target.cpp @@ -6,17 +6,46 @@ #include "toast/renderer/resources/post_process_target.hpp" +#include +#include + namespace renderer { -void PostProcessTarget::create(const VulkanCore& core, vk::Extent2D extent, vk::Format format, std::string_view debug_name) { +namespace { + +std::mutex g_post_target_images_mutex; +std::unordered_map g_post_target_images; + +} + +auto PostProcessTarget::imageOf(vk::ImageView view) -> vk::Image { + const std::lock_guard lock(g_post_target_images_mutex); + const auto it = g_post_target_images.find(view); + return it != g_post_target_images.end() ? vk::Image(it->second) : vk::Image {}; +} + +PostProcessTarget::~PostProcessTarget() { + if (m_view.has_value()) { + const std::lock_guard lock(g_post_target_images_mutex); + g_post_target_images.erase(**m_view); + } +} + +void PostProcessTarget::create( + const VulkanCore& core, vk::Extent2D extent, vk::Format format, std::string_view debug_name, vk::ImageUsageFlags usage +) { ZoneScoped; + if (m_view.has_value()) { + const std::lock_guard lock(g_post_target_images_mutex); + g_post_target_images.erase(**m_view); + } // View before the image it views m_view.reset(); m_image.reset(); m_extent = extent; m_state = {}; - const auto image_ci = colorTargetImageInfo(extent, format); + const auto image_ci = colorTargetImageInfo(extent, format, usage); vma::AllocationCreateInfo allocation_ci {}; allocation_ci.usage = vma::MemoryUsage::eAutoPreferDevice; @@ -32,6 +61,9 @@ void PostProcessTarget::create(const VulkanCore& core, vk::Extent2D extent, vk:: view_ci.subresourceRange = colorSubresourceRange(); m_view.emplace(core.getDevice(), view_ci); setDebugName(core, **m_view, std::format("{} TargetView", debug_name)); + + const std::lock_guard lock(g_post_target_images_mutex); + g_post_target_images[**m_view] = **m_image; } void PostProcessTarget::beginScope(vk::CommandBuffer cmd) const { diff --git a/engine/src/toast/renderer/resources/post_process_target.hpp b/engine/src/toast/renderer/resources/post_process_target.hpp index e5fc2e8cb..f977b7275 100644 --- a/engine/src/toast/renderer/resources/post_process_target.hpp +++ b/engine/src/toast/renderer/resources/post_process_target.hpp @@ -26,7 +26,19 @@ class PostProcessTarget { return {width > 0 ? width : 1u, height > 0 ? height : 1u}; } - void create(const VulkanCore& core, vk::Extent2D extent, vk::Format format, std::string_view debug_name); + /// Image behind a live target view or null. Post passes only hand on views and NGX also needs the image + [[nodiscard]] + static auto imageOf(vk::ImageView view) -> vk::Image; + + PostProcessTarget() = default; + ~PostProcessTarget(); + PostProcessTarget(const PostProcessTarget&) = delete; + auto operator=(const PostProcessTarget&) -> PostProcessTarget& = delete; + + /// @p usage adds to colour attachment and sampled + void create( + const VulkanCore& core, vk::Extent2D extent, vk::Format format, std::string_view debug_name, vk::ImageUsageFlags usage = {} + ); void beginScope(vk::CommandBuffer cmd) const; @@ -40,6 +52,12 @@ class PostProcessTarget { return m_view.has_value() ? **m_view : vk::ImageView {}; } + /// For barriers recorded outside the scopes, such as a compute write + [[nodiscard]] + auto state() const noexcept -> sync::ImageState& { + return m_state; + } + [[nodiscard]] auto extent() const noexcept -> vk::Extent2D { return m_extent; diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index 2da51dc90..a3a8c3801 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -571,6 +571,18 @@ void registerQuality(VulkanRenderer& renderer) { ) .onChange([&renderer](bool enabled) { renderer.setTaaEnabled(enabled); }); + toast::settings::declareInt( + "renderer.quality.antialiasing", + 1, + { + .label = "Anti-aliasing", + .category = "Quality", + .description = "DLSS on NVIDIA RTX GPUs, TAA everywhere else. Needs TAA on.", + .options = {"TAA", "DLSS"} + } + ) + .onChange([&renderer](int64_t mode) { renderer.setDlssRequested(mode == 1); }); + toast::settings::declareFloat( "renderer.quality.taa_history", 0.9, diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.cpp b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp new file mode 100644 index 000000000..c12ea27ff --- /dev/null +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.cpp @@ -0,0 +1,389 @@ +/** + * @file dlss_upscaler.cpp + * @author dario + * @date 22/11/2026 + */ + +#include "toast/renderer/upscale/dlss_upscaler.hpp" + +#include "toast/renderer/core/depth_convention.hpp" +#include "toast/renderer/core/vulkan_core.hpp" + +#include + +#ifdef TOAST_DLSS +#include +#include +#include +#endif + +namespace renderer { + +#ifdef TOAST_DLSS + +namespace { +/// GUID-like id NGX takes from engines without an NVIDIA application id +constexpr const char* k_project_id = "6b85a39b-e850-4545-982c-44e42ac0a548"; +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 = [] { + std::filesystem::path dir; + std::error_code ec; + if (char* pref_path = SDL_GetPrefPath("nullptr-studios", "toast-engine")) { + dir = std::filesystem::path(std::u8string_view(reinterpret_cast(pref_path))) / "logs"; + SDL_free(pref_path); + } else { + dir = std::filesystem::temp_directory_path(ec) / "nullptr-studios" / "toast-engine" / "logs"; + } + std::filesystem::create_directories(dir, ec); + return dir; + }(); + return path; +} + +/// NGX itself only searches the exe directory and the editor exe lives elsewhere +auto engineDirectory() -> std::wstring { + HMODULE module = nullptr; + if (!GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&engineDirectory), + &module + )) { + return {}; + } + std::array path {}; + const DWORD length = GetModuleFileNameW(module, path.data(), MAX_PATH); + if (length == 0 || length >= MAX_PATH) { + return {}; + } + return std::filesystem::path(path.data()).parent_path().wstring(); +} + +auto discoveryInfo() -> NVSDK_NGX_FeatureDiscoveryInfo { + NVSDK_NGX_FeatureDiscoveryInfo info {}; + info.SDKVersion = NVSDK_NGX_Version_API; + 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(); + return info; +} + +auto extensionNames(const VkExtensionProperties* properties, uint32_t count) -> std::vector { + std::vector names; + for (uint32_t i = 0; i < count; ++i) { + names.push_back(properties[i].extensionName); + } + return names; +} + +auto resultString(NVSDK_NGX_Result result) -> std::string { + auto text = std::format("0x{:08X}", static_cast(result)); + if (const wchar_t* name = GetNGXResultAsString(result)) { + text += ' '; + // NGX result names are ASCII + for (; *name != L'\0'; ++name) { + text += static_cast(*name); + } + } + return text; +} + +/// Transformer model, NVIDIA's default for DLAA, Quality and Balanced +constexpr auto k_render_preset = NVSDK_NGX_DLSS_Hint_Render_Preset_K; + +/// Nearest NGX quality mode for the render scale since the slider is continuous +auto qualityFor(vk::Extent2D render_extent, vk::Extent2D output_extent) -> NVSDK_NGX_PerfQuality_Value { + const float scale = static_cast(render_extent.width) / static_cast(output_extent.width); + if (scale >= 0.99f) { + return NVSDK_NGX_PerfQuality_Value_DLAA; + } + if (scale >= 0.62f) { + return NVSDK_NGX_PerfQuality_Value_MaxQuality; + } + return scale >= 0.54f ? NVSDK_NGX_PerfQuality_Value_Balanced : NVSDK_NGX_PerfQuality_Value_MaxPerf; +} + +auto imageResource(vk::ImageView view, vk::Image image, vk::Format format, vk::Extent2D extent, bool depth, bool write) + -> NVSDK_NGX_Resource_VK { + const vk::ImageSubresourceRange range(depth ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1); + return NVSDK_NGX_Create_ImageView_Resource_VK( + view, image, range, static_cast(format), extent.width, extent.height, write + ); +} +} // namespace + +auto DlssUpscaler::instanceExtensions() -> std::vector { + const auto info = discoveryInfo(); + uint32_t count = 0; + VkExtensionProperties* properties = nullptr; + if (NVSDK_NGX_FAILED(NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements(&info, &count, &properties))) { + return {}; + } + return extensionNames(properties, count); +} + +auto DlssUpscaler::deviceExtensions(vk::Instance instance, vk::PhysicalDevice physical_device) -> std::vector { + const auto info = discoveryInfo(); + uint32_t count = 0; + VkExtensionProperties* properties = nullptr; + if (NVSDK_NGX_FAILED( + NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements(instance, physical_device, &info, &count, &properties) + )) { + return {}; + } + return extensionNames(properties, count); +} + +DlssUpscaler::DlssUpscaler(const VulkanCore& core) : m_core(&core) { + ZoneScoped; + m_failure_reason = core.dlssExtensionsEnabled() ? initialize() : std::string(core.dlssReason()); + m_available = m_failure_reason.empty(); + const auto props = core.getPhysicalDevice().getProperties(); + if (m_available) { + TOAST_INFO("Render", "DLSS ready (Super Resolution on {})", props.deviceName.data()); + return; + } + release(); + if (props.vendorID == k_vendor_nvidia) { + TOAST_WARN("Render", "DLSS unavailable on {}: {}", props.deviceName.data(), m_failure_reason); + } else { + TOAST_INFO("Render", "DLSS unavailable: {}", m_failure_reason); + } +} + +auto DlssUpscaler::initialize() -> std::string { + const auto& instance = m_core->getInstance(); + const auto& device = m_core->getDevice(); + + const std::wstring engine_dir = engineDirectory(); + const std::array search_paths {engine_dir.c_str()}; + NVSDK_NGX_FeatureCommonInfo common_info {}; + if (!engine_dir.empty()) { + common_info.PathListInfo.Path = search_paths.data(); + common_info.PathListInfo.Length = static_cast(search_paths.size()); + } + + auto result = NVSDK_NGX_VULKAN_Init_with_ProjectID( + k_project_id, + NVSDK_NGX_ENGINE_TYPE_CUSTOM, + k_engine_version, + dataPath().c_str(), + *instance, + *m_core->getPhysicalDevice(), + *device, + instance.getDispatcher()->vkGetInstanceProcAddr, + device.getDispatcher()->vkGetDeviceProcAddr, + &common_info + ); + if (NVSDK_NGX_FAILED(result)) { + return std::format("NGX initialisation failed ({})", resultString(result)); + } + m_ngx_initialized = true; + + result = NVSDK_NGX_VULKAN_GetCapabilityParameters(&m_parameters); + if (NVSDK_NGX_FAILED(result) || m_parameters == nullptr) { + m_parameters = nullptr; + return std::format("NGX capability query failed ({})", resultString(result)); + } + + int needs_driver = 0; + if (NVSDK_NGX_SUCCEED(m_parameters->Get(NVSDK_NGX_Parameter_SuperSampling_NeedsUpdatedDriver, &needs_driver)) && + needs_driver != 0) { + unsigned int major = 0; + unsigned int minor = 0; + m_parameters->Get(NVSDK_NGX_Parameter_SuperSampling_MinDriverVersionMajor, &major); + m_parameters->Get(NVSDK_NGX_Parameter_SuperSampling_MinDriverVersionMinor, &minor); + return std::format("the NVIDIA driver is too old, DLSS needs {}.{} or newer", major, minor); + } + + int available = 0; + if (NVSDK_NGX_FAILED(m_parameters->Get(NVSDK_NGX_Parameter_SuperSampling_Available, &available)) || available == 0) { + int init_result = NVSDK_NGX_Result_Fail; + m_parameters->Get(NVSDK_NGX_Parameter_SuperSampling_FeatureInitResult, &init_result); + return std::format("Super Resolution is not available ({})", resultString(static_cast(init_result))); + } + return {}; +} + +void DlssUpscaler::ensureFeature(vk::CommandBuffer cmd, vk::Extent2D render_extent, vk::Extent2D output_extent) { + if (!m_available || m_create_failed) { + return; + } + if (m_feature != nullptr) { + if ((render_extent != m_feature_render || output_extent != m_feature_output) && !m_mismatch_logged) { + m_mismatch_logged = true; + setRuntimeReason("the frame extents changed without a resize"); + TOAST_WARN( + "Render", + "DLSS feature is {}x{} -> {}x{} but the frame is {}x{} -> {}x{}, the extents changed without TaaPass::onResize; " + "using TAA until the next resize", + m_feature_render.width, + m_feature_render.height, + m_feature_output.width, + m_feature_output.height, + render_extent.width, + render_extent.height, + output_extent.width, + output_extent.height + ); + } + return; + } + + ZoneScoped; + for (const char* hint : + {NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_DLAA, + NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_Quality, + NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_Balanced, + NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_Performance, + NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_UltraPerformance, + NVSDK_NGX_Parameter_DLSS_Hint_Render_Preset_UltraQuality}) { + NVSDK_NGX_Parameter_SetUI(m_parameters, hint, k_render_preset); + } + + int flags = + NVSDK_NGX_DLSS_Feature_Flags_IsHDR | NVSDK_NGX_DLSS_Feature_Flags_MVLowRes | NVSDK_NGX_DLSS_Feature_Flags_AutoExposure; + if constexpr (depth::k_reversed_z) { + flags |= NVSDK_NGX_DLSS_Feature_Flags_DepthInverted; + } + + NVSDK_NGX_DLSS_Create_Params create {}; + create.Feature.InWidth = render_extent.width; + create.Feature.InHeight = render_extent.height; + create.Feature.InTargetWidth = output_extent.width; + create.Feature.InTargetHeight = output_extent.height; + create.Feature.InPerfQualityValue = qualityFor(render_extent, output_extent); + create.InFeatureCreateFlags = flags; + + const auto result = NGX_VULKAN_CREATE_DLSS_EXT1(*m_core->getDevice(), cmd, 1, 1, &m_feature, m_parameters, &create); + if (NVSDK_NGX_FAILED(result) || m_feature == nullptr) { + m_feature = nullptr; + m_create_failed = true; + setRuntimeReason(std::format("feature creation failed ({})", resultString(result))); + TOAST_WARN( + "Render", + "DLSS feature creation failed for {}x{} -> {}x{} ({}); using TAA until the next resize", + render_extent.width, + render_extent.height, + output_extent.width, + output_extent.height, + resultString(result) + ); + return; + } + m_feature_render = render_extent; + m_feature_output = output_extent; + m_reset_pending = true; + m_mismatch_logged = false; + m_evaluate_failure_logged = false; + TOAST_INFO( + "Render", + "DLSS feature created ({}x{} -> {}x{}, quality {}, preset K)", + render_extent.width, + render_extent.height, + output_extent.width, + output_extent.height, + static_cast(create.Feature.InPerfQualityValue) + ); +} + +auto DlssUpscaler::evaluate(vk::CommandBuffer cmd, const DlssInputs& inputs) -> bool { + // A missing or mismatched feature was already logged by ensureFeature + if (m_feature == nullptr || inputs.render_extent != m_feature_render || inputs.output_extent != m_feature_output) { + return false; + } + ZoneScoped; + + auto color = imageResource(inputs.color, inputs.color_image, inputs.color_format, inputs.render_extent, false, false); + auto depth = imageResource(inputs.depth, inputs.depth_image, inputs.depth_format, inputs.render_extent, true, false); + auto motion = + imageResource(inputs.motion, inputs.motion_image, vk::Format::eR16G16B16A16Sfloat, inputs.render_extent, false, false); + auto reactive = imageResource(inputs.reactive, inputs.reactive_image, vk::Format::eR8Unorm, inputs.render_extent, false, false); + auto output = imageResource(inputs.output, inputs.output_image, inputs.color_format, inputs.output_extent, false, true); + + NVSDK_NGX_VK_DLSS_Eval_Params eval {}; + eval.Feature.pInColor = &color; + eval.Feature.pInOutput = &output; + eval.pInDepth = &depth; + eval.pInMotionVectors = &motion; + eval.pInBiasCurrentColorMask = &reactive; + eval.InJitterOffsetX = inputs.jitter_pixels.x; + eval.InJitterOffsetY = inputs.jitter_pixels.y; + eval.InRenderSubrectDimensions = {inputs.render_extent.width, inputs.render_extent.height}; + eval.InReset = inputs.reset || m_reset_pending ? 1 : 0; + // Motion is current minus previous in uv and NGX wants previous minus current in render pixels + eval.InMVScaleX = -static_cast(inputs.render_extent.width); + eval.InMVScaleY = -static_cast(inputs.render_extent.height); + eval.InPreExposure = 1.0f; + eval.InExposureScale = 1.0f; + + const auto result = NGX_VULKAN_EVALUATE_DLSS_EXT(cmd, m_feature, m_parameters, &eval); + if (NVSDK_NGX_FAILED(result)) { + setRuntimeReason(std::format("evaluate failed ({})", resultString(result))); + if (!m_evaluate_failure_logged) { + m_evaluate_failure_logged = true; + TOAST_WARN("Render", "DLSS evaluate failed ({}); TAA resolves every frame it fails", resultString(result)); + } + return false; + } + m_reset_pending = false; + setRuntimeReason({}); + return true; +} + +void DlssUpscaler::releaseFeature() noexcept { + if (m_feature != nullptr) { + NVSDK_NGX_VULKAN_ReleaseFeature(m_feature); + m_feature = nullptr; + } + m_create_failed = false; + setRuntimeReason({}); +} + +void DlssUpscaler::release() noexcept { + releaseFeature(); + if (m_parameters != nullptr) { + NVSDK_NGX_VULKAN_DestroyParameters(m_parameters); + m_parameters = nullptr; + } + if (m_ngx_initialized) { + NVSDK_NGX_VULKAN_Shutdown1(*m_core->getDevice()); + m_ngx_initialized = false; + } +} + +#else + +auto DlssUpscaler::instanceExtensions() -> std::vector { + return {}; +} + +auto DlssUpscaler::deviceExtensions(vk::Instance, vk::PhysicalDevice) -> std::vector { + return {}; +} + +DlssUpscaler::DlssUpscaler(const VulkanCore& core) : m_core(&core), m_failure_reason("built without DLSS") { + TOAST_INFO("Render", "DLSS unavailable: {}", m_failure_reason); +} + +void DlssUpscaler::ensureFeature(vk::CommandBuffer, vk::Extent2D, vk::Extent2D) { } + +auto DlssUpscaler::evaluate(vk::CommandBuffer, const DlssInputs&) -> bool { + return false; +} + +void DlssUpscaler::releaseFeature() noexcept { } + +void DlssUpscaler::release() noexcept { } + +#endif + +DlssUpscaler::~DlssUpscaler() { + release(); +} + +} diff --git a/engine/src/toast/renderer/upscale/dlss_upscaler.hpp b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp new file mode 100644 index 000000000..0e460c190 --- /dev/null +++ b/engine/src/toast/renderer/upscale/dlss_upscaler.hpp @@ -0,0 +1,109 @@ +/** + * @file dlss_upscaler.hpp + * @author dario + * @date 22/11/2026 + */ + +#pragma once + +#include "toast/renderer/core/vulkan_common.hpp" + +#include +#include +#include +#include +#include + +struct NVSDK_NGX_Parameter; +struct NVSDK_NGX_Handle; + +namespace renderer { +class VulkanCore; + +/// Every image in a shader read layout visible to compute except output, which is in eGeneral +struct DlssInputs { + vk::ImageView color, depth, motion, reactive, output; + vk::Image color_image, depth_image, motion_image, reactive_image, output_image; + /// Shared by color and output + vk::Format color_format = vk::Format::eUndefined; + vk::Format depth_format = vk::Format::eUndefined; + vk::Extent2D render_extent, output_extent; + /// Offset the projection moved the scene by this frame, in render pixels with y down + glm::vec2 jitter_pixels {0.0f}; + bool reset = false; +}; + +/// NVIDIA DLSS Super Resolution through NGX, every call is a no-op in builds without TOAST_DLSS +class DlssUpscaler { +public: + /// What NGX needs at vkCreateInstance, before any GPU is known. Empty when the query fails + /// @warning The names point into NGX memory, use them before the next NGX call + [[nodiscard]] + static auto instanceExtensions() -> std::vector; + + /// What NGX needs on this NVIDIA device, empty when the query fails. Same lifetime as instanceExtensions() + [[nodiscard]] + static auto deviceExtensions(vk::Instance instance, vk::PhysicalDevice physical_device) -> std::vector; + + explicit DlssUpscaler(const VulkanCore& core); + /// Must run before the device is destroyed + ~DlssUpscaler(); + + DlssUpscaler(const DlssUpscaler&) = delete; + auto operator=(const DlssUpscaler&) -> DlssUpscaler& = delete; + + [[nodiscard]] + auto available() const noexcept -> bool { + return m_available; + } + + /// Why DLSS is off or failing, empty when it works. By value since the render thread writes it + [[nodiscard]] + auto failureReason() const -> std::string { + const std::scoped_lock lock(m_runtime_mutex); + return m_runtime_reason.empty() ? m_failure_reason : m_runtime_reason; + } + + /// Records a failure after init, cleared by a successful evaluate or releaseFeature + void setRuntimeReason(std::string reason) { + const std::scoped_lock lock(m_runtime_mutex); + m_runtime_reason = std::move(reason); + } + + /// Creates the feature on first use, never recreates a live one since only an idle device may release it + void ensureFeature(vk::CommandBuffer cmd, vk::Extent2D render_extent, vk::Extent2D output_extent); + + /// False when nothing usable was recorded and the caller resolves the frame itself + [[nodiscard]] + auto evaluate(vk::CommandBuffer cmd, const DlssInputs& inputs) -> bool; + + /// Keeps NGX initialised. The device must be idle + void releaseFeature() noexcept; + +private: + /// Empty on success, otherwise why DLSS is off + [[nodiscard]] + auto initialize() -> std::string; + void release() noexcept; + + const VulkanCore* m_core = nullptr; + NVSDK_NGX_Parameter* m_parameters = nullptr; + NVSDK_NGX_Handle* m_feature = nullptr; + vk::Extent2D m_feature_render {}; + vk::Extent2D m_feature_output {}; + /// Creation failed for the current extents, retried after the next releaseFeature + bool m_create_failed = false; + /// The first evaluate of a new feature has no history + bool m_reset_pending = false; + bool m_mismatch_logged = false; + bool m_evaluate_failure_logged = false; + bool m_ngx_initialized = false; + + bool m_available = false; + std::string m_failure_reason; + /// Read by the UI thread, written by the render thread + mutable std::mutex m_runtime_mutex; + std::string m_runtime_reason; +}; + +} diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index b10e300e7..eade38877 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -298,6 +298,11 @@ class VulkanRenderer { return m_scene_color.view.has_value() ? **m_scene_color.view : vk::ImageView {}; } + [[nodiscard]] + auto getSceneColorImage() const noexcept -> vk::Image { + return m_scene_color.state.image; + } + /// xyz world normal w roughness void setVoxelDetailTexture(assets::Handle detail); @@ -822,6 +827,17 @@ class VulkanRenderer { return m_depth_resources.view.has_value() ? **m_depth_resources.view : vk::ImageView {}; } + /// For a pass that needs another layout briefly and restores the tracked usage + [[nodiscard]] + auto getDepthState() const noexcept -> const sync::ImageState& { + return m_depth_resources.state; + } + + [[nodiscard]] + auto getDepthFormat() const noexcept -> vk::Format { + return m_depth_format; + } + [[nodiscard]] auto getOverlayDepthView() const noexcept -> vk::ImageView { return m_output_depth.view.has_value() ? **m_output_depth.view : getDepthView(); @@ -1265,6 +1281,38 @@ class VulkanRenderer { return m_taa_enabled.load(std::memory_order_relaxed); } + /// DLSS replaces the temporal resolve when it is available + void setDlssRequested(bool requested) noexcept { m_dlss_requested.store(requested, std::memory_order_relaxed); } + + [[nodiscard]] + auto dlssRequested() const noexcept -> bool { + return m_dlss_requested.load(std::memory_order_relaxed); + } + + /// Set by TaaPass after each record + void setDlssActive(bool active) noexcept { m_dlss_active.store(active, std::memory_order_relaxed); } + + /// True while DLSS produced the last resolved frame + [[nodiscard]] + auto dlssActive() const noexcept -> bool { + return m_dlss_active.load(std::memory_order_relaxed); + } + + /// Why DLSS cannot run, empty when it can + [[nodiscard]] + auto dlssFailureReason() const -> std::string; + + /// Sharper material mips offset the lower render resolution so the temporal resolve recovers detail + [[nodiscard]] + auto materialMipBias() const noexcept -> float { + const float scale_bias = std::log2(m_applied_render_scale.load(std::memory_order_relaxed)); + // NVIDIA's DLSS guidance is one level sharper than the resolution ratio + if (dlssActive()) { + return scale_bias - 1.0f; + } + return taaEnabled() ? scale_bias : 0.0f; + } + void setTaaHistoryWeight(float weight) noexcept { m_taa_history_weight.store(weight, std::memory_order_relaxed); } [[nodiscard]] @@ -1699,6 +1747,8 @@ class VulkanRenderer { bool m_traced_shadows_voxel_fallback_logged = false; std::atomic_bool m_taa_enabled {true}; + std::atomic_bool m_dlss_requested {true}; + std::atomic_bool m_dlss_active {false}; std::atomic m_render_scale {1.0f}; std::mutex m_setting_request_mutex; std::vector> m_setting_requests; diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index aa2a7fef7..6286541ee 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -1514,13 +1514,33 @@ void VulkanRenderer::updateTemporalAA(RenderFrame& frame, vk::Extent2D render_ex frame.jitter_ndc = glm::vec2(0.0f); if (taa && render_extent.width > 0 && render_extent.height > 0) { - // R2 low discrepancy sequence from the plastic number - constexpr double k_plastic = 1.32471795724474602596; - const auto n = static_cast(++m_taa_history.jitter_index); - const glm::vec2 pixel_offset( - static_cast(std::fmod(0.5 + (n / k_plastic), 1.0)) - 0.5f, - static_cast(std::fmod(0.5 + (n / (k_plastic * k_plastic)), 1.0)) - 0.5f - ); + const uint64_t index = ++m_taa_history.jitter_index; + glm::vec2 pixel_offset; + if (dlssActive()) { + // Halton(2,3) with enough phases per output pixel as NVIDIA's DLSS guide asks + const float ratio = frame.output_extent.x / static_cast(render_extent.width); + const auto phases = static_cast(std::ceil(8.0f * ratio * ratio)); + const auto halton = [](uint64_t i, uint64_t base) { + float fraction = 1.0f; + float result = 0.0f; + for (; i > 0; i /= base) { + fraction /= static_cast(base); + result += fraction * static_cast(i % base); + } + return result; + }; + // Halton index 0 is the corner so the cycle starts at 1 + const uint64_t phase = (index % std::max(phases, 1)) + 1; + pixel_offset = glm::vec2(halton(phase, 2) - 0.5f, halton(phase, 3) - 0.5f); + } else { + // R2 low discrepancy sequence from the plastic number + constexpr double k_plastic = 1.32471795724474602596; + const auto n = static_cast(index); + pixel_offset = glm::vec2( + static_cast(std::fmod(0.5 + (n / k_plastic), 1.0)) - 0.5f, + static_cast(std::fmod(0.5 + (n / (k_plastic * k_plastic)), 1.0)) - 0.5f + ); + } const glm::vec2 ndc_offset = 2.0f * pixel_offset / glm::vec2(static_cast(render_extent.width), static_cast(render_extent.height)); frame.jitter_ndc = ndc_offset; diff --git a/engine/src/toast/renderer/vulkan_renderer_thread.cpp b/engine/src/toast/renderer/vulkan_renderer_thread.cpp index 86ea10003..ba875d622 100644 --- a/engine/src/toast/renderer/vulkan_renderer_thread.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_thread.cpp @@ -395,6 +395,10 @@ auto VulkanRenderer::previousResolvedColour() const noexcept -> vk::ImageView { return m_taa_pass->resolvedHistory(); } +auto VulkanRenderer::dlssFailureReason() const -> std::string { + return m_taa_pass != nullptr ? m_taa_pass->dlssFailureReason() : std::string {}; +} + void VulkanRenderer::submitFrame() noexcept { { std::lock_guard lock(m_queue_mutex); diff --git a/engine/src/toast/world/workspace_voxel.cpp b/engine/src/toast/world/workspace_voxel.cpp index 620fd849a..c82f69da6 100644 --- a/engine/src/toast/world/workspace_voxel.cpp +++ b/engine/src/toast/world/workspace_voxel.cpp @@ -5,6 +5,10 @@ #include #include +#include +#include +#include +#include #include #include #include @@ -1458,6 +1462,72 @@ auto meshRayHit(const assets::Mesh& mesh, glm::vec3 origin, glm::vec3 direction, return nearest; } +/// Entry t of a unit ray into a sphere, none from inside or behind +[[nodiscard]] +auto rayBallEntry(glm::vec3 origin, glm::vec3 direction, glm::vec3 centre, float radius) -> std::optional { + const glm::vec3 m = origin - centre; + const float b = glm::dot(m, direction); + const float disc = (b * b) - (glm::dot(m, m) - (radius * radius)); + if (disc < 0.0f) { + return std::nullopt; + } + const float t = -b - std::sqrt(disc); + return t >= 0.0f ? std::optional(t) : std::nullopt; +} + +/// Entry t of a unit ray into a centred box, none from inside or behind +[[nodiscard]] +auto rayBoxEntry(glm::vec3 origin, glm::vec3 direction, glm::vec3 half) -> std::optional { + float t_min = -std::numeric_limits::max(); + float t_max = std::numeric_limits::max(); + for (int axis = 0; axis < 3; ++axis) { + if (std::abs(direction[axis]) < 1.0e-8f) { + if (std::abs(origin[axis]) > half[axis]) { + return std::nullopt; + } + continue; + } + float t1 = (-half[axis] - origin[axis]) / direction[axis]; + float t2 = (half[axis] - origin[axis]) / direction[axis]; + if (t1 > t2) { + std::swap(t1, t2); + } + t_min = std::max(t_min, t1); + t_max = std::min(t_max, t2); + } + return (t_min >= 0.0f && t_min <= t_max) ? std::optional(t_min) : std::nullopt; +} + +/// Entry t of a unit ray into a capsule along Z with shaft the half length between the cap centres +[[nodiscard]] +auto rayCapsuleEntry(glm::vec3 origin, glm::vec3 direction, float radius, float shaft) -> std::optional { + const glm::vec3 along(0.0f, 0.0f, std::clamp(origin.z, -shaft, shaft)); + if (glm::dot(origin - along, origin - along) <= radius * radius) { + return std::nullopt; + } + std::optional nearest; + const auto take = [&](std::optional t) { + if (t.has_value() && (!nearest.has_value() || *t < *nearest)) { + nearest = t; + } + }; + take(rayBallEntry(origin, direction, {0.0f, 0.0f, shaft}, radius)); + take(rayBallEntry(origin, direction, {0.0f, 0.0f, -shaft}, radius)); + const float a = (direction.x * direction.x) + (direction.y * direction.y); + if (a > 1.0e-12f) { + const float b = (origin.x * direction.x) + (origin.y * direction.y); + const float c = (origin.x * origin.x) + (origin.y * origin.y) - (radius * radius); + const float disc = (b * b) - (a * c); + if (disc >= 0.0f) { + const float t = (-b - std::sqrt(disc)) / a; + if (t >= 0.0f && std::abs(origin.z + (t * direction.z)) <= shaft) { + take(t); + } + } + } + return nearest; +} + /// Entry t of a unit ray into a world sphere or 0 from inside and none behind [[nodiscard]] auto raySphereEntry(const Ray& ray, glm::vec3 direction, glm::vec4 sphere) -> std::optional { @@ -1494,12 +1564,46 @@ auto Workspace::pickSceneHit() -> std::optional { }; std::vector candidates; + Box collider_node; + 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) { + if (!collider.draw_debug) { + return; + } + collider.syncTransform(); + glm::vec3 centre = collider.world_position; + if (const auto sphere = node.as(); sphere.exists()) { + if (const auto body = collider.parent().as(); body.exists()) { + body->syncTransform(); + centre = body->world_position + body->world_rotation * collider.position; + } + } + const glm::quat inverse = glm::inverse(collider.world_rotation); + const glm::vec3 origin = inverse * (ray->origin - centre); + const glm::vec3 local_direction = inverse * direction; + std::optional t; + if (const auto box = node.as(); box.exists()) { + t = rayBoxEntry(origin, local_direction, box->size * 0.5f); + } 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)); + } + if (t.has_value() && *t < collider_t) { + collider_t = *t; + collider_node = node; + } + }; const auto visit = [&](const auto& self, Box node) -> void { if (!node.exists() || !node->enabled()) { return; } - if (auto* voxels = reflect_cast(&*node)) { + if (auto* collider = reflect_cast(&*node)) { + pickCollider(*collider, node); + } else if (auto* voxels = reflect_cast(&*node)) { voxels->syncTransform(); const auto add = [&](const voxel::Volume* volume, const glm::mat4& model) { if (const auto entry = raySphereEntry(*ray, direction, voxel::worldBoundingSphere(model, volume->brickDims()))) { @@ -1575,6 +1679,11 @@ auto Workspace::pickSceneHit() -> std::optional { if (!voxel_hit) { hit = nearest(false); } + // A collider wins when its shown surface is in front of the geometry or flush with it + constexpr float k_collider_slack = 0.02f; + if (collider_node.exists() && (!hit.first.exists() || collider_t <= hit.second + k_collider_slack)) { + return SceneHit {.node = collider_node, .t = collider_t, .position = ray->origin + direction * collider_t}; + } if (!hit.first.exists()) { return std::nullopt; } diff --git a/vcpkg.json b/vcpkg.json index 359ba154e..9e61a4ab0 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -2,6 +2,11 @@ "name": "engine", "version-string": "1.0.0", "builtin-baseline": "e06564091c10e0b042900800c9fd48aad7f00643", + "vcpkg-configuration": { + "overlay-ports": [ + "./cmake/vcpkg-ports" + ] + }, "dependencies": [ { "name": "asio", @@ -140,6 +145,10 @@ } ], "version>=": "1.0.4" + }, + { + "name": "nvidia-dlss", + "platform": "windows & x64" } ], "overrides": [ 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 05/15] 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 06/15] 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 07/15] 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 08/15] 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 09/15] 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 10/15] 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 11/15] 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 12/15] 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; From 7c9757877af46b7f0d1a89841a8c842714ab782a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 27 Nov 2026 05:43:45 +0100 Subject: [PATCH 13/15] tonemapping and LUTs --- editor/Assets/Importers/KtxWriter.cs | 2 + editor/Components/Elements/ColorWheel.cs | 164 ++++++++++++++++++ editor/Editors/ColorWheelsPanel.cs | 81 +++++++++ editor/Editors/GenericModels.cs | 22 ++- editor/Editors/GenericView.axaml | 4 + editor/Editors/GenericViewModel.cs | 4 +- .../assets/schemas/post_process.schema.json | 111 ++++++++++++ engine/assets/shaders/tonemap.slang | 107 +++++++++++- engine/assets/textures/neutral_lut.ktx2 | Bin 0 -> 131344 bytes engine/assets/textures/neutral_lut.ktx2.meta | 4 + .../renderer/passes/post/tonemap_pass.cpp | 74 ++++++-- .../renderer/passes/post/tonemap_pass.hpp | 20 ++- .../renderer/resources/vulkan_texture.hpp | 5 + .../renderer/settings/post_process_params.cpp | 16 ++ .../settings/post_process_settings.hpp | 26 +++ tests/postprocess/01-blend.cpp | 14 ++ tools/color_grading/make_neutral_lut.py | 32 ++++ tools/color_grading/neutral_lut.png | Bin 0 -> 314 bytes 18 files changed, 670 insertions(+), 16 deletions(-) create mode 100644 editor/Components/Elements/ColorWheel.cs create mode 100644 editor/Editors/ColorWheelsPanel.cs create mode 100644 engine/assets/textures/neutral_lut.ktx2 create mode 100644 engine/assets/textures/neutral_lut.ktx2.meta create mode 100644 tools/color_grading/make_neutral_lut.py create mode 100644 tools/color_grading/neutral_lut.png diff --git a/editor/Assets/Importers/KtxWriter.cs b/editor/Assets/Importers/KtxWriter.cs index a38e98b0f..c7581c79d 100644 --- a/editor/Assets/Importers/KtxWriter.cs +++ b/editor/Assets/Importers/KtxWriter.cs @@ -87,6 +87,8 @@ private static string BuildArgs(TextureImporter.Settings s, string destPath, str break; case TextureCompression.None: default: + // An RGB source would stay 24 bit, which the engine refuses to upload + sb.Append("--target_type RGBA "); break; } diff --git a/editor/Components/Elements/ColorWheel.cs b/editor/Components/Elements/ColorWheel.cs new file mode 100644 index 000000000..559bcabf2 --- /dev/null +++ b/editor/Components/Elements/ColorWheel.cs @@ -0,0 +1,164 @@ +// +// ColorWheel.cs +// 27 Nov 2026 +// + +using System; +using System.Diagnostics; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Data; +using Avalonia.Input; +using Avalonia.Media; + +namespace editor.Components.Elements; + +/// Grading wheel for a tint stored as white plus a brightness free offset, the way the engine reads lift, gamma and gain +public class ColorWheel : Control { + /// Chroma at the rim, in Rec.709 Cb/Cr units + private const double RimChroma = 0.3; + + private const int RingSegments = 180; + private const double FineFactor = 0.1; + + public static readonly StyledProperty RProperty = + AvaloniaProperty.Register(nameof(R), 1f, defaultBindingMode: BindingMode.TwoWay); + + public static readonly StyledProperty GProperty = + AvaloniaProperty.Register(nameof(G), 1f, defaultBindingMode: BindingMode.TwoWay); + + public static readonly StyledProperty BProperty = + AvaloniaProperty.Register(nameof(B), 1f, defaultBindingMode: BindingMode.TwoWay); + + private Point m_lastPointer; + private bool m_dragging; + + static ColorWheel() { + AffectsRender(RProperty, GProperty, BProperty); + Debug.Assert(RoundTrips(0.1, -0.2) && RoundTrips(-0.3, 0.0) && RoundTrips(0.0, 0.25)); + } + + public ColorWheel() { + Cursor = new Cursor(StandardCursorType.Hand); + ToolTip.SetTip(this, "Drag to tint, Shift for fine, double click to reset"); + } + + public float R { get => GetValue(RProperty); set => SetValue(RProperty, value); } + public float G { get => GetValue(GProperty); set => SetValue(GProperty, value); } + public float B { get => GetValue(BProperty); set => SetValue(BProperty, value); } + + /// Tint for chroma (cb, cr): white plus the Y = 0 YCbCr colour, so its Rec.709 luminance is exactly 1 + public static (float R, float G, float B) TintFromChroma(double cb, double cr) { + return ((float)(1.0 + 1.5748 * cr), (float)(1.0 - 0.1873 * cb - 0.4681 * cr), (float)(1.0 + 1.8556 * cb)); + } + + /// Inverse of TintFromChroma; brightness a tint carries is ignored, as the engine ignores it + public static (double Cb, double Cr) ChromaFromTint(float r, float g, float b) { + var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + return ((b - luma) / 1.8556, (r - luma) / 1.5748); + } + + private static bool RoundTrips(double cb, double cr) { + var (r, g, b) = TintFromChroma(cb, cr); + var (cb2, cr2) = ChromaFromTint(r, g, b); + return Math.Abs(cb - cb2) < 1e-3 && Math.Abs(cr - cr2) < 1e-3; + } + + protected override Size MeasureOverride(Size availableSize) { + var side = double.IsInfinity(availableSize.Width) ? 120 : Math.Min(availableSize.Width, 160); + return new Size(side, side); + } + + public override void Render(DrawingContext context) { + var radius = Math.Min(Bounds.Width, Bounds.Height) / 2 - 2; + if (radius <= 4) return; + var center = new Point(Bounds.Width / 2, Bounds.Height / 2); + var ringInner = radius * 0.9; + + context.DrawEllipse(new SolidColorBrush(EditorColorPalette.Resolve("Bg1")), null, center, radius, radius); + + // Each segment shows the colour a dot in that direction gives, so the ring cannot disagree with the mapping + var thickness = 2 * Math.PI * radius / RingSegments * 1.6; + for (var i = 0; i < RingSegments; i++) { + var angle = 2 * Math.PI * i / RingSegments; + var (dx, dy) = (Math.Cos(angle), -Math.Sin(angle)); + var pen = new Pen(new SolidColorBrush(DisplayColor(dx, -dy, 2.0)), thickness); + context.DrawLine(pen, center + new Vector(dx, dy) * ringInner, center + new Vector(dx, dy) * radius); + } + + var cross = new Pen(new SolidColorBrush(Color.FromArgb(50, 255, 255, 255))); + context.DrawLine(cross, center - new Vector(ringInner, 0), center + new Vector(ringInner, 0)); + context.DrawLine(cross, center - new Vector(0, ringInner), center + new Vector(0, ringInner)); + + var (cb, cr) = ChromaFromTint(R, G, B); + var dot = center + new Vector(cb, -cr) * (ringInner / RimChroma); + context.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(120, 255, 255, 255))), center, dot); + context.DrawEllipse( + new SolidColorBrush(DisplayColor(cb / RimChroma, cr / RimChroma, 1.0)), new Pen(Brushes.White, 1.5), dot, 5, 5); + } + + /// Exaggerated so a small tint still reads on screen + private static Color DisplayColor(double cb, double cr, double strength) { + var (r, g, b) = TintFromChroma(cb * RimChroma * strength, cr * RimChroma * strength); + static byte Channel(float v) { + return (byte)Math.Clamp((v - 0.35) * 255 / 1.3, 0, 255); + } + + return Color.FromRgb(Channel(r), Channel(g), Channel(b)); + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) { + base.OnPointerPressed(e); + if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; + if (e.ClickCount == 2) { + Reset(); + e.Handled = true; + return; + } + + m_dragging = true; + m_lastPointer = e.GetPosition(this); + e.Pointer.Capture(this); + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) { + base.OnPointerMoved(e); + if (!m_dragging) return; + var position = e.GetPosition(this); + var delta = position - m_lastPointer; + m_lastPointer = position; + + var radius = Math.Min(Bounds.Width, Bounds.Height) / 2 * 0.9; + if (radius <= 0) return; + var scale = RimChroma / radius * (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? FineFactor : 1.0); + var (cb, cr) = ChromaFromTint(R, G, B); + cb += delta.X * scale; + cr -= delta.Y * scale; + + var length = Math.Sqrt(cb * cb + cr * cr); + if (length > RimChroma) { + cb *= RimChroma / length; + cr *= RimChroma / length; + } + + (R, G, B) = TintFromChroma(cb, cr); + e.Handled = true; + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) { + base.OnPointerReleased(e); + if (!m_dragging) return; + m_dragging = false; + e.Pointer.Capture(null); + } + + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) { + base.OnPointerCaptureLost(e); + m_dragging = false; + } + + public void Reset() { + (R, G, B) = (1f, 1f, 1f); + } +} diff --git a/editor/Editors/ColorWheelsPanel.cs b/editor/Editors/ColorWheelsPanel.cs new file mode 100644 index 000000000..780e0f352 --- /dev/null +++ b/editor/Editors/ColorWheelsPanel.cs @@ -0,0 +1,81 @@ +// +// ColorWheelsPanel.cs +// 27 Nov 2026 +// + +using System.Linq; +using Avalonia.Controls; +using Avalonia.Data; +using Avalonia.Layout; +using editor.Components.Elements; +using Lucide.Avalonia; + +namespace editor.Editors; + +/// Lift, gamma and gain wheels for an object field marked x-toast-widget "color_wheels" +public class ColorWheelsPanel : UserControl { + private static readonly (string Label, string Tint, string Offset)[] Wheels = [ + ("Lift", "lift", "lift_offset"), + ("Gamma", "gamma", "gamma_offset"), + ("Gain", "gain", "gain_offset") + ]; + + public ColorWheelsPanel() { + DataContextChanged += (_, _) => Build(); + } + + private void Build() { + Content = null; + // Every object row hosts this panel, only the marked one may claim its children + if (DataContext is not GenericFieldVM { IsColorWheels: true } group) return; + + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), Margin = new(0, 4, 0, 4) }; + for (var i = 0; i < Wheels.Length; i++) { + var (label, tintName, offsetName) = Wheels[i]; + var tint = group.Children.FirstOrDefault(c => c.Name == tintName && c.IsColor3); + var offset = group.Children.FirstOrDefault(c => c.Name == offsetName && c.IsFloat); + // A schema missing a field keeps its plain row rather than losing the control + if (tint is null || offset is null) continue; + tint.OwnedByWidget = true; + offset.OwnedByWidget = true; + + var column = BuildWheel(label, tint, offset); + Grid.SetColumn(column, i); + grid.Children.Add(column); + } + + Content = grid; + } + + private static StackPanel BuildWheel(string label, GenericFieldVM tint, GenericFieldVM offset) { + var wheel = new ColorWheel { HorizontalAlignment = HorizontalAlignment.Center }; + wheel.Bind(ColorWheel.RProperty, new Binding(nameof(GenericFieldVM.X)) { Source = tint, Mode = BindingMode.TwoWay }); + wheel.Bind(ColorWheel.GProperty, new Binding(nameof(GenericFieldVM.Y)) { Source = tint, Mode = BindingMode.TwoWay }); + wheel.Bind(ColorWheel.BProperty, new Binding(nameof(GenericFieldVM.Z)) { Source = tint, Mode = BindingMode.TwoWay }); + + var brightness = new DragFloatBox { Minimum = offset.Minimum, Maximum = offset.Maximum, Classes = { "compact-field" } }; + brightness.Bind(DragFloatBox.ValueProperty, + new Binding(nameof(GenericFieldVM.FloatVal)) { Source = offset, Mode = BindingMode.TwoWay }); + ToolTip.SetTip(brightness, "Brightness"); + + var reset = new Button { + Classes = { "icon-btn", "compact-control" }, + Content = new LucideIcon { Kind = LucideIconKind.RotateCcw, Size = 14, StrokeWidth = 2.5 }, + VerticalAlignment = VerticalAlignment.Center + }; + ToolTip.SetTip(reset, $"Reset {label.ToLowerInvariant()}"); + reset.Click += (_, _) => { + wheel.Reset(); + offset.FloatVal = 0f; + }; + + var header = new DockPanel(); + DockPanel.SetDock(reset, Avalonia.Controls.Dock.Right); + header.Children.Add(reset); + header.Children.Add(new TextBlock { + Text = label, Classes = { "lbl", "compact-text" }, VerticalAlignment = VerticalAlignment.Center + }); + + return new StackPanel { Spacing = 4, Margin = new(4, 0), Children = { header, wheel, brightness } }; + } +} diff --git a/editor/Editors/GenericModels.cs b/editor/Editors/GenericModels.cs index 1dcb5c4cc..45a429ebe 100644 --- a/editor/Editors/GenericModels.cs +++ b/editor/Editors/GenericModels.cs @@ -50,6 +50,12 @@ public partial class GenericFieldVM : ObservableObject, IRowSplittable, IRowVisi [ObservableProperty] private string m_unit = ""; [ObservableProperty] private bool m_variantVisible = true; + // Drawn by a widget on the parent (x-toast-widget) instead of as its own row + [ObservableProperty] private bool m_ownedByWidget; + + // x-toast-widget of this field + [ObservableProperty] private string m_widget = ""; + [ObservableProperty] private float m_x, m_y, m_z, m_w; public IReadOnlyList FieldTypes { get; set; } = AllFieldTypes; @@ -108,7 +114,9 @@ public IReadOnlyList EnumAllowedValues { public bool ShouldSplitRow => NameEditable; - public bool RowVisible => VariantVisible; + public bool RowVisible => VariantVisible && !OwnedByWidget; + + public bool IsColorWheels => IsObject && Widget == "color_wheels"; // IStructRow: true only for a struct (object) array element (no name, not editable, object type) public bool IsStructRow => IsArrayItem && IsObject; @@ -119,6 +127,14 @@ partial void OnVariantVisibleChanged(bool value) { NotifyDirty?.Invoke(); } + partial void OnOwnedByWidgetChanged(bool value) { + OnPropertyChanged(nameof(RowVisible)); + } + + partial void OnWidgetChanged(string value) { + OnPropertyChanged(nameof(IsColorWheels)); + } + partial void OnChildrenLockedChanged(bool value) { OnPropertyChanged(nameof(ChildrenEditable)); } @@ -135,6 +151,7 @@ partial void OnTypeKeyChanged(string value) { OnPropertyChanged(nameof(IsColor3)); OnPropertyChanged(nameof(IsColor4)); OnPropertyChanged(nameof(IsObject)); + OnPropertyChanged(nameof(IsColorWheels)); OnPropertyChanged(nameof(IsArray)); OnPropertyChanged(nameof(IsEnum)); OnPropertyChanged(nameof(IsVectorLayout)); @@ -435,6 +452,9 @@ public SchemaFieldDescriptor( public string DisplayName { get; init; } = ""; public string Unit { get; init; } = ""; + + /// Custom editor for the whole field (x-toast-widget), empty uses the default rows + public string Widget { get; init; } = ""; } public record TypeSwitchCase(string TypeKey, string DefaultStr); diff --git a/editor/Editors/GenericView.axaml b/editor/Editors/GenericView.axaml index 9e1bda7cb..18e835ea7 100644 --- a/editor/Editors/GenericView.axaml +++ b/editor/Editors/GenericView.axaml @@ -222,6 +222,10 @@ HorizontalAlignment="Center" VerticalAlignment="Center" Classes="compact-text" /> + + + ParseProperties(JsonObject props) { typeSwitch ) { DisplayName = val?["x-toast-display-name"]?.GetValue() ?? "", - Unit = val?["x-toast-unit"]?.GetValue() ?? "" + Unit = val?["x-toast-unit"]?.GetValue() ?? "", + Widget = val?["x-toast-widget"]?.GetValue() ?? "" }); } diff --git a/engine/assets/schemas/post_process.schema.json b/engine/assets/schemas/post_process.schema.json index de01a30a4..743079bd0 100644 --- a/engine/assets/schemas/post_process.schema.json +++ b/engine/assets/schemas/post_process.schema.json @@ -13,6 +13,10 @@ "tonemap": { "x-toast-type": "tonemap" }, + "color_grading": { + "x-toast-type": "color_grading", + "x-toast-widget": "color_wheels" + }, "fxaa": { "x-toast-type": "fxaa" }, @@ -331,6 +335,113 @@ } } }, + "color_grading": { + "type": "object", + "properties": { + "temperature": { + "type": "number", + "x-toast-type": "float", + "description": "White balance, warmer above 0", + "default": 0.0, + "minimum": -1, + "maximum": 1 + }, + "tint": { + "type": "number", + "x-toast-type": "float", + "description": "White balance, magenta above 0", + "default": 0.0, + "minimum": -1, + "maximum": 1 + }, + "color_filter": { + "type": "array", + "x-toast-type": "color3", + "description": "Multiplies the image", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "hue_shift": { + "type": "number", + "x-toast-type": "float", + "description": "Hue rotation in degrees", + "default": 0.0, + "minimum": -180, + "maximum": 180 + }, + "lift": { + "type": "array", + "x-toast-type": "color3", + "description": "Shadow tint", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "lift_offset": { + "type": "number", + "x-toast-type": "float", + "description": "Shadow brightness", + "default": 0.0, + "minimum": -1, + "maximum": 1 + }, + "gamma": { + "type": "array", + "x-toast-type": "color3", + "description": "Midtone tint", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "gamma_offset": { + "type": "number", + "x-toast-type": "float", + "description": "Midtone brightness", + "default": 0.0, + "minimum": -1, + "maximum": 1 + }, + "gain": { + "type": "array", + "x-toast-type": "color3", + "description": "Highlight tint", + "default": [ + 1.0, + 1.0, + 1.0 + ] + }, + "gain_offset": { + "type": "number", + "x-toast-type": "float", + "description": "Highlight brightness", + "default": 0.0, + "minimum": -1, + "maximum": 1 + }, + "lut": { + "type": "string", + "x-toast-type": "asset", + "description": "LUT strip, imported linear without compression or mipmaps", + "x-toast-asset-type": "texture" + }, + "lut_intensity": { + "type": "number", + "x-toast-type": "float", + "description": "Mix toward the LUT grade", + "default": 1.0, + "minimum": 0, + "maximum": 1 + } + } + }, "fxaa": { "type": "object", "properties": { diff --git a/engine/assets/shaders/tonemap.slang b/engine/assets/shaders/tonemap.slang index e51e6b695..0a720ac3b 100644 --- a/engine/assets/shaders/tonemap.slang +++ b/engine/assets/shaders/tonemap.slang @@ -34,6 +34,22 @@ struct TonemapParams // 0.01 moves red and blue 1% of the distance to the centre float chromaticAberration; + + // White balance, -1 to 1 + float temperature; + float tint; + + // w is the hue shift in degrees + float4 colorFilter; + + // Prepared on the CPU, neutral is lift 0, gammaInv 1, gain 1 + float4 lift; + + // w is 1 when the LUT has an sRGB format and its samples come back linear + float4 gammaInv; + + // w is the LUT intensity, 0 when no LUT is bound + float4 gain; }; [[vk::binding(0,0)]] @@ -46,6 +62,10 @@ Sampler2D gSceneColor; [[vk::binding(2,0)]] StructuredBuffer gExposure; +// Strip of N slices of NxN, red across a slice, green down, blue picks the slice. The scene stands in when unbound +[[vk::binding(3,0)]] +Sampler2D gLut; + typedef FullscreenVSOutput VSOutput; [shader("vertex")] @@ -74,6 +94,73 @@ float3 tonemapACES(float3 color) return saturate((color * (a * color + b)) / (color * (c * color + d) + e)); } +// CAT02 von Kries adaptation from D65 toward the illuminant temperature and tint pick, coefficients are 1 at 0, 0 +float3 whiteBalance(float3 c, float temperature, float tint) +{ + const float t1 = temperature * (100.0 / 65.0); + const float t2 = tint * (100.0 / 65.0); + const float x = 0.31271 - t1 * (t1 < 0.0 ? 0.1 : 0.05); + const float y = 2.87 * x - 3.0 * x * x - 0.27509507 + t2 * 0.05; + const float3 xyz = float3(x / y, 1.0, (1.0 - x - y) / y); + const float3 lms = float3( + dot(xyz, float3(0.7328, 0.4296, -0.1624)), + dot(xyz, float3(-0.7036, 1.6975, 0.0061)), + dot(xyz, float3(0.0030, 0.0136, 0.9834))); + const float3 coeffs = float3(0.949237, 1.03542, 1.08728) / lms; + + const float3x3 toLms = float3x3( + 0.390405, 0.549941, 0.00892632, + 0.0708416, 0.963172, 0.00135775, + 0.0231082, 0.128021, 0.936245); + const float3x3 fromLms = float3x3( + 2.85847, -1.62879, -0.024891, + -0.210182, 1.1582, 0.000324281, + -0.041812, -0.118169, 1.06867); + return mul(fromLms, mul(toLms, c) * coeffs); +} + +// Rotation about the grey axis keeps luminance roughly where it was +float3 hueShift(float3 c, float degrees) +{ + const float3 k = float3(0.57735027, 0.57735027, 0.57735027); + const float a = radians(degrees); + const float cosA = cos(a); + return c * cosA + cross(k, c) * sin(a) + k * dot(k, c) * (1.0 - cosA); +} + +float3 gradeLinear(float3 c) +{ + // The LMS matrices turn an fp16 overflow into Inf - Inf, the same range GT7 clamps to keeps it white + c = clamp(c, float3(0.0, 0.0, 0.0), float3(65000.0, 65000.0, 65000.0)); + c = whiteBalance(c, gParams.temperature, gParams.tint); + c *= gParams.colorFilter.rgb; + c = hueShift(c, gParams.colorFilter.w); + c = c * gParams.gain.rgb + gParams.lift.rgb; + c = sign(c) * pow(abs(c), gParams.gammaInv.rgb); + return max(c, float3(0.0, 0.0, 0.0)); +} + +float3 linearToSrgb(float3 c) +{ + c = saturate(c); + return select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0 / 2.4) - 0.055); +} + +// Takes display encoded colour, the space the LUT was graded in +float3 applyLut(float3 c) +{ + uint w, h; + gLut.GetDimensions(w, h); + const float n = float(h); + c = saturate(c) * (n - 1.0); + const float slice = floor(c.b); + const float2 uv = float2((c.r + 0.5 + slice * n) / float(w), (c.g + 0.5) / n); + const float3 a = gLut.SampleLevel(uv, 0).rgb; + const float3 b = gLut.SampleLevel(uv + float2(n / float(w), 0.0), 0).rgb; + const float3 graded = lerp(a, b, c.b - slice); + return gParams.gammaInv.w > 0.5 ? linearToSrgb(graded) : graded; +} + float ditherOffset(float2 pixel) { float noise = frac(52.9829189 * frac(dot(pixel, float2(0.06711056, 0.00583715)))); @@ -103,6 +190,8 @@ float4 fragmentMain(VSOutput input) : SV_Target0 color = gSceneColor.Sample(input.uv).rgb * exposure; } + color = gradeLinear(color); + const bool hdr = gParams.hdr != 0u; if (gParams.mode == 2) { @@ -127,8 +216,20 @@ float4 fragmentMain(VSOutput input) : SV_Target0 float lum = luminance(color); color = max(lerp(float3(lum, lum, lum), color, gParams.saturation), float3(0.0, 0.0, 0.0)); + const float invGamma = 1.0 / max(gParams.gamma, 1e-4); + const float lutIntensity = gParams.gain.w; + if (hdr) { + if (lutIntensity > 0.0) + { + // The LUT only covers up to paper white, so it grades hue and chroma and brightness above that is kept + const float scale = max(max(color.r, max(color.g, color.b)), 1.0); + const float3 encoded = pow(color / scale, float3(invGamma, invGamma, invGamma)); + const float3 graded = pow(applyLut(encoded), float3(gParams.gamma, gParams.gamma, gParams.gamma)) * scale; + color = lerp(color, graded, lutIntensity); + } + if (gParams.vignette > 0.0) { float2 centered = input.uv - 0.5; @@ -145,9 +246,13 @@ float4 fragmentMain(VSOutput input) : SV_Target0 return float4(min(max(color, float3(0.0, 0.0, 0.0)) * gParams.paperWhiteScale, float3(gParams.peakScale, gParams.peakScale, gParams.peakScale)), 1.0); } - float invGamma = 1.0 / max(gParams.gamma, 1e-4); color = pow(max(color, float3(0.0, 0.0, 0.0)), float3(invGamma, invGamma, invGamma)); + if (lutIntensity > 0.0) + { + color = lerp(color, applyLut(color), lutIntensity); + } + if (gParams.vignette > 0.0) { float2 centered = input.uv - 0.5; diff --git a/engine/assets/textures/neutral_lut.ktx2 b/engine/assets/textures/neutral_lut.ktx2 new file mode 100644 index 0000000000000000000000000000000000000000..e611d31aad8df72ec3b3d44a9fbe5fd9fbbd2439 GIT binary patch literal 131344 zcmZ79J&dgYz~^PwnCyv(kyweDQPJw@fmkl6DRk{+&drlm$`SQ_;Y~sfBfhF<$v`L|LK47fBxJ5*1!L6{Rcr1 z{1bwIGYJ0S@AbcW`Fq>{^LDTQNB(R6Fa8Vu|1aUc{=neh_*d`xm#_am=kMj;2>z?! zpZt@5`9U)O>gAvQ>)!;Q-~EDr`v3kde}4{xfBLWgvj6A(|6cG<|DAvR34ibZckyNX z^MCQr{`>#=AOD+w{Ad6Ce-8e|f9Gxg;lF(Q|MoBb*+2gG|04Luf8PA#|NamE>woqi z{b&EtfBFyq@jv`e|Lnj0|Ni_R{;&1_()!<(I|LOnqfBHZDpZ-t(r~lLc>HqY9`ak`j{!jm>|I`2J|MY+Q zKmDKnPyeU?)BoxJ^ndz4{h$6%KhzKPL;X-c)DQJT{ZK#D5A{R+P(RcU^+WwoKhzKP zL;X-c)DQJT{ZK#D5A{R+P(RcU^+WwoKhlr%BmGD}(vS2b{YXF3kMtw`NI%k#^dtR9 zKhlr%BmGD}(vS2b{YXF3kMtw`NI%k#^dtR9Kh}@+WBph^){pgL{a8QNkM(2ySU=W} z^<({5Kh}@+WBph^){pgL{a8QNkM(2ySU=W}^<({5KhaP06a7R#(NFXf{X{>}PxKT0 zL_g6_^b`F=KhaP06a7R#(NFXf{X{>}PxKT0L_g6_^b`F=Kh;n5Q~gvw)lcOh41l^fUcTKhw|jGyP0I)6euX{Y*d8&-63>Oh41l^fUcTKiALobNyUD z*U$BH{aioS&-HWtTtC;(^>h7PKiALobNyUD*U$BH{aioS&-HWtTtC;(^>h7PztAuA z3;jaB&@c20{X)OcFZ2ujLch>2^b7q$ztAuA3;jaB&@c20{X)OcFZ2ujLch>2^b7q$ zztk`FOZ`&6)Gzf*{ZhZwFZE0PQoqzM^-KLyztk`FOZ`&6)Gzf*{ZhZwFZE0PQoqzM z^-KLyztXStEB#8p(y#O@{Yt;mukJztXStEB#8p(y#O@{Yt;mukJzt*qyYyDck*01$z{aU})uk~yFTEEt>^=tiFzt*qyYyDck*01$z{aU}) zuk~yFTEEt>^=tiFztL~>8~sMV(Qot{{YJmhZ}c1eM!(T-^c(#~ztL~>8~sMV(Qot{ z{YJmhZ}c1eM!(T-^c(#~ztwN`Tm4qQ)o=A%{Z_x#Z}nUKR=?G6^;`W`ztwN`Tm4qQ z)o=A%{Z_x#Z}nUKR=?G6^;`W`ztivZJN-_-)9>^<{Z7Br@ANzUPQTOd^gI1dztivZ zJN-_-)9>^<{Z7Br@ANzUPQTOd^gI1dzt`{ed;MO&*YEXv{a(M<@AZ5AUccAx^?UtZ zzt`{ed;MO&*YEXv{a(M<@AZ5AUccAx^?UtZf6yQF2mL{R&>!>%{Xu`wAM^+PL4VL6 z^auSxf6yQF2mL{R&>!>%{Xu`wAM^+PL4VL6^auSxf7BoKNBvQM)F1Un{ZW6^AN5E5 zQGe7Q^+)|tf7BoKNBvQM)F1Un{ZW6^AN5E5QGe7Q^+)|tf6|}yC;dr((x3Dv{Yih) zpY$jFNq^Fx^e6pEf6|}yC;dr((x3Dv{Yih)pY$jFNq^Fx^e6pEf7YM%XZ=}!)}Qrf z{aJt3pY><`S%21_^=JKAf7YM%XZ=}!)}Qrf{aJt3pY><`S%21_^=JKAf6-s`7yU(l z(O>iz{Y8J#U-TFKMSsy>^cVd_f6-s`7yU(l(O>iz{Y8J#U-TFKMSsy>^cVd_f7M_0 zSN&Cg)nD~j{Z)U}U-ei0Re#lA^;i8>f7M_0SN&Cg)nD~j{Z)U}U-ei0Re#lA^;i8> zf79ReH~me2)8F(r{Y`(<-}E>AO@Gth^f&!Yf79ReH~me2)8F(r{Y`(<-}E>AO@Gth z^f&!Yf7jpjcl}*|*WdMb{at_8-}QI>U4Pf#^>_VUf7jpjcl}*|*WdMb{at_8-}QI> zU4Pf#^>_VU|Ik155B)>`&_DDK{X_rIKlBg%L;uh}^bh?*|Ik155B)>`&_DDK{X_rI zKlBg%L;uh}^bh?*|I|PAPyJK>)Iar4{Zs$cKlM-jQ~%UI^-uj%|I|PAPyJK>)Iar4 z{Zs$cKlM-jQ~%UI^-uj%|I)woFa1mZ(!caC{Y(GSzw|HtOaIcp^e_EO|I)woFa1mZ z(!caC{Y(GSzw|HtOaIcp^e_EO|JJ|tZ~a^U*1z>{{agRmzx8kZTmRO-^>6)K|JJ|t zZ~a^U*1z>{{agRmzx8kZTmRO-^>6)K|IvT+AN@!F(SP(G{YU@NfAk;yNB_}(^dJ34 z|IvT+AN@!F(SP(G{YU@NfAk;yNB_}(^dJ34|J8r>U;S7A)qnM0{a63hfAwGeSO3+2 z^U;S7A)qnM0{a63hfAwGeSO3+2^>Qk2+&sMeec{2+{wE|NCLtvwr=X;wrlF;yXJBMvW?^Mx=iubx=HW$H z-~J~gA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJyBly|>gha$7q-5k2lvLC-v~=_g zj7-cdtZeKYoLt;IynF;d`=5}An1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=;Aj66 z5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)7*(e?lT+5>hg93Q8(!8d^Gf21X`k z7FITP4o)s^9$r3zpZ!lrL`*_TMovLVMNLCXN6)~>#LU9V#?HaX#m&RZNAR=%35keF zNXf`4D5!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHRv z+5dz@#3ZC->Qk2+&sK|1V8(qkcgOsl#HB$l8Ty!mX4l* zk%^gwm5rT)lZ%^&myh6Q{}U1slaP{;Q&3V-)6mk9I(i01CT12^Hg*n9E^Z!PK7yb9Pe?>eLP|zXK}khTLrX``z{teR z!pg?Z!O6wV!^=nTv;PT+h)GDv$SEkPsA*{F=ouK9m|0la*f}`4xOsT_2!8fIArUbN zDH%BhB^5OdEgd}rBNH8 zar5x<5&Z0bLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOxUFhW?wPArUbNDH%Bh zB^5OdEgd}rBNH9I(i01CT12^Hg*n9 zE^Z!P{tkKszVII*5itoV8948ar5vZs&D@j5)qS-l95wTQc=^;($O<8GBLBTvaxe; za&hzU@)3mgKOqq@2`L#l1tk?V4J{o#10xeN3o9Et2PYRd4=*18ar5x<5rp8ar5x<5rp8ar5x<5rp8ar5x<5rpF604nV4Bv z+1NQaxwv_F`3NHWpOA={gp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ5avi}K*h)GDv z$SEkPsA*{F=ouK9m|0la*f}`4xOsT_2qOERkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT) zlZ%^&myaN_{|SkRNl3}aDJZF^X=v%_85o(ESyF604nV4Bv+1NQaxwv_F`3NHWpOA={gp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ5a zvi}K*h)GDv$SEkPsA*{F=ouK9m|0la*f}`4xOsT_2qOERkcgOsl#HB$l8Ty!mX4l* zk%^gwm5rT)lZ%^&myaN_{|SkRNl3}aDJZF^X=v%_85o(ESyF604nV4Bv+1NQaxwv_F`3NHWpOA={gp`b&f|81whL(<=fsu)sg_Vt+ zgOiJ!hnJ5avi}K*h)GDv$SEkPsA*{F=ouK9m|0la*f}`4xOsT_2qOERkcgOsl#HB$ zl8Ty!mX4l*k%^gwm5rT)lZ%^&myaN_{|SkRNl3}aDJZF^X=v%_85o(ESyXLP|zXK}khTLrX``z{teR!pg?Z z!O6wV!^=nDf`cC+5itoV8948ar5x<5ybXCArUbNDH%Bh zB^5OdEgd}rBNH8ar5x<5ybXC zArUbNDH%BhB^5OdEgd}rBNH8 zar5x<5ybXCArUbNDH%BhB^5OdEgd}rBNH9I(i01CT12^Hg*n9E^Z!P{%&*-xY*%GNJLCR zN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%io0-fs-wMgha$7q-5k2lvLC-v~=_gj7-cd ztZeKYoLt;Iy!@T$5jfcMBP1dwAtfWHproRvp{1i|U}R!uVP#|I;N;@w;pOi@Q{bEJ zM@U3WLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^__{dXU)vgha$7q-5k2lvLC-v~=_g zj7-cdtZeKYoLt;Iya?&r|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4aiTzJV zL`*_TMovLVMNLCXN6)~>#LU9V#?HaX#m&RZN08Y6gha$7q-5k2lvLC-v~=_gj7-cd ztZeKYoLt;IynFeLP|zXK}khTLrX``z{teR!pg?Z z!O6wV!^=mI*#Cq?#3ZC->Qk2+&sK|1d07mNJLCRN=8mW zNkvUVOGnSZ$i&RT%Er#Y$;HjX%SVvd|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO- zJiL4aiTzJVL`*_TMovLVMNLCXN6)~>#LU9V#?HaX#m&RZN08Y6gha$7q-5k2lvLC- zv~=_gj7-cdtZeKYoLt;IynFeLP|zXK}khTLrX`` zz{teR!pg?Z!O6wV!^=mI*#Cq?#3ZC->Qk2+&sK|1d07m zNJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%SVvd|Aa)uB&1~I6qHodG_-W|42(?7 zEUawo9GqO-JiL4aiTzJVL`*_TMovLVMNLCXN6)~>#LU9V#?HaX#m&RZN08Y6gha$7 zq-5k2lvLC-v~=_gj7-cdtZeKYoLt;IynFeLP|zX zK}khTLrX``z{teR!pg?Z!O6wV!^=mI*#Cq?#3ZC->Qk2 z+&sK|1d07mNJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%SVvd|Aa)uB&1~I6qHod zG_-W|42(?7EUawo9GqO-JiL7T-G=<{R%CydBmbR}{P(cr-!w_d$SEkPsA*{F=ouK9 zm|0la*f}`4xOsT_2;6A!M@U3WLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^_`I4g)tj z_z@BjlaP{;Q&3V-)6mkYA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJy z?9I(i01CT12^Hg*n9E^Z!P{(i`U)cz+VA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H z;^yH+MBn}=BqAmuB_pSxq@t#wrK4wHWMXDvWn<^yhg93Q8(! z8d^Gf21X`k7FITP4o)s^9$r3z)cz+VA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJy zBS`IkLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs}<{wE|NCLtvwr=X;wrlF;y zXJBMvW?^Mx=iubx=HcZdNbP?@B4QF!GI9z^Dry>9I(i01CT12^Hg*n9E^Z!PK7!Q# zCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHPp?SDcdViHm^atcZ+Y8qNPdIm-& zW)@a9b`DN1ZXRAfg4F&eBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yhg93Q8(!8d^Gf21X`k7FITP4o)s^9$r3z)cz+VA|@dvBd4IGqNbsxqi0}bVrF4w zW9Q)H;^yJyBS`IkLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs}<{wE|NCLtvw zr=X;wrlF;yXJBMvW?^Mx=iubx=HcZdNbP?@B4QF!GI9z^Dry>9I(i01CT12^Hg*n9 zE^Z!PK7!Q#CnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHPp?SDcdViHm^atcZ+ zY8qNPdIm-&W)@a9b`DN1ZXRAfg4F&eBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yhg93Q8(!8d^Gf21X`k7FITP4o)s^9$r3z)cz+VA|@dvBd4IGqNbsx zqi0}bVrF4wW9Q)H;^yJyBS`IkLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs}< z{wE|NCLtvwr=X;wrlF;yXJBMvW?^Mx=iubx=HcZdNbP?@B4QF!GI9z^Dry>9I(i01 zCT12^Hg*n9E^Z!PK7!Q#CnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHPp?SDcd zViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAf{+3;N;J=3k|K>qP zPC-dUO+!mZ&%nsU%)-jX&cVsW&BMz_;7JC4gha$7q-5k2lvLC-v~=_gj7-cdtZeKY zoLt;Iy!<`ELEt8bKSCm65>hg93Q8(!8d^Gf21X`k7FITP4o)s^9$x-#uo$?>!jF)M zn1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?Ub8$1Lq^7s)F5tERTkyB7oQPa@U(K9eI zF|)9;v2$>8ar5xF604nV4Bv+1NQaxwv_F`8&WC_#yid5)qS-l95wTQc=^; z($O<8GBLBTvaxe;a&hzU^7jKCWcEKH5itoV894{}U1slaP{;Q&3V-)6mk< zGcYnSv#_$Ub8vET^YHQ!WcEKH5itoV8948ar5x<5oGp1ArUbNDH%BhB^5OdEgd}rBNH{}U1slaP{; zQ&3V-)6mk8ar5x<5oGp1ArUbNDH%BhB^5OdEgd}rBNH z{}U1slaP{;Q&3V-)6mk{MD z7_j(9NJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%Wt@2V8Fv4ArUbNDH%BhB^5Od zEgd}rBNHhg93Q8(!8d^Gf21X`k7FITP z4o)s^9$tPwE8ar5x<5#;)xkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT) zlZ%^&myaOV|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4ax&9|4A|@dvBd4IG zqNbsxqi0}bVrF4wW9Q)H;^yJyBgpkXArUbNDH%BhB^5OdEgd}rBNH#LU9V#?HaX#m&RZN094(LLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs|c z{}U1slaP{;Q&3V-)6mk9I(i01CT12^Hg*n9 zE^Z!PK7w5T6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVGl`k#=9n1qy!oPv^y znueB+o`I2xnT3^&or9B$n}?T=AlLtdM8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--do zd<41vCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHR9^*F604nV4Bv+1NQaxwv_F`3T$w z|5joD)?xidV*kcs{a%gz9gqF}i|lusTu@R`)6mkhg93Q8(!8d^Gf21X`k z7FITP4o)s^9$tQn6$8r^{s@VPNl3}aDJZF^X=v%_85o(ESy>Qk2+&sMe zUaScmuK6P*A|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJycd#e$aPN>Qk2+&sMaVBfF*35keFNXf`4 zD59I(i01CT12^Hg*n9E^Z!PK7vC36A}@Vkdl#8P*PFT z(9+Q}FfuW-u(GjpaB^|;@bVE9`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T= zpwRz>M8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<2F5CnO>!AtfWHproRvp{1i| zU}R!uVP#|I;N;@w;pHPJ^gkgHF$pOdIRzyZH4QBtJp&^XGYcylI|nBhHxDl#L81Q% ziHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F`3MUAPe?>eLP|zXK}khTLrX``z{teR z!pg?Z!O6wV!^=ld=zl^YViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAff>Qk2+&sK|1cm-5BqAmuB_pSx zq@t#wrK4wHWMXDvWn<^yhg93Q8(!8d^Gf21X`k7FITP4o)s^9$r3z zLjMyI5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x<5fu8LkcgOsl#HB$l8Ty!mX4l* zk%^gwm5rT)lZ%^&myf`0=pVmz)W4Nfzp>Q6(Nw?JQ-4QPfB&ZX-Kv&U)HJko^bCwl z%q*;I>>Qk2+&sK|1f~8bBqAmuB_pSxq@t#wrK4wHWMXDvWn<^y?nq7%cfm zNJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%WtSArUbNDH%BhB^5OdEgd}r zBNHm-KSCm65>hg93Q8(!8d^Gf21X`k7FITP4o)s^ z9$tPwszIs$35keFNXf`4D58ar5x<5tRC$kcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^& zmye*-|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4arT!-*A|@dvBd4IGqNbsx zqi0}bVrF4wW9Q)H;^yJyBPjJhArUbNDH%BhB^5OdEgd}rBNH z#LU9V#?HaX#m&RZM^Ng2LLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs|S{}U1s zlaP{;Q&3V-)6mk@A35keFNXf`4D59I(i01CT12^Hg*n9E^Z!P zK7vyJ6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVFq`k#=9n1qy!oPv^ynueB+ zo`I2xnT3^&or9B$n}?T=pw$0_M8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<3Qb zCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHQ68~8`aZzc3^E!1x`^lv=W?-kMC zG11?@ihj3?6*Ubl9X$gh6Eh1d8#@Ol7dH%635keFNXf`4D59I(i01CT12^Hg*n9E^Z!PK7vaB6A}@Vkdl#8P*PFT(9+Q}FfuW-u(Gjp zaB^|;@bX(I8C3e8kcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^&m)}B*pwj<@M8qVd zWaJc-RMa%Ibo302Ow25-Z0sDIT--do{03?UmHsCrA|@dvBd4IGqNbsxqi0}bVrF4w zW9Q)H;^yJyH_#*SQqLbD5itoV8946P ziHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F`5kBqJkhg93Q8(!8d^Gf z21X`k7FITP4o)s^9$r3zO8*lQ5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x<5mfr0 zkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^&mye**|Aa)uB&1~I6qHodG_-W|42(?7 zEUawo9GqO-JiL4amHsCrA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJyBdGL0ArUbN zDH%BhB^5OdEgd}rBNH#LU9V#?HaX#m&RZM^Nd1LLy=kQZjN1 zN-Am^S~_|LMkZz!RyKAHPA+a9UOs|K{}U1slaP{;Q&3V-)6mk%635keFNXf`4D59I(i01CT12^Hg*n9E^Z!PK7vaB6A}@Vkdl#8P*PFT(9+Q}FfuW- zu(GjpaB^|;@bVE<`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=z-`zcArUbN zDH*@lG=E1mfB&xe-Llm*v~=_gj7-cdtZeKYoLt;IynF<;{wE|NCLtvwr=X;wrlF;y zXJBMvW?^Mx=iubx=HcZdsP#V~5itoV894t6ArUbNDH%BhB^5OdEgd}rBNH}& zNZ^H{KSCm65>hg93Q8(!8d^Gf21X`k7FITP4o)s^9$tPgGX)Mb{SguolaP{;Q&3V- z)6mk9I(i01CT12^Hg*n9 zE^Z!PK7v~R6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVGV`k#=9n1qy!oPv^y znueB+o`I2xnT3^&or9B$n}?T=pw|C{M8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--do zd<3=rCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHQ!^*F604nV4Bv+1NQaxwv_F`3P$L zPe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^=ld>wiKbViHm^atcZ+Y8qNPdIm-& zW)@a9b`DN1ZXRAff?EF*5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)6YfpOA={ zgp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ6_*8hY=#3ZC->Qk2+&sK|1hxJrBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yhg93Q8(! z8d^Gf21X`k7FITP4o)s^9$r3zTK^Lg5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x< z5x5QdBP1f`w;K7k9x3BDCh7O8x435keF zNXf`4D5M@U3WLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^>}wN#JFs zKSCm65>hg93Q8(!8d^Gf21X`k7FITP4o)s^9$tPgQUwlE{SguolaP{;Q&3V-)6mk< zGcYnSv#_$Ub8vET^YHRJ$Q5{)`$tGbOhQUVPC-dUO+!mZ&%nsU%)-jX&cVsW&BM#@ zL2}??@<&KSOhQUVPC-dUO+!mZ&%nsU%)-jX&cVsW&BM#@LKZaopOA={gp`b&f|81w zhL(<=fsu)sg_Vt+gOiJ!hZi5@`}IE|5itoV894x435keFNXf`4D59I(i01CT12^Hg*n9E^Z!PK7vO7 z6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVEf`k#=9n1qy!oPv^ynueB+o`I2x znT3^&or9B$n}?T=pwa(?M8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<2dDCnO>! zAtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHP}^gkgHF$pOdIRzyZH4QBtJp&^XGYcyl zI|nBhHxDl#L8Jc(iHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F`3M^QPe?>eLP|zX zK}khTLrX``z{teR!pg?Z!O6wV!^=m|=zl^YViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1 zZXRAff=2%n5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)0!ppOA={gp`b&f|81w zhL(<=fsu)sg_Vt+gOiJ!hnJ6_(f@=*#3ZC->Qk2+&sK| z1daYDBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yxnadV~T&Hihi#v{*EmE{%!HQb!qA785o(E zSy#LU9V#?HaX#m&RZN6_kjLLy=k zQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs|W{}U1slaP{;Q&3V-)6mk^c{s@VPNl3}aDJZF^X=v%_85o(E zSyeLP|zXK}khTLrX`` zz{teR!pg?Z!O6wV!;25`{raDfh?s}C35keF zNXf`4D59I(i01CT12^Hg*n9E^Z!PK7v;N6A}@Vkdl#8 zP*PFT(9+Q}FfuW-u(GjpaB^|;@bVF~`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$ zn}?T=pw<6`M8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<3ojCnO>!AtfWHproRv zp{1i|U}R!uVP#|I;N;@w;pHP}^*iHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F`3PG5Pe?>eLP|zXK}khTLrX`` zz{teR!pg?Z!O6wV!^=m|>VHBaViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAff>!?% z5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)5WV_#-4DCLtx`w#LU9V#?HaX#m&RZN6_hiLLy=kQZjN1N-Am^ zS~_|LMkZz!RyKAHPA+a9UOs|O{}U1slaP{;Q&3V-)6mk!AtfWHproRvp{1i|U}R!u zVP#|I;N;@w;l&5|e*I5KL`*_TMovLVMNLCXN6)~>#LU9V#?HaX#m&RZN6_hiLLy=k zQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs|O{}U1slaP{;Q&3V-)6mk-835keFNXf`4D59I(i01CT12^Hg*n9E^Z!PK7vmF6A}@Vkdl#8P*PFT(9+Q} zFfuW-u(GjpaB^|;@bVFK`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=pws_^ zM8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<32TCnO>!AtfWHproRvp{1i|U}R!u zVP#|I;N;@w;pHRf^gkgHF$pOdIRzyZH4QBtJp&^XGYcylI|nBhHxDl#fy?k8ArUbN zDH*>ty}wmGzj3|4kv+fH_I^kAevj{em++o}k%^gwm5rT)lZ%^&mye*=|Aa)uB&1~I z6qHodG_-W|42(?7EUawo9GqO-JiL4az5XX8A|@dvBd4IG`lsj)!DWM@0E~(^s-h^W zq9}^0D2l2mimE7zqAH4_DvIu!u-bj!q&MTo*_)b%mX4l*k%^gwm5rT)lZ%^&mye*= z|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4az5XX8A|@dvBd4IGqNbsxqi0}b zVrF4wW9Q)H;^yJyBk1)%ArUbNDH%BhB^5OdEgd}rBNH#LU9V z#?HaX#m&RZN6_nkLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOoZ~ME?khh)GDv z$SEkPsA*{F=ouK9m|0la*f}`4xOsT_EiVl$F!>`SA|@dvBd4IGqNbsxqi0}bVrF4w zW9Q)H;^yJyw>%{9I(i01CT12^Hg*n9E^Z!Pe#2t|2gv>iiHJ!^$;c@vsiF604 znV4Bv+1NQaxwv_F`5j&hyukKHNJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%kSm6 zzzy_2LLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UVb<413%z@gha$7q-5k2lvLC- zv~=_gj7-cdtZeKYoLt;Iy!9 zI(i01CT12^Hg*n9E^Z!PK7wBV6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVG# z`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=px6I|M8qVdWaJc-RMa%Ibo302 zOw25-Z0sDIT--dod<4DzCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHRf^*F604nV4Bv z+1NQaxwv_F`3QRbPe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^=m|>wiKbViHm^ zatcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAff?od<5)qS-l95wTQc=^;($O<8GBLBTvaxe; za&hzU@)7j#3ZC->Qk2+&sK|1ik(zBqAmuB_pSxq@t#wrK4wHWMXDvWn<^y9I(i01CT12^Hg*n9E^Z!PK7v926A}@Vkdl#8P*PFT(9+Q} zFfuW-u(GjpaB^|;@bVE1`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=V9@`B zM8qVdWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<293CnO>!AtfWHproRvp{1i|U}R!u zVP#|I;N;@w;pHP3^gkgHF$pOdIRzyZH4QBtJp&^XGYcylI|nBhHxDl#!Jz*MiHJ!^ z$;c@vsiF604nV4Bv+1NQaxwv_F`3MI6Pe?>eLP|zXK}khTLrX``z{teR!pg?Z z!O6wV!^=l7=zl^YViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAf0?SMP2#JVENXf`4 zD5hg93Q8(!8d^Gf21X`k7FITP4o)s^9$tQfYXXPY{s@VPNl3}aDJZF^X=v%_85o(E zSy_eV%XOhQUVPC-dUO+!mZ&%nsU%)-jX&cVsW&BM#@#l67I z`#(Y=ViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRBK4-Nts4}XM2#3ZC->Qk2+&sMeE?j~^{}U1slaP{;Q&3V-)6mkhg93Q8(!8d^Gf z21X`k7FITP4o)s^9$r3zLH`pH5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x<5e)jD zkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^&mycl3|Aa)uB&1~I6qHodG_-W|42(?7 zEUawo9GqO-JiL4agZ?KZA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJyBN+5QArUbN zDH%BhB^5OdEgd}rBNH#LU9V#?HaX#m&RZM=hg93Q8(!8d^Gf21X`k7FITP4o)s^9$r3zQU4PX5tERTkyB7oQPa@U(K9eI zF|)9;v2$>8ar5x<5sdnukcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^&mycl7|Aa)u zB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4aqy8r(A|@dvBd4IGqNbsxqi0}bVrF4w zW9Q)H;^yJyBN+8RArUbNDH%BhB^5OdEgd}rBNH#LU9V#?HaX z#m&RZM==|B4QF! zGI9z^Dry>9I(i01CT12^Hg*n9E^Z!PenWEt2j~6>iHJ!^$;c@vsiF604nV4Bv z+1NQaxwv_F`5oE|ytwyANJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%kQPZz=MN7 zLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UVaZP0v9fSgha$7q-5k2lvLC-v~=_g zj7-cdtZeKYoLt;Iy!Hky5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU;ve~Z z{ZB|lOhQUVPC-dUO+!mZ&%nsU%)-jX&cVsW&BMz_FzSCoB4QF!GI9z^Dry>9I(i01 zCT12^Hg*n9E^Z!PK7vvI6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVFi`k#=9 zn1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=VATJFM8qVdWaJc-RMa%Ibo302Ow25- zZ0sDIT--dod<3KZCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHP3^*F604nV4Bv+1NQa zxwv_F`3Oe+Pe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^=l7>VHBaViHm^atcZ+ zY8qNPdIm-&W)@a9b`DN1ZXRAff>Hky5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU z@)3;spOA={gp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ7Q&%hrc5itoV8947S zwK2cZvA^*#zawP7*T{ail7BxZ6Eh1d8#@Ol7dH{ZB|lOhQUVPC-dUO+!mZ&%nsU%)-jX&cVsW&BMz_FzJ6n zB4QF!GI9z^Dry>9I(i01CT12^Hg*n9E^Z!PK7vXA6A}@Vkdl#8P*PFT(9+Q}FfuW- zu(GjpaB^|;@bVE%`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=VAB7DM8qVd zWaJc-RMa%Ibo302Ow25-Z0sDIT--dod<2vJCnO>!AtfWHproRvp{1i|U}R!uVP#|I z;N;@w;pHQk^gkgHF$pOdIRzyZH4QBtJp&^XGYcylI|nBhHxDl#!KD8QiHJ!^$;c@v zsiF604nV4Bv+1NQaxwv_F`3NTcPe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV z!^=l7>3>2ZViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAf0!v%}2#JVENXf`4D59I(i01CT12^Hg*n9E^Z!Pegk^~hxYymiHJ!^$;c@vsiF604nV4Bv+1NQa zxwv_F`5hPxyfpYnNJLCRN=8mWNkvUVOGnSZ$i&RT%Er#Y$;HjX%kPE7z(b2aLLy=k zQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UVaZu0vAnxgha$7q-5k2lvLC-v~=_gj7-cd ztZeKYoLt;Iy!9I(i01CT12^ zHg*n9E^Z!PK7vXA6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVE%`k#=9n1qy! zoPv^ynueB+o`I2xnT3^&or9B$n}?T=VAB7DM8qVdWaJc-RMa%Ibo302Ow25-Z0sDI zT--dod<2vJCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w;pHQk^gkgHF$pOdIRzyZ zH4QBtJp&^XGYcylI|nBhHxDl#!KD8QiHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F z`3NTcPe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^=l7>3>2ZViHm^atcZ+Y8qNP zdIm-&W)@a9b`DN1ZXRAff=T}q5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)7tN z{v#wJCLtvwr=X%^*6%hcZ}=zD%bCJ?(ZvoW?^Mx=iubx=HcZdnDsv) z5itoV8949I(i01CT12^Hg*n9E^Z!PK7v{Q6A}@Vkdl#8P*PFT(9+Q}FfuW-u(Gjp zaB^|;@bVGN`k#=9n1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=VAlVHM8qVdWaJc- zRMa%Ibo302Ow25-Z0sDIT--dod<3)pCnO>!AtfWHproRvp{1i|U}R!uVP#|I;N;@w z;pHQk^*F604nV4Bv+1NQaxwv_F`3PqHPe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV!^=l7 z>wiKbViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAf0t;jR2#JVENXf`4D54J@qrBP1dwAtfWHproRvp{1i|U}R!uVP#|I;N;@w;pMk1 zConMgkC2F%gp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnL^5-oU_~KSCm65>hg93Q8(! z8d^Gf21X`k7FITP4o)s^9$tRKf&vEy{|JeQNl3}aDJZF^X=v%_85o(ESy>Qk2+&sMeE*67X{}U1slaP{;Q&3V-)6mkhg93Q8(!8d^Gf21X`k7FITP4o)s^ z9$r3zS^pCf5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x<5zP9ZkcgOsl#HB$l8Ty! zmX4l*k%^gwm5rT)lZ%^&mycl9|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiL4a zv;HR}A|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJyBbfC+ArUbNDH%BhB^5OdEgd}r zBNHygZmIsh zRu@(_b`DN1ZXRAff<^xm5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)0chpOA={ zgp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ6F(f@=*#3ZC->Qk2+&sK|1dIMBBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yhg93Q8(! z8d^Gf21X`k7FITP4o)s^9$r3zMgJ2L5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x< z5iI(jkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^&mycl4|Aa)uB&1~I6qHodG_-W| z42(?7EUawo9GqO-JiL4ai~c7hA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJyBUto5 zArUbNDH%BhB^5OdEgd}rBNH>Qk2+&sMe7Uc$(<@^y65tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x#LU9V#?HaX#m&RZZ%}YxSkNCK5itoV894S6UY7hLBqAmuB_pSxq@t#wrK4wHWMXDvWn<^yF604nV4Bv+1NQaxwv_F@rOQN{}U1slaP{; zQ&3V-)6mk9I(i01CT12^Hg*n9E^Z!PK7vL6 z6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVG(8u}w7A|@dvBd4IGqNd@uzVx@k z#LU9V#?HaX#m&RZN3iODLLy=kQZjN1N-Am^S~_|LMkZz!RyKAH zPA+a9UOs|V{}U1slaP{;Q&3V-)6mk9I(i01 zCT12^Hg*n9E^Z!PK7v*M6A}@Vkdl#8P*PFT(9+Q}FfuW-u(GjpaB^|;@bVF?`k#=9 zn1qy!oPv^ynueB+o`I2xnT3^&or9B$n}?T=z@pqgLLy=kQZjN1N-Am^S~_|LMkZz! zRyKAHPA+a9UVck@1B-h82#JVENXf`4D5hg93Q8(!8d^Gf21X`k7FITP4o)s^9$tQj zGy^Yc{t*%plaP{;Q&3V-)6mkK`EyF$pOdIRzyZH4QBtJp&^XGYcylI|nBh zHxDnri{xO{|Aa)uB&1~I6qHodG_-W|42(?7EUawo9GqO-JiPcLpRfN3iHJ!^$;c@v zsiF604nV4Bv+1NQaxwv_F`3P41Pe?>eLP|zXK}khTLrX``z{teR!pg?Z!O6wV z!^=mo>VHBaViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAff>r+$5)qS-l95wTQc=^; z($O<8GBLBTvaxe;a&hzU@)4~1pOA={gp`b&f|81whL(<=fsu)sg_Vt+gOiJ!hnJ6F z)&GP<#3ZC->Qk2+&sK|1grihBqAmuB_pSxq@t#wrK4wH zWMXDvWn<^y9ek(+OYeasdM1SK%en*OauND1nE&je!AtfWH zproRvp{1i|U}R!uVP#|I;N;@w;pHRP^gkgHF$pOdIRzyZH4QBtJp&^XGYcylI|nBh zHxDl#!KVKSiHJ!^$;c@vsiF604nV4Bv+1NQaxwv_F`3N@sPe?>eLP|zXK}khT zLrX``z{teR!pg?Z!O6wV!^=mo>3>2ZViHm^atcZ+Y8qNPdIm-&W)@a9b`DN1ZXRAf zf=&Mu5)qS-l95wTQc=^;($O<8GBLBTvaxe;a&hzU@)2zMpOA={gp`b&f|81whL(<= zfsu)sg_Vt+gOiJ!hnJ6F)Bl7-#3ZC->Qk2+&sK|1e^XR zBqAmuB_pSxq@t#wrK4wHWMXDvWn<^y>Qk2+&sMe78C`B6#o$t z5tERTkyB7oQPa@U(K9eIF|)9;v2$>8ar5x<8;~3rlJrMNL`*_TMovLVMNLCXN6)~> z#LU9V#?HaX#m&RZZ$MMvkmesD5itoV894F604nV4Bv+1NQaxwv_F`MsbTcu4g}NJLCRN=8mWNkvUV zOGnSZ$i&RT%Er#Y$;HjX%kKeM;3D~tkcgOsl#HB$l8Ty!mX4l*k%^gwm5rT)lZ%^& zm)`|?u<3t7B4QF!GI9z^Dry>9I(i01CT12^Hg*n9E^Z!P{DIHc|Aa)uB&1~I6qHod zG_-W|42(?7EUawo9GqO-JiL4aoBk&xA|@dvBd4IGqNbsxqi0}bVrF4wW9Q)H;^yJy zBiQsmArUbNDH%BhB^5OdEgd}rBNH#LU9V#?HaX#m&RZN3iLC zLLy=kQZjN1N-Am^S~_|LMkZz!RyKAHPA+a9UOs|N{}U1slaP{;Q&3V-)6mkYN=8mWNkvUVOGnSZ$i&RT%Ep(SgOiJ! zhnF9pUH&H`CLtvwr=X;wrlF;yXJBMvW?^OH%g({c#m&RZkIydu6A_b;l95wTQc=^; z($O<8GBLBTvhii-;N;@w;pN9?m;Z@~Nl3}aDJZF^X=v%_85o(ESyhg93Q8(!8d^Gf z21X`k7FIUC>>Qk2+&sMe`0VmO5itoV894 z#LU9V#+RLglZ%^&m+*4p&o2KH5tERTkyB7oQPa@U(K9eIF|)9;@nz@W^oE^Z!P!o#6HejxfsL`*_TMovLVMNLCXN6)~>#LU9V#+RLglZ%^& zm+<4%k1weH5fPJ+l95wTQc=^;($O<8GBLBTvhii-;N;@w;U#=I_TvMxKO$lhQZjN1 zN-Am^S~_|LMkZz!RyMxu9GqO-JiLSt=RO+rKO$lhQZjN1N-Am^S~_|LMkZz!RyMxu z9GqO-JiLT(@Y&^mB4QF!GI9z^Dry>9I(i01CT12^Hooi}oLt;Iy!eOe%l|~gB&1~I z6qHodG_-W|42(?7EUavN**Q45xOsT_@!92nB4QF!GI9z^Dry>9I(i01CT12^Hooi} zoLt;Iy!`m=@;?zV2`L#l1tk?V4J{o#10xeN3o9F6b`DN1ZXRBKe0KSth?s%or9B$ zn}?SlpI!bZA|@dvBd4IGqNbsxqi0}bVrF4wULP|zXK}khT zLrX``KzNmAc%4Rgq~=2SX-)WgP52XAm}Unj7dH2Pee>YN=8mWNkvUVOGnSZ z$i&RT%Ep(SgOiJ!hnF9pL;fcsCLtvwr=X;wrlF;yXJBMvW?^OH%g({c#m&RZkIy0h z6A_b;l95wTQc=^;($O<8GBLBTvhii-;N;@w;pNBYkpGE@Nl3}aDJZF^X=v%_85o(E zSyhg93Q8(!8d^Gf21X`k7FIUC>>Qk2+&sMe_#E;-5itoV894#LU9V#+RLglZ%^&mmi-){wE?PAtfWHproRvp{1i|U}R!uVP)gX z&cVsW&BM!&&msR45tERTkyB7oQPa@U(K9eIF|)9;@nz@W^oE^Z!PetZu3pNN=*l#HB$l8Ty!mX4l*k%^gwm5nbu2PYRd z4=+DHhx|`OOhQUVPC-dUO+!mZ&%nsU%)-jXmz{%?i<^g+A0IC#{v#qLAtfWHproRv zp{1i|U}R!uVP)gX&cVsW&BIH0G4jXDk^YE?Nl3}aDJZF^X=v%_85o(ESyF604nV4Bv+4!<^aB^|;@Dje5`|;u2 z9}zJLDH%BhB^5OdEgd}rBNH%or9B$n}?SlpF{p9 zA|@dvBd4IGqNbsxqi0}bVrF4wdo{Nl3}aDJZF^X=v%_85o(ESyhg93Q8(! z8d^Gf21X`k7FIUC>>Qk2+&sMe_?+@T5itoV894#LU9V#+RLglZ%^&mmi-~{wE?PAtfWHproRvp{1i|U}R!uVP)gX&cVsW&BM!& z&nf>C5tERTkyB7oQPa@U(K9eIF|)9;@nz@WrF$pOdIRzyZH4QBtJp&^X zGYcylUv>^oE^Z!Petb^(pNN=*l#HB$l8Ty!mX4l*k%^gwm5nbu2PYRd4=+DHr~FSu zOhQUVPC-dUO+!mZ&%nsU%)-jXmz{%?i<^g+AD>hHCn6>xB_pSxq@t#wrK4wHWMXDv zW#h}v!O6wV!^@A)DgP4@laP{;Q&3V-)6mkf5 zNXf`4D5hg93Q8(!8d^Gf21X`k z7FIUC>>Qk2+&sL5mqL9``JafGgp`b&f|81whL(<=fsu)sg_VsjI|nBhHxDo2q0}D_ zruriyCLtvwr=X;wrlF;yXJBMvW?^OH%g({c#m&P@cqrD#4`cs`h)GDv$SEkPsA*{F z=ouK9m|0la__A|wa&hzU5`L8X@x|OfB4QF!GI9z^Dry>9I(i01CT12^Hooi}oLt;I zyo4_We|#|bM?_3QN=8mWNkvUVOGnSZ$i&RT%Ep(SgOiJ!hnMi7#LU9V#+RLglZ%^&mmi-~{wE?PAtfWHproRvp{1i|U}R!uVP)gX&cVsW z&BM!&&nf>C5tERTkyB7oQPa@U(K9eIF|)9;@nz@WJ9Cn6>xB_pSxq@t#wrK4wH zWMXDvW#h}v!O6wV!^@A)CI1rF604nV4Bv+4!<^aB^|;@bcqx$^S&eB&1~I6qHodG_-W|42(?7 zEUavN**Q45xOsT_@ww!GB4QF!GI9z^Dry>9I(i01CT12^Hooi}oLt;Iy!`lF@;?zV z2`L#l1tk?V4J{o#10xeN3o9F6b`DN1ZXRBKd@lK)h?s%or9B$n}?SlpG*EHA|@dv zBd4IGqNbsxqi0}bVrF4wYN=8mWNkvUVOGnSZ$i&RT%Ep(SgOiJ! zhnF9pOa3P!CLtvwr=X;wrlF;yXJBMvW?^OH%g({c#m&RZkIyCl6A_b;l95wTQc=^; z($O<8GBLBTvhii-;N;@w;pNBYlK+W_Nl3}aDJZF^X=v%_85o(ESy%or9B$ zn}?V1KjlaP{;Q&3V-)6mk%or9B$n}?SlpG*EH zA|@dvBd4IGqNbsxqi0}bVrF4whg93Q8(! z8d^Gf21X`k7FIUC>>Qk2+&sMe_}ub85itoV894#LU9V#+RLglZ%^&mmi;7{wE?PAtfWHproRvp{1i|U}R!uVP)gX&cVsW&BM!& z&n^EG5tERTkyB7oQPa@U(K9eIF|)9;@nz@W^oE^Z!Petd5EpNN=*l#HB$l8Ty!mX4l*k%^gwm5nbu2PYRd4=+DHxBO2; zOhQUVPC-dUO+!mZ&%nsU%)-jXmz{%?i<^g+AD>(PCn6>xB_pSxq@t#wrK4wHWMXDv zW#h}v!O6wV!^@A)E&me{laP{;Q&3V-)6mkF604nV4Bv+4!<^aB^|;@bcqx%l|~gB&1~I6qHodG_-W|42(?7EUavN z**Q45xOsT_@ww%HB4QF!GI9z^Dry>9I(i01CT12^Hooi}oLt;Iyo8rgf4q?DkBFFr zl#HB$l8Ty!mX4l*k%^gwm5nbu2PYRd4=>?mSRW6>{v#qLAtfWHproRvp{1i|U}R!u zVP)gX&cVsW&BIH08285mx&DZVNl3}aDJZF^X=v%_85o(ESyF604nV4Bv+4!<^aB^|;@Djq{=a&D8h)GDv$SEkP zsA*{F=ouK9m|0la__A|wa&hzU;=iab{}U0Dkdl#8P*PFT(9+Q}FfuW-u(I)G=iubx z=HcbX=a&D8h)GDv$SEkPsA*{F=ouK9m|0la__A|wa&hzU^5f$&{1Fk8kdl#8P*PFT z(9+Q}FfuW-5MHeqUat@yu^1k+5PoVAzHSlzF604nV4Bv+4!<^aB^|;@bcsH z$p1vdB&1~I6qHodG_-W|42(?7EUavN**Q45xOsT_@p9I(i01 zCT12^Hooi}oLt;Iy!`k)@;?zV2`L#l1tk?V4J{o#10xeN3o9F6b`DN1ZXRBKd>;9q zh?s%or9B$n}?SlpGW>DA|@dvBd4IGqNbsxqi0}bVrF4wYN=8mW zNkvUVOGnSZ$i&RT%Ep(SgOiJ!hnF9pNB$=wCLtvwr=X;wrlF;yXJBMvW?^OH%g({c z#m&RZkIy6j6A_b;l95wTQc=^;($O<8GBLBTvhii-;N;@w;pNBYk^hN^Nl3}aDJZF^ zX=v%_85o(ESyM8qVdWaJc-RMa%Ibo302Ow25-Y<$@{IJvla zc=_>phg93Q8(!8d^Gf21X`k7FIUC>>Qk2+&sMe_&oAI5itoV894F604nV4Bv+4!<^aB^|;@Dd&b{_!xdKO$lhQZjN1N-Am^S~_|LMkZz!RyMxu z9GqO-JiLSlk$wCa`HzU0gp`b&f|81whL(<=fsu)sg_VsjI|nBhHxDo2htMBihW;ZW zCLtvwr=X;wrlF;yXJBMvW?^OH%g({c#m&P@_#*blhp~S|#3ZC-hg93Q8(!8d^Gf21X`k7FIUC>>Qk2+&sMa59-VRM8qVdWaJc-RMa%Ibo302 zOw25-Y<$@{IJvlac=_@1f8&pcn1qy!oPv^ynueB+o`I2xnT3_`dc*LFgYcNc@Ti0E zbBFMihwx{QaOy8VKCk>wL`*_TMovLVMNLCXN6)~>#LU9V#+RLglZ%^&mmi;3{wE?P zAtfWHproRvp{1i|U}R!uVP)gX&cVsW&BM!&&ny2E5tERTkyB7oQPa@U(K9eIF|)9; z@nz@We^oE^Z!Petcf}pNN=*l#HB$ zl8Ty!mX4l*k%^gwm5nbu2PYRd4=+DHul!F$OhQUVPC-dUO+!mZ&%nsU%)-jXmz{%? zi<^g+AD>tLCn6>xB_pSxq@t#wrK4wHWMXDvW#h}v!O6wV!^@A)EB_M_laP{;Q&3V- z)6mkF604nV4Bv+4!<^aB^|; z@bcsH%Kt>fB&1~I6qHodG_-W|42(?7EUavN**Q45xOsT_@p9 zI(i01CT12^Hooi}oLt;Iy!`mQ@;?zV2`L#l1tk?V4J{o#10xeN3o9F6b`DN1ZXRBK zd|vsVh?s%or9B$n}?SlpI81TA|@dvBd4IGqNbsxqi0}bVrF4w32`L#l1tk?V4J{o#10xeN z3o9F6b`DN1ZXRC3OSnH?#Pvr+OhQUVPC-dUO+!mZ&%nsU%)-jXmz{%?i<^g+@Di|( z2Z8?)5tERTkyB7oQPa@U(K9eIF|)9;@nz@W%or9B$n}?V1CGd|Ag8zt!Nl3}a zDJZF^X=v%_85o(ESydXH`#3ZC- zb*;{B-C)UGh(-`qM4`bZkFe(@*E}(>?s`;6JdXJ=+SHf-(Lty$|6?~(U;f9+s=oY>S+2hPPZ(|Cj)$ur&OB5PhZL^9{EtMazWk4L zqQ3l(PFa2VA6=XJ@;^EV_2qx;X6noTSXtGV|1rze|2NXZXbX2dT=j6~p?Wx^aP{SX zBtrG&f20%j<$rX_>dXJ=+SHf-(Lty$|6?~(U;f9+s=oY>S?>J9C=Vko-0g71!&!&Q z^1nk0S6}`|B2-`gM>*zWk4_O?~+v9fbPwKXxdXIx86IX?80lfO zg*zUudN}h?JseWF`tm;#q5ASa(uw-=KRRXg<$rW->dXJ=Ak>%tv74zc|6^rU|KI8o zW_XxoVWfxA7Vdbs>fy{o^>9ex>dXH~gzC%xNGIyc|LBy}m;ceVsW1PdgHT`o$8M&+ z{EwB@`G=Jy%>0z{mJ07ljIP*|F98$RY@;?%x`tm>0iTd(C zI%W0ce{^l?%m3&g)R+IUo2mbAMGvcLSlPnr5@vXqWnrX;(H8D_xa#4|L-lY-;p)r( zNQCOk|41k5%m3(<)tCR#wW%-vqk~Xi{>N_S{KIM*zWk4_O?~+v9fbPwKVc^eyGdBl!>Srqwy?T{ z86IX?80lfOg*zUudN}h?JseWF`tm;#q5ASa(uw-=KRRXg<$rW->dXJ=Ak_c2i-w&n z>?UDF536ce*~01)W_XxoVWfxA7Vdbs>fy{o^>9ex>dXH~gzC%xNGIyc|LBy}m;ceV zsW1PdgK+*~2MxPe*h#`_9#+(_s)dy$%>0z{mJ07lj zIP*|F98$RY@;?%x`tm>0iTd(CI%W0ce{^l?|La^r_YijQu#1MBEbJy>MGvcLSlPnr z5@vXqWnrX;(H8D_xa#4|L-lY-;p)r(NQCOk|41k5%m3(<)tCR#wK@OLwS>+g?A~Dq z4ZB#_Ny2I#R@AVng_R}D?l8l`C=Vko-0g71!&!&Q^1nk0S6}`|B2-`gM>* zzWh(<*h1G7I+xHrgdIHWqG2ZsyGdBl!>Srqwy?T{86IX?80lfOg*zUudN}h?JseWF z`tm;#q5ASa(uw-=KRRXg|8?UDF536ce*~01)W_Xxo zVWfxA7Vdbs>fy{o^>9ex>dXH~gzC%xNGIyc|LByRf9MoLw-!34(6xllA?)5^2MxPe z*h#`_9#+(_s)dy$%>0z{mJ07ljIP*|F98$RY z@;?%x`tm>0iTeLK^w1@TPBnCkp<@eOQ|Mem_YijQu#1MBEbJy>MGvcLSlPnr5@vXq zWnrX;(H8D_xa#4|L-lY-;p)r(NQCOk|41j!KXm7zLk?YP=oCY@7CNTTwS>+g?A~Dq z4ZB#_Ny2I#R@AVng_R}D?l8l`C=Vko-0g71!&!&Q^1nk0S6}`|B2-`gCnS@Q4nl_> zy5!KQhHf!*Y@urkolEE*!VVsG(Xf++-6X8&VO0$)TUcGf3=gv`jPx+t!W|D+J)C){ z9u6s7efb}WQ2l?YC?u1R4nl_>y5!KQhHf!*Y@urkolEE*!VVsG(Xf++-6X8&VO0$) zTUcGf3=gv`jPx+t!W|D+J)C){9u6s7efgj81MrZ@LMjT$B&37Tp@%LxbgH3S3>{nO znnLFix`(iXhg~%6WMMZ6D|%Q}!^##`moUS_EDIw&jJ9yc!&MJw9;$~!3RnN%7tli* z42dkHqL55NItU$l=#oRH8oI^Mv4yTFbS|NL2s?P#MZ-=Oc9XE8hgCJKY+-c?Gd#?) zFw(F5)dN`zT=l?H>hBO!wSx7}8nS^u@I`q&bhfXzgi=kr+T~p{>LiZ4M z@UV-9ohJnynm}Oz4htU@9c)04}%tQ5Xga95=a7dyd4TeM(Qc*}I zAsvJcJ#@*TQw`l>=-5Kn6grpCJ%k-R?4n^O3%f~J(Zi}5R<^LZgc%-YSs3YIw1qn! Mu6j80P(A$XKV(bs>;M1& literal 0 HcmV?d00001 diff --git a/engine/assets/textures/neutral_lut.ktx2.meta b/engine/assets/textures/neutral_lut.ktx2.meta new file mode 100644 index 000000000..8de2632f0 --- /dev/null +++ b/engine/assets/textures/neutral_lut.ktx2.meta @@ -0,0 +1,4 @@ +uid = "NeutralLut1" +type = "texture" +created_at = "2026-11-27T05:24:00.0000000Z" +modified_at = "2026-11-27T05:24:00.0000000Z" diff --git a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp index dcc596670..827933f0c 100644 --- a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp +++ b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp @@ -34,6 +34,19 @@ void memoryBarrier( cmd.pipelineBarrier2(dependency); } +/// Tints lose their brightness first so the pickers only tint and the offsets only brighten +auto prepareLiftGammaGain(const PostProcessSettings::ColorGrading& grade) -> std::array { + const auto balanced = [](float r, float g, float b) { + const glm::vec3 tint(r, g, b); + return tint - glm::dot(tint, glm::vec3(0.2126f, 0.7152f, 0.0722f)); + }; + const glm::vec3 lift = (balanced(grade.lift_r, grade.lift_g, grade.lift_b) + grade.lift_offset) * 0.15f; + // Symmetric in log space so -1 and +1 are equal and opposite, 1/(1+x) reached 1000 at -1 and overflowed + const glm::vec3 gamma_inv = glm::exp2(-(balanced(grade.gamma_r, grade.gamma_g, grade.gamma_b) + grade.gamma_offset)); + const glm::vec3 gain = 1.0f + balanced(grade.gain_r, grade.gain_g, grade.gain_b) + grade.gain_offset; + return {lift, gamma_inv, gain}; +} + } TonemapPass::TonemapPass(const VulkanCore& core, vk::Format ldr_format, vk::Extent2D extent) @@ -295,6 +308,35 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV m_was_metering = false; } + const auto grade = frame != nullptr ? frame->post_process.color_grading : PostProcessSettings::ColorGrading {}; + const auto [lift, gamma_inv, gain] = prepareLiftGammaGain(grade); + + // A LUT still uploading or failed grades nothing rather than sampling an unready image + vk::ImageView lut_view = nullptr; + uint64_t lut_generation = 0; + bool lut_srgb = false; + if (grade.lut_intensity > 0.0f && grade.lut.hasValue()) { + const VulkanTexture& lut = grade.lut->gpuTexture(); + if (lut.isReady()) { + const auto& lut_params = lut.params(); + const uint32_t size = lut_params.extent.height; + const bool strip = lut_params.extent.width == size * size && lut_params.layer_count == 1 && !lut_params.is_cubemap; + if (strip) { + lut_view = lut.getView(); + lut_generation = lut.generation(); + // Default texture imports are sRGB, the sampler then hands back linear values the shader re-encodes + lut_srgb = vk::to_string(lut.getFormat()).find("Srgb") != std::string::npos; + } else if (std::exchange(m_rejected_lut, lut.generation()) != lut.generation()) { + TOAST_WARN( + "Render", + "Colour grading LUT is {}x{}, it needs a strip of N slices of NxN like 1024x32; the image stays ungraded", + lut_params.extent.width, + size + ); + } + } + } + const Params params { .exposure = settings.exposure, .mode = settings.mode, @@ -310,6 +352,12 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV .peak_scale = VulkanRenderer::instance->hdrPeakScale(), .gt_toe = settings.gt_contrast_dip, .chromatic_aberration = settings.chromatic_aberration, + .temperature = grade.temperature, + .tint = grade.tint, + .color_filter = {grade.color_filter_r, grade.color_filter_g, grade.color_filter_b, grade.hue_shift}, + .lift = {lift, 0.0f}, + .gamma_inv = {gamma_inv, lut_srgb ? 1.0f : 0.0f}, + .gain = {gain, lut_view ? grade.lut_intensity : 0.0f}, }; if (m_params_buffers[frame_index].gpu_buffer.has_value()) { @@ -320,16 +368,22 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV } } - if (m_bound_views.update(frame_index, source_view)) { - vk::DescriptorImageInfo image_info {}; - image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - image_info.imageView = source_view; - image_info.sampler = *m_sampler; - - const vk::WriteDescriptorSet write( - *m_descriptor_sets[frame_index], 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_info - ); - m_core->getDevice().updateDescriptorSets(write, {}); + if (m_bound_views.update(frame_index, {source_view, lut_view, lut_generation})) { + DescriptorWriter writer; + const auto image = [&](uint32_t binding, vk::ImageView view) { + writer.image( + *m_descriptor_sets[frame_index], + binding, + vk::DescriptorType::eCombinedImageSampler, + *m_sampler, + view, + vk::ImageLayout::eShaderReadOnlyOptimal + ); + }; + image(1, source_view); + // The scene stands in so the set stays valid; the shader skips the LUT when its intensity is 0 + image(3, lut_view ? lut_view : source_view); + writer.flush(m_core->getDevice()); } m_target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/post/tonemap_pass.hpp b/engine/src/toast/renderer/passes/post/tonemap_pass.hpp index 0432e3efc..3a1b9dfb9 100644 --- a/engine/src/toast/renderer/passes/post/tonemap_pass.hpp +++ b/engine/src/toast/renderer/passes/post/tonemap_pass.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include namespace renderer { @@ -49,7 +50,7 @@ class TonemapPass : public IPostProcessPass { void onResize(vk::Extent2D extent) override; private: - /// Mirrors tonemap.slang TonemapParams padded by std140 to 48 bytes + /// Mirrors tonemap.slang TonemapParams, 128 bytes under std140 struct Params { float exposure = 1.0f; uint32_t mode = static_cast(TonemapMode::reinhard); @@ -66,9 +67,18 @@ class TonemapPass : public IPostProcessPass { float peak_scale = 1.0f; float gt_toe = 1.28f; float chromatic_aberration = 0.0f; - std::array pad1 {}; + float temperature = 0.0f; + float tint = 0.0f; + /// w is the hue shift in degrees + glm::vec4 color_filter {1.0f, 1.0f, 1.0f, 0.0f}; + glm::vec4 lift {0.0f}; + glm::vec4 gamma_inv {1.0f, 1.0f, 1.0f, 0.0f}; + /// w is the LUT intensity, 0 when no LUT is bound + glm::vec4 gain {1.0f, 1.0f, 1.0f, 0.0f}; }; + static_assert(sizeof(Params) == 128); + /// Mirrors exposure.slang ExposureParams struct ExposureParams { float min_log = 0.0f; @@ -102,7 +112,8 @@ class TonemapPass : public IPostProcessPass { std::vector m_descriptor_sets; std::vector m_params_buffers; - DescriptorCache m_bound_views; + /// Scene view, LUT view and the LUT's generation since a reloaded LUT can reuse a destroyed view handle + DescriptorCache> m_bound_views; ShaderLayout m_exposure_layout; VulkanPipeline m_histogram_pipeline; @@ -118,6 +129,9 @@ class TonemapPass : public IPostProcessPass { bool m_exposure_ready = false; bool m_was_metering = false; + + /// Generation of the last LUT warned about, so a wrong sized LUT warns once rather than every frame + uint64_t m_rejected_lut = 0; std::chrono::steady_clock::time_point m_last_meter; }; diff --git a/engine/src/toast/renderer/resources/vulkan_texture.hpp b/engine/src/toast/renderer/resources/vulkan_texture.hpp index 798e39e6e..95159b318 100644 --- a/engine/src/toast/renderer/resources/vulkan_texture.hpp +++ b/engine/src/toast/renderer/resources/vulkan_texture.hpp @@ -44,6 +44,11 @@ class VulkanTexture : public IVulkanResource { return m_params.format; } + [[nodiscard]] + auto params() const -> const Params& { + return m_params; + } + /// Unique per create() so a descriptor cache notices a recreated view that reuses a destroyed handle value [[nodiscard]] auto generation() const noexcept -> uint64_t { diff --git a/engine/src/toast/renderer/settings/post_process_params.cpp b/engine/src/toast/renderer/settings/post_process_params.cpp index a086909c7..53388351d 100644 --- a/engine/src/toast/renderer/settings/post_process_params.cpp +++ b/engine/src/toast/renderer/settings/post_process_params.cpp @@ -360,6 +360,22 @@ auto PostProcessParams::resolve() const -> PostProcessSettings { f("tonemap.adapt_speed_up", s.tonemap.adapt_speed_up); f("tonemap.adapt_speed_down", s.tonemap.adapt_speed_down); + auto& grade = s.color_grading; + f("color_grading.temperature", grade.temperature); + f("color_grading.tint", grade.tint); + c("color_grading.color_filter", grade.color_filter_r, grade.color_filter_g, grade.color_filter_b); + f("color_grading.hue_shift", grade.hue_shift); + c("color_grading.lift", grade.lift_r, grade.lift_g, grade.lift_b); + f("color_grading.lift_offset", grade.lift_offset); + c("color_grading.gamma", grade.gamma_r, grade.gamma_g, grade.gamma_b); + f("color_grading.gamma_offset", grade.gamma_offset); + c("color_grading.gain", grade.gain_r, grade.gain_g, grade.gain_b); + f("color_grading.gain_offset", grade.gain_offset); + if (const auto uid = assetUid("color_grading.lut"); uid && uid->data() != 0) { + grade.lut = assets::load(*uid); + } + f("color_grading.lut_intensity", grade.lut_intensity); + f("fxaa.contrast_threshold", s.fxaa.contrast_threshold); f("fxaa.relative_threshold", s.fxaa.relative_threshold); f("fxaa.subpixel_blending", s.fxaa.subpixel_blending); diff --git a/engine/src/toast/renderer/settings/post_process_settings.hpp b/engine/src/toast/renderer/settings/post_process_settings.hpp index 714c502c6..3091f1501 100644 --- a/engine/src/toast/renderer/settings/post_process_settings.hpp +++ b/engine/src/toast/renderer/settings/post_process_settings.hpp @@ -65,6 +65,32 @@ struct PostProcessSettings { float adapt_speed_down = 1.0f; } tonemap; + /// Every default is neutral so a profile without grading renders as before + struct ColorGrading { + float temperature = 0.0f; + float tint = 0.0f; + float color_filter_r = 1.0f; + float color_filter_g = 1.0f; + float color_filter_b = 1.0f; + /// Degrees + float hue_shift = 0.0f; + float lift_r = 1.0f; + float lift_g = 1.0f; + float lift_b = 1.0f; + float lift_offset = 0.0f; + float gamma_r = 1.0f; + float gamma_g = 1.0f; + float gamma_b = 1.0f; + float gamma_offset = 0.0f; + float gain_r = 1.0f; + float gain_g = 1.0f; + float gain_b = 1.0f; + float gain_offset = 0.0f; + /// Strip of N slices of NxN, display encoded + assets::Handle lut; + float lut_intensity = 1.0f; + } color_grading; + struct Fxaa { float contrast_threshold = 0.0312f; float relative_threshold = 0.125f; diff --git a/tests/postprocess/01-blend.cpp b/tests/postprocess/01-blend.cpp index c3095bdc1..03e9651d7 100644 --- a/tests/postprocess/01-blend.cpp +++ b/tests/postprocess/01-blend.cpp @@ -49,6 +49,20 @@ TOAST_TEST_NAMED("postprocess", "postprocess/01-blend", test_postprocess_01_blen assert(defaults.ssao.sample_count == fallback.ssao.sample_count); assert(near(defaults.fog.distance, fallback.fog.distance)); assert(near(defaults.fog.albedo_b, fallback.fog.albedo_b)); + assert(near(defaults.color_grading.temperature, fallback.color_grading.temperature)); + assert(near(defaults.color_grading.color_filter_g, 1.0f)); + assert(near(defaults.color_grading.gain_b, fallback.color_grading.gain_b)); + assert(near(defaults.color_grading.lut_intensity, 1.0f)); + assert(!defaults.color_grading.lut.hasValue()); + + // Grading sliders fade between volumes like every other float and colour + PostProcessParams ungraded(layout); + PostProcessParams graded(layout); + must(graded.setNumber("color_grading.temperature", 1.0f)); + must(graded.setColor("color_grading.lift", {0.0f, 1.0f, 1.0f})); + ungraded.blend(graded, 0.5f); + assert(near(ungraded.resolve().color_grading.temperature, 0.5f)); + assert(near(ungraded.resolve().color_grading.lift_r, 0.5f)); PostProcessParams target(layout); PostProcessParams source(layout); diff --git a/tools/color_grading/make_neutral_lut.py b/tools/color_grading/make_neutral_lut.py new file mode 100644 index 000000000..469f3f3e6 --- /dev/null +++ b/tools/color_grading/make_neutral_lut.py @@ -0,0 +1,32 @@ +"""Writes the neutral colour grading LUT strip that tonemap.slang applyLut reads. + +Layout: 32 slices of 32x32 side by side (1024x32). Red runs across a slice, green down, blue picks the slice. +Artists paste this strip into a screenshot, grade the screenshot, then crop the strip back out. + +Usage: python make_neutral_lut.py +""" + +import sys + +import numpy as np +from PIL import Image + +SIZE = 32 + + +def neutral_lut(size: int = SIZE) -> np.ndarray: + x = np.arange(size * size) + y = np.arange(size) + xx, yy = np.meshgrid(x, y) + rgb = np.stack([xx % size, yy, xx // size], axis=-1) / (size - 1) + return np.round(rgb * 255).astype(np.uint8) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(__doc__) + lut = neutral_lut() + assert lut.shape == (SIZE, SIZE * SIZE, 3) + assert tuple(lut[0, 0]) == (0, 0, 0) and tuple(lut[-1, -1]) == (255, 255, 255) + assert tuple(lut[5, 3 * SIZE + 7]) == tuple(round(v * 255 / (SIZE - 1)) for v in (7, 5, 3)) + Image.fromarray(lut, "RGB").save(sys.argv[1]) diff --git a/tools/color_grading/neutral_lut.png b/tools/color_grading/neutral_lut.png new file mode 100644 index 0000000000000000000000000000000000000000..c8a022a98797dd758332617acdefa94ea786d272 GIT binary patch literal 314 zcmeAS@N?(olHy`uVBq!ia0y~yU;#226gZfGB=elP9~l@J89iMbLn`LHy?v0Y*+9Vc zqF~I6|Njd%UhoxPdb*{WPl-|0!$+(?v2W(id)NO;*7Vlf{Cd7MdEMFP`_2FVyZe0m zzklyf{Vx9gbFTjD{h$8bsjYi{`q%kQzdzUHF)%nZgRE109?S!zq(Xp%f(wvn5MTt7 zPG5k8LkGxlEgV2XKnctT5)6v78W@2}S%FL^kc&A4frNq!Kagx$0VEtcfCPgg$QLay zfMzuahys~VRX`Th0ux4NEEdRtlm>!zft?ZOwNj~i%bdcAKye07S3j3^P6 Date: Fri, 27 Nov 2026 09:22:11 +0100 Subject: [PATCH 14/15] fixes --- .github/workflows/package-release.yml | 5 ----- editor/Assets/Types/PostProcessProfileAsset.cs | 8 +++++--- editor/Editors/GenericViewModel.cs | 7 ++++++- engine/assets/shaders/voxel.slang | 3 ++- engine/src/toast/assets/asset_registry.cpp | 2 +- engine/src/toast/assets/data.cpp | 4 ++++ engine/src/toast/renderer/passes/post/tonemap_pass.cpp | 2 +- .../src/toast/renderer/settings/post_process_profile.hpp | 2 +- 8 files changed, 20 insertions(+), 13 deletions(-) diff --git a/.github/workflows/package-release.yml b/.github/workflows/package-release.yml index 5f0d5097f..9d913f3ba 100644 --- a/.github/workflows/package-release.yml +++ b/.github/workflows/package-release.yml @@ -40,9 +40,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - name: Setup MSVC uses: ilammy/msvc-dev-cmd@v1 @@ -116,8 +113,6 @@ jobs: - name: Build editor run: nix develop --command bash -c " - rustup toolchain install stable --no-self-update && - rustup default stable && cmake -B build/package -G Ninja -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ diff --git a/editor/Assets/Types/PostProcessProfileAsset.cs b/editor/Assets/Types/PostProcessProfileAsset.cs index b1b95363a..06581dac9 100644 --- a/editor/Assets/Types/PostProcessProfileAsset.cs +++ b/editor/Assets/Types/PostProcessProfileAsset.cs @@ -10,10 +10,10 @@ public class PostProcessProfileAsset : BaseAsset { public override string Extension => ".tpp"; public override string DisplayName => "Post Process Profile"; public override string ChipText => "POST"; - public override string ChipColor => "Purple"; + public override string ChipColor => "Orange"; public override LucideIconKind Icon => LucideIconKind.Sun; public override bool CanBeCreated => true; - public override string Category => "Rendering"; + public override string Category => "Visual"; public override bool HasThumbnail => false; public override bool CanBeEdited => true; public override string EditorTool => "GenericEditor"; @@ -23,7 +23,9 @@ public class PostProcessProfileAsset : BaseAsset { public override Task CreateAsync(string path) { const string schemaUid = "PostProcSc4"; - File.WriteAllText(path, $"# Toast Post Process Profile\nschema = \"{schemaUid}\"\n"); + File.WriteAllText(path, + $"# Toast post process profile\n" + + $"schema = \"{schemaUid}\"\n"); return Task.CompletedTask; } } diff --git a/editor/Editors/GenericViewModel.cs b/editor/Editors/GenericViewModel.cs index f982a425a..ac23d2b98 100644 --- a/editor/Editors/GenericViewModel.cs +++ b/editor/Editors/GenericViewModel.cs @@ -680,7 +680,7 @@ private string SerializeDocument() { // Preserve schema UID reference if (!SchemaLocked && !string.IsNullOrEmpty(SchemaUid)) table["schema"] = SchemaUid; - else if (!SchemaLocked) { + else { // Check if the original file had a schema key and preserve it var realPath = ProjectContext.Resolve(CurrentPath); if (File.Exists(realPath)) { @@ -691,6 +691,11 @@ private string SerializeDocument() { // ignored } } + + // A type with a fixed schema gets its UID back if the file lost it + if (!table.ContainsKey("schema") && Definition is { SchemaPath: { Length: > 0 } schemaPath } and not ProjectSettingsAsset && + MetaFile.ReadHeader(ProjectContext.Resolve(schemaPath)) is { } header) + table["schema"] = header.Uid; } foreach (var field in Fields) { diff --git a/engine/assets/shaders/voxel.slang b/engine/assets/shaders/voxel.slang index 944576515..66892d772 100644 --- a/engine/assets/shaders/voxel.slang +++ b/engine/assets/shaders/voxel.slang @@ -562,7 +562,8 @@ bool shade(VSOutput input, out FSOutput output, out float depth) // Never hit in front of the near plane whose clip distance is linear along the ray in either convention 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 float tMin = nearStep > 0.0 ? max(0.0, -nearOrigin / nearStep) : 0.0; + const float tMin = max(0.0, -nearOrigin / nearStep); const RayHit hit = marchRayBox(instance.recordIndex, origin, direction, tMin, kFloatMax, input.boxMin, input.boxMax); return shadeHit(input.position, instance, origin, direction, worldDirection, hit, output, depth); diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 1ef23aef1..e45de216d 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -88,7 +88,7 @@ void AssetRegistry::init() { s_schema_toml["destruction_material"] = [](const toml::table& t, Handle s) { return std::make_unique(t, std::move(s)); }; - s_schema_toml["post_process_profile"] = [](const toml::table& t, Handle s) { + s_schema_toml["post_process"] = [](const toml::table& t, Handle s) { return std::make_unique(t, std::move(s)); }; diff --git a/engine/src/toast/assets/data.cpp b/engine/src/toast/assets/data.cpp index 6acd3aa18..5ec54206d 100644 --- a/engine/src/toast/assets/data.cpp +++ b/engine/src/toast/assets/data.cpp @@ -106,6 +106,8 @@ auto Data::serialize(SaveMode mode) const -> std::vector { auto j = m_root.toJson(); if (m_schema.hasValue()) { j["schema"] = m_schema.uid().get(); + } else { + TOAST_ERROR("AssetManager", "Missing schema while serializing!!!"); } auto bson = json_t::to_bson(j); return bson; @@ -115,6 +117,8 @@ auto Data::serialize(SaveMode mode) const -> std::vector { if (m_schema.hasValue()) { tbl.insert_or_assign("schema", m_schema.uid().get()); + } else { + TOAST_ERROR("AssetManager", "Missing schema while serializing!!!"); } if (m_root.type() == DataType::object_t) { diff --git a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp index 827933f0c..b5e682364 100644 --- a/engine/src/toast/renderer/passes/post/tonemap_pass.cpp +++ b/engine/src/toast/renderer/passes/post/tonemap_pass.cpp @@ -325,7 +325,7 @@ auto TonemapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageV lut_view = lut.getView(); lut_generation = lut.generation(); // Default texture imports are sRGB, the sampler then hands back linear values the shader re-encodes - lut_srgb = vk::to_string(lut.getFormat()).find("Srgb") != std::string::npos; + lut_srgb = vk::to_string(lut.getFormat()).contains("Srgb"); } else if (std::exchange(m_rejected_lut, lut.generation()) != lut.generation()) { TOAST_WARN( "Render", diff --git a/engine/src/toast/renderer/settings/post_process_profile.hpp b/engine/src/toast/renderer/settings/post_process_profile.hpp index 5726e83c2..d5395dc97 100644 --- a/engine/src/toast/renderer/settings/post_process_profile.hpp +++ b/engine/src/toast/renderer/settings/post_process_profile.hpp @@ -16,7 +16,7 @@ class TOAST_API PostProcessProfile : public Data { [[nodiscard]] auto type() const -> std::string_view override { - return "post_process_profile"; + return "post_process"; } /// Bumps whenever the file is re-read From f8670d659407b795139af115fd2ef4ec8af699d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Rodr=C3=ADguez=20Mart=C3=ADnez?= Date: Fri, 27 Nov 2026 10:22:03 +0100 Subject: [PATCH 15/15] fix --- editor/Components/Elements/ColorWheel.cs | 5 ++++- editor/Editors/ColorWheelsPanel.cs | 15 +++++++-------- engine/src/toast/assets/asset_registry.cpp | 2 +- .../renderer/settings/post_process_profile.hpp | 2 +- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/editor/Components/Elements/ColorWheel.cs b/editor/Components/Elements/ColorWheel.cs index 559bcabf2..bc1eb345f 100644 --- a/editor/Components/Elements/ColorWheel.cs +++ b/editor/Components/Elements/ColorWheel.cs @@ -21,6 +21,9 @@ public class ColorWheel : Control { private const int RingSegments = 180; private const double FineFactor = 0.1; + /// Dot travel per pixel of pointer travel + private const double DragFactor = 0.2; + public static readonly StyledProperty RProperty = AvaloniaProperty.Register(nameof(R), 1f, defaultBindingMode: BindingMode.TwoWay); @@ -131,7 +134,7 @@ protected override void OnPointerMoved(PointerEventArgs e) { var radius = Math.Min(Bounds.Width, Bounds.Height) / 2 * 0.9; if (radius <= 0) return; - var scale = RimChroma / radius * (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? FineFactor : 1.0); + var scale = RimChroma / radius * DragFactor * (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? FineFactor : 1.0); var (cb, cr) = ChromaFromTint(R, G, B); cb += delta.X * scale; cr -= delta.Y * scale; diff --git a/editor/Editors/ColorWheelsPanel.cs b/editor/Editors/ColorWheelsPanel.cs index 780e0f352..8f605c1d3 100644 --- a/editor/Editors/ColorWheelsPanel.cs +++ b/editor/Editors/ColorWheelsPanel.cs @@ -29,9 +29,8 @@ private void Build() { // Every object row hosts this panel, only the marked one may claim its children if (DataContext is not GenericFieldVM { IsColorWheels: true } group) return; - var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), Margin = new(0, 4, 0, 4) }; - for (var i = 0; i < Wheels.Length; i++) { - var (label, tintName, offsetName) = Wheels[i]; + var stack = new StackPanel { Spacing = 12, Margin = new(0, 4, 0, 4) }; + foreach (var (label, tintName, offsetName) in Wheels) { var tint = group.Children.FirstOrDefault(c => c.Name == tintName && c.IsColor3); var offset = group.Children.FirstOrDefault(c => c.Name == offsetName && c.IsFloat); // A schema missing a field keeps its plain row rather than losing the control @@ -39,12 +38,10 @@ private void Build() { tint.OwnedByWidget = true; offset.OwnedByWidget = true; - var column = BuildWheel(label, tint, offset); - Grid.SetColumn(column, i); - grid.Children.Add(column); + stack.Children.Add(BuildWheel(label, tint, offset)); } - Content = grid; + Content = stack; } private static StackPanel BuildWheel(string label, GenericFieldVM tint, GenericFieldVM offset) { @@ -53,7 +50,9 @@ private static StackPanel BuildWheel(string label, GenericFieldVM tint, GenericF wheel.Bind(ColorWheel.GProperty, new Binding(nameof(GenericFieldVM.Y)) { Source = tint, Mode = BindingMode.TwoWay }); wheel.Bind(ColorWheel.BProperty, new Binding(nameof(GenericFieldVM.Z)) { Source = tint, Mode = BindingMode.TwoWay }); - var brightness = new DragFloatBox { Minimum = offset.Minimum, Maximum = offset.Maximum, Classes = { "compact-field" } }; + var brightness = new DragFloatBox { + Minimum = offset.Minimum, Maximum = offset.Maximum, CoarseStep = 0.01f, Classes = { "compact-field" } + }; brightness.Bind(DragFloatBox.ValueProperty, new Binding(nameof(GenericFieldVM.FloatVal)) { Source = offset, Mode = BindingMode.TwoWay }); ToolTip.SetTip(brightness, "Brightness"); diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index e45de216d..1ef23aef1 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -88,7 +88,7 @@ void AssetRegistry::init() { s_schema_toml["destruction_material"] = [](const toml::table& t, Handle s) { return std::make_unique(t, std::move(s)); }; - s_schema_toml["post_process"] = [](const toml::table& t, Handle s) { + s_schema_toml["post_process_profile"] = [](const toml::table& t, Handle s) { return std::make_unique(t, std::move(s)); }; diff --git a/engine/src/toast/renderer/settings/post_process_profile.hpp b/engine/src/toast/renderer/settings/post_process_profile.hpp index d5395dc97..5726e83c2 100644 --- a/engine/src/toast/renderer/settings/post_process_profile.hpp +++ b/engine/src/toast/renderer/settings/post_process_profile.hpp @@ -16,7 +16,7 @@ class TOAST_API PostProcessProfile : public Data { [[nodiscard]] auto type() const -> std::string_view override { - return "post_process"; + return "post_process_profile"; } /// Bumps whenever the file is re-read