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..bc4f0e442 --- /dev/null +++ b/cmake/vcpkg-ports/nvidia-dlss/nvidia-dlss-config.cmake @@ -0,0 +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, 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" + 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() + +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 new file mode 100644 index 000000000..1c4127911 --- /dev/null +++ b/cmake/vcpkg-ports/nvidia-dlss/portfile.cmake @@ -0,0 +1,70 @@ +# 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 + 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) + 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() + +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" 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}") +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..5565325c4 --- /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 | linux) & x64" +} diff --git a/editor/Assets/AssetBrowserViewModel.cs b/editor/Assets/AssetBrowserViewModel.cs index 6c3fae51d..b200ac099 100644 --- a/editor/Assets/AssetBrowserViewModel.cs +++ b/editor/Assets/AssetBrowserViewModel.cs @@ -52,7 +52,8 @@ public class AssetBrowserViewModel : Tool, INotifyPropertyChanged, IDisposable { new HdrImporter(), new VoxImporter(new VoxImporter.Settings()), new AudioBankImporter(), - new AudioStringImporter(new AudioStringImporter.Settings()) + new AudioStringImporter(new AudioStringImporter.Settings()), + new VideoImporter() ]; private static readonly HashSet s_artworkExts = new( @@ -60,7 +61,7 @@ public class AssetBrowserViewModel : Tool, INotifyPropertyChanged, IDisposable { StringComparer.OrdinalIgnoreCase); private static readonly HashSet s_assetExts = new( - AssetTypeRegistry.All.Select(a => a.Extension), + AssetTypeRegistry.All.SelectMany(a => a.AllExtensions), StringComparer.OrdinalIgnoreCase); private static readonly HashSet s_reservedNames = ["root", "world", "global"]; diff --git a/editor/Assets/AssetDatabase.cs b/editor/Assets/AssetDatabase.cs index 8d69fba06..6b05e3a76 100644 --- a/editor/Assets/AssetDatabase.cs +++ b/editor/Assets/AssetDatabase.cs @@ -20,7 +20,8 @@ namespace editor.Assets; public static class AssetDatabase { // extension -> engine asset type, derived from the registry private static readonly Dictionary s_assetTypes = - AssetTypeRegistry.All.ToDictionary(a => a.Extension, a => a.Type, StringComparer.OrdinalIgnoreCase); + AssetTypeRegistry.All.SelectMany(a => a.AllExtensions.Select(e => (e, a.Type))) + .ToDictionary(p => p.e, p => p.Type, StringComparer.OrdinalIgnoreCase); public static event Action? ReloadedDatabase; @@ -331,6 +332,7 @@ public static async Task Reimport( ".hdr" => new HdrImporter(), ".bank" when isStringsBank => new AudioStringImporter(new AudioStringImporter.Settings()), ".bank" => new AudioBankImporter(), + ".webm" or ".mp4" or ".mkv" => new VideoImporter(), _ => new TextureImporter(textureSettings) }; diff --git a/editor/Assets/Importers/CompactImportWindowViewModel.cs b/editor/Assets/Importers/CompactImportWindowViewModel.cs index b300e38ae..ab0d360ef 100644 --- a/editor/Assets/Importers/CompactImportWindowViewModel.cs +++ b/editor/Assets/Importers/CompactImportWindowViewModel.cs @@ -33,7 +33,8 @@ public CompactImportWindowViewModel(IReadOnlyList filePaths, string loca new GltfImporter(GltfSettings, TextureSettings), new VoxImporter(VoxSettings), new AudioBankImporter(), - new AudioStringImporter(AudioStringSettings) + new AudioStringImporter(AudioStringSettings), + new VideoImporter() ]; RebuildSettingsCards(); diff --git a/editor/Assets/Importers/ImportWindowViewModel.cs b/editor/Assets/Importers/ImportWindowViewModel.cs index 4b282ed04..8bb4e9373 100644 --- a/editor/Assets/Importers/ImportWindowViewModel.cs +++ b/editor/Assets/Importers/ImportWindowViewModel.cs @@ -299,7 +299,8 @@ public ImportWindowViewModel(string? destination = null) { new AudioStringImporter(AudioStringSettings), new FontImporter(), new UIImageImporter(), - new HdrImporter() + new HdrImporter(), + new VideoImporter() ]; m_allowedExtensions = []; foreach (var importer in m_importers) diff --git a/editor/Assets/Importers/VideoImporter.cs b/editor/Assets/Importers/VideoImporter.cs new file mode 100644 index 000000000..4adf20d1a --- /dev/null +++ b/editor/Assets/Importers/VideoImporter.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using editor.Assets.Types; +using Lucide.Avalonia; + +namespace editor.Assets.Importers; + +/// Copies a video file as is; the engine decodes it at runtime, VP9 .webm plays everywhere. +public class VideoImporter : IAssetImporter { + public bool CanHandle(string filePath) { + return SupportedExtensions.Contains(Path.GetExtension(filePath), StringComparer.OrdinalIgnoreCase); + } + + public IReadOnlyList SupportedExtensions => [".webm", ".mp4", ".mkv"]; + public string DisplayName => "Video"; + public LucideIconKind Icon => LucideIconKind.Film; + public BaseAsset PrimaryOutputType => AssetTypeRegistry.ByType("video")!; + + public IReadOnlyList GetSettings() { + return []; + } + + public Task> Import( + string realSourcePath, ImportContext ctx, Action log, Action? progress = null) { + try { + log("Importing video..."); + Directory.CreateDirectory(ctx.DestDir); + var destPath = Path.Combine(ctx.DestDir, Path.GetFileName(realSourcePath)); + File.Copy(realSourcePath, destPath, true); + + log("Writing .meta sidecar..."); + var uid = UidGenerator.Generate(); + var header = new MetaHeader { Uid = uid, Type = PrimaryOutputType.Type, Source = ctx.SourceVirtualPath }; + MetaFile.Write(destPath, header); + return Task.FromResult>([uid]); + } catch (Exception exception) { + return Task.FromException>(exception); + } + } +} diff --git a/editor/Assets/MaterialSchemaGenerator.cs b/editor/Assets/MaterialSchemaGenerator.cs index c7a74c3fb..580b8804d 100644 --- a/editor/Assets/MaterialSchemaGenerator.cs +++ b/editor/Assets/MaterialSchemaGenerator.cs @@ -105,7 +105,9 @@ private static JsonObject WrapEnum(string[] options, string defaultValue) { private static JsonObject TextureDefProperties(TomlTable? textureDefaults) { var props = new JsonObject { - ["texture"] = new JsonObject { ["x-toast-type"] = "asset", ["x-toast-asset-type"] = "texture" }, + ["texture"] = new JsonObject { + ["x-toast-type"] = "asset", ["x-toast-asset-type"] = Components.Elements.AssetBox.MaterialTextureType + }, ["repeat_u"] = WrapEnum(["repeat", "mirrored", "clamp", "border"], "repeat"), ["repeat_v"] = WrapEnum(["repeat", "mirrored", "clamp", "border"], "repeat"), ["min_filter"] = WrapEnum(["nearest", "linear"], "linear"), diff --git a/editor/Assets/Types/AssetTypeRegistry.cs b/editor/Assets/Types/AssetTypeRegistry.cs index e43b2ca1c..98581c47f 100644 --- a/editor/Assets/Types/AssetTypeRegistry.cs +++ b/editor/Assets/Types/AssetTypeRegistry.cs @@ -25,7 +25,7 @@ static AssetTypeRegistry() { public static IReadOnlyList<(string Category, IReadOnlyList Types)> CreatableByCategory { get; } public static BaseAsset? ByExtension(string ext) { - return All.FirstOrDefault(a => a.Extension.Equals(ext, StringComparison.OrdinalIgnoreCase)); + return All.FirstOrDefault(a => a.AllExtensions.Any(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase))); } public static BaseAsset? ByType(string type) { diff --git a/editor/Assets/Types/BaseAsset.cs b/editor/Assets/Types/BaseAsset.cs index 9443220af..1e06c0103 100644 --- a/editor/Assets/Types/BaseAsset.cs +++ b/editor/Assets/Types/BaseAsset.cs @@ -10,6 +10,9 @@ namespace editor.Assets.Types; public abstract class BaseAsset { public abstract string Type { get; } public abstract string Extension { get; } + /// Further extensions files of this type keep, e.g. a video imported as .mp4. + public virtual IReadOnlyList ExtraExtensions => []; + public IEnumerable AllExtensions => ExtraExtensions.Prepend(Extension); public abstract string DisplayName { get; } public abstract string ChipText { get; } public abstract string ChipColor { get; } 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/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/editor/Assets/Types/VideoAsset.cs b/editor/Assets/Types/VideoAsset.cs new file mode 100644 index 000000000..7c788f61d --- /dev/null +++ b/editor/Assets/Types/VideoAsset.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using Lucide.Avalonia; + +namespace editor.Assets.Types; + +public sealed class VideoAsset : BaseAsset { + public override string Type => "video"; + public override string Extension => ".webm"; + public override IReadOnlyList ExtraExtensions => [".mp4", ".mkv"]; + public override string DisplayName => "Video"; + public override string ChipText => "VID"; + public override string ChipColor => "Orange"; + public override LucideIconKind Icon => LucideIconKind.Film; + public override bool CanBeCreated => false; + public override string Category => "Visual"; + public override bool HasThumbnail => false; + public override bool CanBeEdited => false; + public override string EditorTool => ""; + public override string SchemaPath => ""; +} diff --git a/editor/Components/Elements/AssetBox.cs b/editor/Components/Elements/AssetBox.cs index 3ea6cbd05..b87f19a25 100644 --- a/editor/Components/Elements/AssetBox.cs +++ b/editor/Components/Elements/AssetBox.cs @@ -262,6 +262,9 @@ private void UpdateClipboardMenu() { m_pasteItem.Command = FieldPasteCommand; } + /// Material texture slots, which accept videos as well as textures. + public const string MaterialTextureType = "material_texture"; + private static string? NormalizeAssetType(string? type) { if (string.IsNullOrEmpty(type)) return null; // Direct lookup (handles types that are already identifiers like "texture") @@ -280,12 +283,15 @@ private void UpdateClipboardMenu() { private async void OpenPicker() { if (!IsEnabled || (TopLevel.GetTopLevel(this) as Window ?? App.MainWindow) is not { } owner) return; var normalized = NormalizeAssetType(AssetType); + // A material slot also takes a video; other texture fields load the uid as a texture without checking + if (normalized == MaterialTextureType) normalized = "texture"; // A material picker should also show material instances var extra = normalized switch { "material" => "material_instance", "voxel_model" => "node", _ => null }; + if (AssetType == MaterialTextureType) extra = "video"; var picked = await new AssetList(normalized, extra).ShowDialog(owner); if (picked is not null) Value = picked; } @@ -309,6 +315,8 @@ private bool IsAcceptable(DragEventArgs e) { } private static bool IsCompatibleType(string boxType, string dragged) { + if (boxType == MaterialTextureType) + return dragged is "texture" or "video"; return (string.Equals(boxType, "material", StringComparison.OrdinalIgnoreCase) && string.Equals(dragged, "material_instance", StringComparison.OrdinalIgnoreCase)) || (string.Equals(boxType, "voxel_model", StringComparison.OrdinalIgnoreCase) 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/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/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/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/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 23e4aed7e..6009c8213 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -43,6 +43,7 @@ find_package(RmlUi CONFIG REQUIRED) find_package(Lua REQUIRED) find_package(imgui CONFIG REQUIRED) find_package(cpptrace CONFIG REQUIRED) +find_package(FFMPEG REQUIRED) find_path(LUABRIDGE3_INCLUDE_DIRS "luabridge3/LuaBridge/Array.h") # External paths @@ -97,7 +98,7 @@ set(TOAST_ENGINE_OUTPUT_ROOT "${OUTPUT_ROOT}/$/toast_engine") set(TOAST_ENGINE_BIN_DIR "${TOAST_ENGINE_OUTPUT_ROOT}/bin") target_include_directories(toast_engine - PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}" "${EXTERNAL_INC_DIR}" ${LUA_INCLUDE_DIR} ${LUABRIDGE3_INCLUDE_DIRS} + PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}" "${EXTERNAL_INC_DIR}" ${LUA_INCLUDE_DIR} ${LUABRIDGE3_INCLUDE_DIRS} ${FFMPEG_INCLUDE_DIRS} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/ffi" "${CMAKE_CURRENT_SOURCE_DIR}/generated" ) @@ -118,6 +119,7 @@ target_link_libraries(toast_engine $<$:${EXTERNAL_LIBS_DEBUG}> $<$>:${EXTERNAL_LIBS_RELEASE}> ${LUA_LIBRARIES} + ${FFMPEG_LIBRARIES} PUBLIC $<$,$>:Tracy::TracyClient> glm::glm nlohmann_json::nlohmann_json GPUOpen::VulkanMemoryAllocator ) @@ -138,6 +140,28 @@ endforeach () target_compile_definitions(toast_engine PRIVATE TOAST_EXPORT) +# 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 OR CMAKE_SYSTEM_NAME STREQUAL Linux;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) @@ -175,7 +199,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} @@ -301,6 +325,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 $ @@ -311,6 +340,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/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/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/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/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/selection_mask.slang b/engine/assets/shaders/selection_mask.slang index 2a3f6a26a..37e8d6b21 100644 --- a/engine/assets/shaders/selection_mask.slang +++ b/engine/assets/shaders/selection_mask.slang @@ -45,7 +45,7 @@ struct PushConstants PushConstants gPush; /// Relative since voxel cells raster as quads in the scene and march here -static const float kDepthSlack = 0.002; +static const float kDepthSlack = 0.05; /// The mask shares the scene jitter so both depths sample the same point bool unoccluded(int2 pixel, float depth) 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/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/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/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 487c77c35..9cbf96c38 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 { @@ -24,6 +25,7 @@ void AssetRegistry::init() { // Raw binary loaders s_raw["mesh"] = [](const std::vector& d) { return std::make_unique(d); }; s_raw["texture"] = [](std::vector d) { return std::make_unique(std::move(d)); }; + s_raw["video"] = [](std::vector d) { return std::make_unique