diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 2d31cf9e7..8b11197f0 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -31,6 +31,17 @@ env:
RUN_TESTS: true
jobs:
+ feature-index:
+ runs-on: ubuntu-24.04
+ name: Check feature index
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Check that wiki/Features.md lists all features
+ run: python3 wiki/check_features.py
+
windows-build:
runs-on: windows-2022
name: Build on Windows
@@ -62,7 +73,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
cache: ${{ env.USE_CACHE }}
# This doesn't work when the Visual Studio C++ CLI was set up first (maybe needs a setup with 2019 version)
@@ -138,7 +149,7 @@ jobs:
cc: "cl"
cxx: "cl"
configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake'
- -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja
+ -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja
parallel: 16
build-type: ${{ matrix.build-type }}
@@ -206,7 +217,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
cache: ${{ env.USE_CACHE }}
- name: Setup Ninja
@@ -274,7 +285,7 @@ jobs:
cc: "gcc"
cxx: "g++"
configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake'
- -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja
+ -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja
parallel: 16
build-type: ${{ matrix.build-type }}
@@ -339,7 +350,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
cache: ${{ env.USE_CACHE }}
- name: Setup Ninja
@@ -429,7 +440,7 @@ jobs:
cc: "clang"
cxx: "clang++"
configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake'
- -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_BUNDLE=ON -DATLAS_HEADLESS=ON -G Ninja
+ -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_BUNDLE=ON -DATLAS_HEADLESS=ON -G Ninja
parallel: 16
build-type: ${{ matrix.build-type }}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cd80630eb..9f083e352 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -31,7 +31,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
- name: Delete MSVC tool version
shell: pwsh
@@ -110,7 +110,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
- name: Setup Ninja
uses: ashutoshvarma/setup-ninja@master
@@ -178,7 +178,7 @@ jobs:
uses: friendlyanon/setup-vcpkg@v1
# Committish: The commit sha of the vcpkg repo, same as in vcpkg.json
with:
- committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19
+ committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091
cache: ${{ env.USE_CACHE }}
- name: Setup Ninja
diff --git a/.gitignore b/.gitignore
index e6080f1e6..de231aef0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,8 @@
# Project files
!/.gitattributes
!/.gitignore
+!/.mcp.json
+!/AtlasEngine.aeproject
!/CMakeLists.txt
!/Doxyfile
!/LICENSE.md
@@ -18,8 +20,12 @@
!/.github/
!/libs/
!/src/
+!/templates/
!/wiki/
+# Vendor SDKs of the optional upscalers are downloaded separately (see libs/upscalers/README.md)
+/libs/upscalers/*/sdk/
+
# data/: engine assets only. The large sample asset folders are downloaded separately (see data/README.md)
!/data/
/data/*
@@ -33,6 +39,16 @@
!/data/shader/
!/data/sponza/
+# Import output stays local, only these default assets are tracked
+/data/materials/*
+!/data/materials/CapsuleMaterial.aematerial
+!/data/materials/Chrome.aematerial
+!/data/materials/Material.001.aematerial
+/data/meshes/*
+!/data/meshes/capsule.aemesh
+!/data/meshes/chromesphere.aemesh
+!/data/meshes/metallicwall.aemesh
+
!/data/README.md
!/data/capsule.gltf
!/data/chromesphere.bin
@@ -71,3 +87,4 @@ __pycache__/
local.properties
CMakeSettings.json
CMakeUserPresets.json
+src/bridge/examples
diff --git a/.mcp.json b/.mcp.json
new file mode 100644
index 000000000..e1afdf714
--- /dev/null
+++ b/.mcp.json
@@ -0,0 +1,8 @@
+{
+ "mcpServers": {
+ "atlas": {
+ "type": "http",
+ "url": "http://127.0.0.1:7777/mcp"
+ }
+ }
+}
diff --git a/AtlasEngine.aeproject b/AtlasEngine.aeproject
new file mode 100644
index 000000000..f41ac5565
--- /dev/null
+++ b/AtlasEngine.aeproject
@@ -0,0 +1,6 @@
+{
+ "name": "Atlas Engine",
+ "assetDirectory": "data",
+ "mainScript": "",
+ "startScene": "scenes/sponza.aescene"
+}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2a25207ea..8f2096dc1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -14,6 +14,8 @@ endif(COMMAND cmake_policy)
cmake_minimum_required(VERSION 3.25)
project(AtlasEngine VERSION 0.2.1)
+# The engine library has its own project() call, which clears PROJECT_VERSION
+set(ATLAS_ENGINE_VERSION ${PROJECT_VERSION})
# Only 64 bit is supported
###################################################################
@@ -27,11 +29,13 @@ option(ATLAS_EXPORT_MAIN "Add main file in root of directory tree. Add ${ATLAS_E
option(ATLAS_NO_APP "Disables the engines main function" OFF)
option(ATLAS_DEMO "Build demo executable" OFF)
option(ATLAS_EDITOR "Build editor executable" ON)
+option(ATLAS_BRIDGE "Build the Atlas Bridge executable, the scene capture and inspection tool" OFF)
+option(ATLAS_BRIDGE_LIBRARY "Build only the bridge library, for game hosts that run bridge jobs" OFF)
option(ATLAS_IMGUI "Activate ImGui integration" OFF)
option(ATLAS_ASSIMP "Activate Assimp integration" ON)
option(ATLAS_HEADLESS "Activate support for running the engine in headless mode" OFF)
-option(ATLAS_BINDLESS "Activate support for running the engine with bindless resources turned on" ON)
option(ATLAS_BUNDLE "Allows the applications to be bundled and installed on MacOS" OFF)
+option(ATLAS_LUA_SAFETIES "Check the arguments of Lua binding calls, wrong ones raise Lua errors instead of crashing" ON)
option(ATLAS_MSVC_HOT_RELOAD "Configures all targets to be hot-reloadable" OFF)
if(${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
@@ -72,23 +76,24 @@ endif()
if (ATLAS_DEMO)
set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE)
endif()
+if (ATLAS_BRIDGE)
+set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE)
+endif()
# Set dependencies location #######################################################################
set (ATLAS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/engine)
set (DEMO_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/demo)
set (TESTS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/tests)
set (EDITOR_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/editor)
+set (BRIDGE_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/bridge)
set (IMGUI_EXTENSION_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/ImguiExtension)
# Add dependencies ################################################################################
-find_package(SDL2 CONFIG REQUIRED)
+find_package(SDL3 CONFIG REQUIRED)
if(ATLAS_ASSIMP)
find_package(assimp CONFIG REQUIRED)
endif()
-if (ANDROID)
- add_subdirectory(${HIDAPI_LOCATION})
-endif()
find_package(unofficial-spirv-reflect CONFIG REQUIRED)
find_package(Vulkan REQUIRED)
@@ -100,6 +105,9 @@ find_package(SPIRV-Tools-opt CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
find_package(Jolt CONFIG REQUIRED)
find_package(Lua REQUIRED)
+find_package(Ktx CONFIG REQUIRED)
+find_package(recastnavigation CONFIG REQUIRED)
+find_package(meshoptimizer CONFIG REQUIRED)
if (ATLAS_TESTS)
find_package(GTest CONFIG REQUIRED)
@@ -121,6 +129,11 @@ if (ATLAS_EDITOR)
add_subdirectory(${EDITOR_LOCATION})
endif()
+# The editor runs the commands of the bridge in the open scene
+if (ATLAS_BRIDGE OR ATLAS_BRIDGE_LIBRARY OR ATLAS_EDITOR)
+ add_subdirectory(${BRIDGE_LOCATION})
+endif()
+
if (ATLAS_TESTS)
add_subdirectory(${TESTS_LOCATION})
endif()
diff --git a/README.md b/README.md
index e5cdcbaaf..04f8422aa 100644
--- a/README.md
+++ b/README.md
@@ -55,11 +55,11 @@ initialize the engine yourself
- **ATLAS_IMGUI** Enables the [ImGui](https://github.com/ocornut/imgui) integration. Is enabled by default if the demo project is build.
- **ATLAS_ASSIMP** Enables the [Assimp](https://github.com/assimp/assimp) integration. Is enabled by default.
- **ATLAS_HEADLESS** Enables the headless support, which means no window needs to be created. Is disabled by default.
-- **ATLAS_BINDLESS** Enables support for bindless resources. Might be problematic on MacOS. Enabled by default.
- **ATLAS_TESTS** Generates the testing project and allows to target it.
- **ATLAS_BUNDLE** Allows the applications to be bundled and installed on MacOS. Disabled by default
## Documentation
If you want more information have a look into the [Documentation](https://tippesi.github.io/Atlas-Engine-Doc/index.html).
+To let an agent (Claude Code, Codex, ChatGPT, ...) work in the scene open in the editor, see [Atlas Bridge](wiki/AtlasBridge.md).
## License
The source code is licensed under the MIT license. The copyright notices of the dependencies can be found
in the LICENSE.md file in the dependency directory.
diff --git a/THIRDPARTY.md b/THIRDPARTY.md
index 0964aa752..52c9d66ae 100644
--- a/THIRDPARTY.md
+++ b/THIRDPARTY.md
@@ -322,6 +322,25 @@ JoltPhysics
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+KTX-Software
+--------------------------------------------------------------------------------
+ Copyright 2013-2020 Mark Callow and The Khronos Group Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ Includes the Basis Universal transcoder (Copyright 2019-2021 Binomial LLC, Apache-2.0)
+ and links zstd (Copyright (c) Meta Platforms, Inc. and affiliates, BSD-3-Clause).
+
spirv-reflect
--------------------------------------------------------------------------------
Apache License
diff --git a/data/editor/icons/cancel.png b/data/editor/icons/cancel.png
new file mode 100644
index 000000000..40216068f
Binary files /dev/null and b/data/editor/icons/cancel.png differ
diff --git a/data/editor/icons/cancel.svg b/data/editor/icons/cancel.svg
new file mode 100644
index 000000000..8504fbfda
--- /dev/null
+++ b/data/editor/icons/cancel.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/cancel_light.png b/data/editor/icons/cancel_light.png
new file mode 100644
index 000000000..15d6db4c8
Binary files /dev/null and b/data/editor/icons/cancel_light.png differ
diff --git a/data/editor/icons/clouds.png b/data/editor/icons/clouds.png
new file mode 100644
index 000000000..a2f8cdbb3
Binary files /dev/null and b/data/editor/icons/clouds.png differ
diff --git a/data/editor/icons/clouds.svg b/data/editor/icons/clouds.svg
new file mode 100644
index 000000000..a36bddda9
--- /dev/null
+++ b/data/editor/icons/clouds.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/clouds_light.png b/data/editor/icons/clouds_light.png
new file mode 100644
index 000000000..a86f413e5
Binary files /dev/null and b/data/editor/icons/clouds_light.png differ
diff --git a/data/editor/icons/error.png b/data/editor/icons/error.png
new file mode 100644
index 000000000..3f2270083
Binary files /dev/null and b/data/editor/icons/error.png differ
diff --git a/data/editor/icons/error.svg b/data/editor/icons/error.svg
new file mode 100644
index 000000000..9a83c9306
--- /dev/null
+++ b/data/editor/icons/error.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/error_light.png b/data/editor/icons/error_light.png
new file mode 100644
index 000000000..36ab386b6
Binary files /dev/null and b/data/editor/icons/error_light.png differ
diff --git a/data/editor/icons/fog.png b/data/editor/icons/fog.png
new file mode 100644
index 000000000..794a098ef
Binary files /dev/null and b/data/editor/icons/fog.png differ
diff --git a/data/editor/icons/fog.svg b/data/editor/icons/fog.svg
new file mode 100644
index 000000000..428ea0add
--- /dev/null
+++ b/data/editor/icons/fog.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/fog_light.png b/data/editor/icons/fog_light.png
new file mode 100644
index 000000000..2e2c8d3ea
Binary files /dev/null and b/data/editor/icons/fog_light.png differ
diff --git a/data/editor/icons/globalIllumination.png b/data/editor/icons/globalIllumination.png
new file mode 100644
index 000000000..7ee7b2ebc
Binary files /dev/null and b/data/editor/icons/globalIllumination.png differ
diff --git a/data/editor/icons/globalIllumination.svg b/data/editor/icons/globalIllumination.svg
new file mode 100644
index 000000000..78e442622
--- /dev/null
+++ b/data/editor/icons/globalIllumination.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/globalIllumination_light.png b/data/editor/icons/globalIllumination_light.png
new file mode 100644
index 000000000..8dae6a821
Binary files /dev/null and b/data/editor/icons/globalIllumination_light.png differ
diff --git a/data/editor/icons/irradianceVolume.png b/data/editor/icons/irradianceVolume.png
new file mode 100644
index 000000000..2ef9b0d6e
Binary files /dev/null and b/data/editor/icons/irradianceVolume.png differ
diff --git a/data/editor/icons/irradianceVolume.svg b/data/editor/icons/irradianceVolume.svg
new file mode 100644
index 000000000..9fbbea5ed
--- /dev/null
+++ b/data/editor/icons/irradianceVolume.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/irradianceVolume_light.png b/data/editor/icons/irradianceVolume_light.png
new file mode 100644
index 000000000..a22c5bac4
Binary files /dev/null and b/data/editor/icons/irradianceVolume_light.png differ
diff --git a/data/editor/icons/log.png b/data/editor/icons/log.png
new file mode 100644
index 000000000..e59b73264
Binary files /dev/null and b/data/editor/icons/log.png differ
diff --git a/data/editor/icons/log.svg b/data/editor/icons/log.svg
new file mode 100644
index 000000000..53b09a6bd
--- /dev/null
+++ b/data/editor/icons/log.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/log_light.png b/data/editor/icons/log_light.png
new file mode 100644
index 000000000..d34812040
Binary files /dev/null and b/data/editor/icons/log_light.png differ
diff --git a/data/editor/icons/materialGraph.png b/data/editor/icons/materialGraph.png
new file mode 100644
index 000000000..118cce659
Binary files /dev/null and b/data/editor/icons/materialGraph.png differ
diff --git a/data/editor/icons/materialGraph.svg b/data/editor/icons/materialGraph.svg
new file mode 100644
index 000000000..0f5425584
--- /dev/null
+++ b/data/editor/icons/materialGraph.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/materialGraph_light.png b/data/editor/icons/materialGraph_light.png
new file mode 100644
index 000000000..8c31ee3d6
Binary files /dev/null and b/data/editor/icons/materialGraph_light.png differ
diff --git a/data/editor/icons/navigation.png b/data/editor/icons/navigation.png
new file mode 100644
index 000000000..1098b6337
Binary files /dev/null and b/data/editor/icons/navigation.png differ
diff --git a/data/editor/icons/navigation.svg b/data/editor/icons/navigation.svg
new file mode 100644
index 000000000..eff7d6127
--- /dev/null
+++ b/data/editor/icons/navigation.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/navigation_light.png b/data/editor/icons/navigation_light.png
new file mode 100644
index 000000000..f74440b4b
Binary files /dev/null and b/data/editor/icons/navigation_light.png differ
diff --git a/data/editor/icons/notifications.png b/data/editor/icons/notifications.png
new file mode 100644
index 000000000..ee217ed20
Binary files /dev/null and b/data/editor/icons/notifications.png differ
diff --git a/data/editor/icons/notifications.svg b/data/editor/icons/notifications.svg
new file mode 100644
index 000000000..dbfe0e040
--- /dev/null
+++ b/data/editor/icons/notifications.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/notifications_light.png b/data/editor/icons/notifications_light.png
new file mode 100644
index 000000000..ff24d3cb6
Binary files /dev/null and b/data/editor/icons/notifications_light.png differ
diff --git a/data/editor/icons/ocean.png b/data/editor/icons/ocean.png
new file mode 100644
index 000000000..548572661
Binary files /dev/null and b/data/editor/icons/ocean.png differ
diff --git a/data/editor/icons/ocean.svg b/data/editor/icons/ocean.svg
new file mode 100644
index 000000000..b6857326d
--- /dev/null
+++ b/data/editor/icons/ocean.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/ocean_light.png b/data/editor/icons/ocean_light.png
new file mode 100644
index 000000000..16ce5fb94
Binary files /dev/null and b/data/editor/icons/ocean_light.png differ
diff --git a/data/editor/icons/openInNew.png b/data/editor/icons/openInNew.png
new file mode 100644
index 000000000..5fb94c3bc
Binary files /dev/null and b/data/editor/icons/openInNew.png differ
diff --git a/data/editor/icons/openInNew.svg b/data/editor/icons/openInNew.svg
new file mode 100644
index 000000000..ef3fe201a
--- /dev/null
+++ b/data/editor/icons/openInNew.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/openInNew_light.png b/data/editor/icons/openInNew_light.png
new file mode 100644
index 000000000..314551c04
Binary files /dev/null and b/data/editor/icons/openInNew_light.png differ
diff --git a/data/editor/icons/pause.png b/data/editor/icons/pause.png
new file mode 100644
index 000000000..01b8e5293
Binary files /dev/null and b/data/editor/icons/pause.png differ
diff --git a/data/editor/icons/pause.svg b/data/editor/icons/pause.svg
new file mode 100644
index 000000000..95bc792fc
--- /dev/null
+++ b/data/editor/icons/pause.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/pause_light.png b/data/editor/icons/pause_light.png
new file mode 100644
index 000000000..61fdadb44
Binary files /dev/null and b/data/editor/icons/pause_light.png differ
diff --git a/data/editor/icons/pin.png b/data/editor/icons/pin.png
new file mode 100644
index 000000000..e7333c9b7
Binary files /dev/null and b/data/editor/icons/pin.png differ
diff --git a/data/editor/icons/pin.svg b/data/editor/icons/pin.svg
new file mode 100644
index 000000000..9f3538e70
--- /dev/null
+++ b/data/editor/icons/pin.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/pinFilled.png b/data/editor/icons/pinFilled.png
new file mode 100644
index 000000000..3439438ca
Binary files /dev/null and b/data/editor/icons/pinFilled.png differ
diff --git a/data/editor/icons/pinFilled.svg b/data/editor/icons/pinFilled.svg
new file mode 100644
index 000000000..c2f8ef72f
--- /dev/null
+++ b/data/editor/icons/pinFilled.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/pinFilled_light.png b/data/editor/icons/pinFilled_light.png
new file mode 100644
index 000000000..77c4aba1b
Binary files /dev/null and b/data/editor/icons/pinFilled_light.png differ
diff --git a/data/editor/icons/pin_light.png b/data/editor/icons/pin_light.png
new file mode 100644
index 000000000..08f6adf49
Binary files /dev/null and b/data/editor/icons/pin_light.png differ
diff --git a/data/editor/icons/postProcessing.png b/data/editor/icons/postProcessing.png
new file mode 100644
index 000000000..90f327d6f
Binary files /dev/null and b/data/editor/icons/postProcessing.png differ
diff --git a/data/editor/icons/postProcessing.svg b/data/editor/icons/postProcessing.svg
new file mode 100644
index 000000000..887f8bd49
--- /dev/null
+++ b/data/editor/icons/postProcessing.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/postProcessing_light.png b/data/editor/icons/postProcessing_light.png
new file mode 100644
index 000000000..0b14a2336
Binary files /dev/null and b/data/editor/icons/postProcessing_light.png differ
diff --git a/data/editor/icons/profiler.png b/data/editor/icons/profiler.png
new file mode 100644
index 000000000..821a59c17
Binary files /dev/null and b/data/editor/icons/profiler.png differ
diff --git a/data/editor/icons/profiler.svg b/data/editor/icons/profiler.svg
new file mode 100644
index 000000000..cf94f4936
--- /dev/null
+++ b/data/editor/icons/profiler.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/profiler_light.png b/data/editor/icons/profiler_light.png
new file mode 100644
index 000000000..e62da384b
Binary files /dev/null and b/data/editor/icons/profiler_light.png differ
diff --git a/data/editor/icons/redo.png b/data/editor/icons/redo.png
new file mode 100644
index 000000000..0c77c238f
Binary files /dev/null and b/data/editor/icons/redo.png differ
diff --git a/data/editor/icons/redo.svg b/data/editor/icons/redo.svg
new file mode 100644
index 000000000..94d65b4c8
--- /dev/null
+++ b/data/editor/icons/redo.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/redo_light.png b/data/editor/icons/redo_light.png
new file mode 100644
index 000000000..3c87cdb97
Binary files /dev/null and b/data/editor/icons/redo_light.png differ
diff --git a/data/editor/icons/reflection.png b/data/editor/icons/reflection.png
new file mode 100644
index 000000000..622fdd042
Binary files /dev/null and b/data/editor/icons/reflection.png differ
diff --git a/data/editor/icons/reflection.svg b/data/editor/icons/reflection.svg
new file mode 100644
index 000000000..844fc7a08
--- /dev/null
+++ b/data/editor/icons/reflection.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/reflection_light.png b/data/editor/icons/reflection_light.png
new file mode 100644
index 000000000..131f94295
Binary files /dev/null and b/data/editor/icons/reflection_light.png differ
diff --git a/data/editor/icons/reset.png b/data/editor/icons/reset.png
new file mode 100644
index 000000000..0e3508cf7
Binary files /dev/null and b/data/editor/icons/reset.png differ
diff --git a/data/editor/icons/reset.svg b/data/editor/icons/reset.svg
new file mode 100644
index 000000000..8fa96d44b
--- /dev/null
+++ b/data/editor/icons/reset.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/reset_light.png b/data/editor/icons/reset_light.png
new file mode 100644
index 000000000..19165a5aa
Binary files /dev/null and b/data/editor/icons/reset_light.png differ
diff --git a/data/editor/icons/save.png b/data/editor/icons/save.png
new file mode 100644
index 000000000..a9743387e
Binary files /dev/null and b/data/editor/icons/save.png differ
diff --git a/data/editor/icons/save.svg b/data/editor/icons/save.svg
new file mode 100644
index 000000000..03da450db
--- /dev/null
+++ b/data/editor/icons/save.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/save_light.png b/data/editor/icons/save_light.png
new file mode 100644
index 000000000..795d8428b
Binary files /dev/null and b/data/editor/icons/save_light.png differ
diff --git a/data/editor/icons/scaleInverse.png b/data/editor/icons/scaleInverse.png
new file mode 100644
index 000000000..8b3b31670
Binary files /dev/null and b/data/editor/icons/scaleInverse.png differ
diff --git a/data/editor/icons/scaleInverse.svg b/data/editor/icons/scaleInverse.svg
new file mode 100644
index 000000000..2e33ce508
--- /dev/null
+++ b/data/editor/icons/scaleInverse.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/scaleInverse_light.png b/data/editor/icons/scaleInverse_light.png
new file mode 100644
index 000000000..04c84afe2
Binary files /dev/null and b/data/editor/icons/scaleInverse_light.png differ
diff --git a/data/editor/icons/search.png b/data/editor/icons/search.png
new file mode 100644
index 000000000..384f7331f
Binary files /dev/null and b/data/editor/icons/search.png differ
diff --git a/data/editor/icons/search.svg b/data/editor/icons/search.svg
new file mode 100644
index 000000000..ef0d0521e
--- /dev/null
+++ b/data/editor/icons/search.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/search_light.png b/data/editor/icons/search_light.png
new file mode 100644
index 000000000..cbd55e094
Binary files /dev/null and b/data/editor/icons/search_light.png differ
diff --git a/data/editor/icons/shadow.png b/data/editor/icons/shadow.png
new file mode 100644
index 000000000..3c7cc6741
Binary files /dev/null and b/data/editor/icons/shadow.png differ
diff --git a/data/editor/icons/shadow.svg b/data/editor/icons/shadow.svg
new file mode 100644
index 000000000..c37b321f4
--- /dev/null
+++ b/data/editor/icons/shadow.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/shadow_light.png b/data/editor/icons/shadow_light.png
new file mode 100644
index 000000000..53fd70f83
Binary files /dev/null and b/data/editor/icons/shadow_light.png differ
diff --git a/data/editor/icons/sky.png b/data/editor/icons/sky.png
new file mode 100644
index 000000000..c0276b9b3
Binary files /dev/null and b/data/editor/icons/sky.png differ
diff --git a/data/editor/icons/sky.svg b/data/editor/icons/sky.svg
new file mode 100644
index 000000000..8e4e9d0d9
--- /dev/null
+++ b/data/editor/icons/sky.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/sky_light.png b/data/editor/icons/sky_light.png
new file mode 100644
index 000000000..6a8770880
Binary files /dev/null and b/data/editor/icons/sky_light.png differ
diff --git a/data/editor/icons/undo.png b/data/editor/icons/undo.png
new file mode 100644
index 000000000..66d1ff32e
Binary files /dev/null and b/data/editor/icons/undo.png differ
diff --git a/data/editor/icons/undo.svg b/data/editor/icons/undo.svg
new file mode 100644
index 000000000..c451e1adc
--- /dev/null
+++ b/data/editor/icons/undo.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/undo_light.png b/data/editor/icons/undo_light.png
new file mode 100644
index 000000000..fc8c6340a
Binary files /dev/null and b/data/editor/icons/undo_light.png differ
diff --git a/data/editor/icons/viewGrid.png b/data/editor/icons/viewGrid.png
new file mode 100644
index 000000000..c9904ebe2
Binary files /dev/null and b/data/editor/icons/viewGrid.png differ
diff --git a/data/editor/icons/viewGrid.svg b/data/editor/icons/viewGrid.svg
new file mode 100644
index 000000000..962298238
--- /dev/null
+++ b/data/editor/icons/viewGrid.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/viewGrid_light.png b/data/editor/icons/viewGrid_light.png
new file mode 100644
index 000000000..76f6dbd53
Binary files /dev/null and b/data/editor/icons/viewGrid_light.png differ
diff --git a/data/editor/icons/viewList.png b/data/editor/icons/viewList.png
new file mode 100644
index 000000000..676f1c174
Binary files /dev/null and b/data/editor/icons/viewList.png differ
diff --git a/data/editor/icons/viewList.svg b/data/editor/icons/viewList.svg
new file mode 100644
index 000000000..8bff278f9
--- /dev/null
+++ b/data/editor/icons/viewList.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/viewList_light.png b/data/editor/icons/viewList_light.png
new file mode 100644
index 000000000..85e0c726f
Binary files /dev/null and b/data/editor/icons/viewList_light.png differ
diff --git a/data/editor/icons/warning.png b/data/editor/icons/warning.png
new file mode 100644
index 000000000..2d4ff221d
Binary files /dev/null and b/data/editor/icons/warning.png differ
diff --git a/data/editor/icons/warning.svg b/data/editor/icons/warning.svg
new file mode 100644
index 000000000..7fe972ff2
--- /dev/null
+++ b/data/editor/icons/warning.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/warning_light.png b/data/editor/icons/warning_light.png
new file mode 100644
index 000000000..1b5befc47
Binary files /dev/null and b/data/editor/icons/warning_light.png differ
diff --git a/data/editor/icons/wind.png b/data/editor/icons/wind.png
new file mode 100644
index 000000000..4bad7a7f0
Binary files /dev/null and b/data/editor/icons/wind.png differ
diff --git a/data/editor/icons/wind.svg b/data/editor/icons/wind.svg
new file mode 100644
index 000000000..5a41f9dbf
--- /dev/null
+++ b/data/editor/icons/wind.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/data/editor/icons/wind_light.png b/data/editor/icons/wind_light.png
new file mode 100644
index 000000000..d168c5bbd
Binary files /dev/null and b/data/editor/icons/wind_light.png differ
diff --git a/data/font/LICENSE b/data/font/LICENSE
index c660ed35c..cad0ee0ee 100644
--- a/data/font/LICENSE
+++ b/data/font/LICENSE
@@ -1,3 +1,5 @@
+Roboto (roboto.ttf)
+--------------------------------------------------------------------------------
Copyright 2024 Google
@@ -11,4 +13,101 @@
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
+ limitations under the License.
+
+Roboto Mono (robotomono.ttf)
+--------------------------------------------------------------------------------
+
+Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/data/font/robotomono.ttf b/data/font/robotomono.ttf
new file mode 100644
index 000000000..eb1fde544
Binary files /dev/null and b/data/font/robotomono.ttf differ
diff --git a/data/scenes/sponza.aescene b/data/scenes/sponza.aescene
index ebb6d0873..adf21663e 100644
Binary files a/data/scenes/sponza.aescene and b/data/scenes/sponza.aescene differ
diff --git a/data/shader/atmosphere/atmosphere.csh b/data/shader/atmosphere/atmosphere.csh
index 1716f759e..ed4dd92cb 100644
--- a/data/shader/atmosphere/atmosphere.csh
+++ b/data/shader/atmosphere/atmosphere.csh
@@ -27,6 +27,7 @@ layout(set = 3, binding = 3, std140) uniform UniformBuffer {
float surfaceHeightOffset;
float planetRadius;
float atmosphereRadius;
+ float sunAngularRadius;
} uniforms;
#ifndef ENVIRONMENT_PROBE
@@ -116,9 +117,9 @@ void main() {
vec3 GetSunDisk(vec3 viewDirection, AtmosphereParameters atmosphere) {
- float viewSunCosAngle = dot(viewDirection, uniforms.sunDirection.xyz);
- float sunDisk = smoothstep(cos(atmosphereSunAngularRadius * 1.25), cos(atmosphereSunAngularRadius),
- viewSunCosAngle);
+ // The chord length stays precise for small sun disks, unlike the cosine of the angle
+ float viewSunDistance = distance(viewDirection, uniforms.sunDirection.xyz);
+ float sunDisk = 1.0 - smoothstep(uniforms.sunAngularRadius, uniforms.sunAngularRadius * 1.25, viewSunDistance);
vec3 cameraUp = normalize(uniforms.cameraLocation.xyz - uniforms.planetCenter.xyz);
float cameraRadius = length(uniforms.cameraLocation.xyz - uniforms.planetCenter.xyz);
diff --git a/data/shader/atmosphere/common.hsh b/data/shader/atmosphere/common.hsh
index 424bbcffa..6da4fafb4 100644
--- a/data/shader/atmosphere/common.hsh
+++ b/data/shader/atmosphere/common.hsh
@@ -222,6 +222,7 @@ void GetRadiusMuFromMultipleScatteringTextureUv(vec2 uv, AtmosphereParameters at
}
+// Multiple scattering for a unit sun radiance
vec3 GetMultipleScattering(sampler2D multipleScatteringTexture, float radius, float muS,
AtmosphereParameters atmosphere) {
@@ -263,7 +264,7 @@ vec3 GetGroundRadiance(sampler2D transmittanceTexture, sampler2D multipleScatter
vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, groundRadius,
sunZenithCosAngle, atmosphere);
vec3 directIrradiance = sunRadiance * transmittanceToSun * saturate(sunZenithCosAngle);
- vec3 indirectIrradiance = GetMultipleScattering(multipleScatteringTexture, groundRadius,
+ vec3 indirectIrradiance = sunRadiance * GetMultipleScattering(multipleScatteringTexture, groundRadius,
sunZenithCosAngle, atmosphere) * PI * atmosphereGroundIndirectFactor;
return atmosphere.groundAlbedo * (directIrradiance + indirectIrradiance) / PI;
@@ -365,7 +366,7 @@ vec3 IntegrateAtmosphereScattering(sampler2D transmittanceTexture, sampler2D mul
vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, sampleRadius,
muS, atmosphere);
vec3 phaseScattering = GetAtmospherePhaseScattering(densities, cosTheta, atmosphere);
- vec3 multipleScattering = GetMultipleScattering(multipleScatteringTexture, sampleRadius,
+ vec3 multipleScattering = sunRadiance * GetMultipleScattering(multipleScatteringTexture, sampleRadius,
muS, atmosphere);
float shadowVisibility = max3(transmittanceToSun);
float multipleScatteringVisibility = shadowVisibility *
diff --git a/data/shader/atmosphere/multipleScattering.csh b/data/shader/atmosphere/multipleScattering.csh
index 60430b156..e5d2c7e59 100644
--- a/data/shader/atmosphere/multipleScattering.csh
+++ b/data/shader/atmosphere/multipleScattering.csh
@@ -1,12 +1,12 @@
#include
-layout (local_size_x = 8, local_size_y = 8) in;
+// One work group per texel, each invocation integrates one direction
+layout (local_size_x = 64) in;
layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D multipleScatteringImage;
layout(set = 3, binding = 1) uniform sampler2D transmittanceTexture;
layout(set = 3, binding = 2, std140) uniform UniformBuffer {
- vec4 sunRadiance;
vec4 rayleighScatteringCoeff;
vec4 groundAlbedo;
float mieScatteringCoeff;
@@ -20,16 +20,17 @@ layout(set = 3, binding = 2, std140) uniform UniformBuffer {
const int multipleScatteringDirectionSampleCount = 64;
const int multipleScatteringRaySampleCount = 20;
+shared vec3 sharedLuminance[multipleScatteringDirectionSampleCount];
+shared vec3 sharedMultiScatteringFactor[multipleScatteringDirectionSampleCount];
+
AtmosphereParameters GetAtmosphereParameters();
vec3 GetSphericalFibonacciDirection(int index, int count);
void main() {
- ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ ivec2 pixel = ivec2(gl_WorkGroupID.xy);
ivec2 resolution = imageSize(multipleScatteringImage);
-
- if (pixel.x >= resolution.x || pixel.y >= resolution.y)
- return;
+ int index = int(gl_LocalInvocationIndex);
vec2 uv = (vec2(pixel) + 0.5) / vec2(resolution);
@@ -40,25 +41,36 @@ void main() {
vec3 samplePosition = vec3(0.0, 0.0, radius);
vec3 sunDirection = vec3(sqrt(max(1.0 - muS * muS, 0.0)), 0.0, muS);
+ vec3 rayDirection = GetSphericalFibonacciDirection(index, multipleScatteringDirectionSampleCount);
- vec3 inScatteredLuminance = vec3(0.0);
- vec3 multiScatteringFactor = vec3(0.0);
+ vec3 rayLuminance;
+ vec3 rayMultiScatteringFactor;
+ // Computed for a unit sun radiance, the sun is applied where the table is sampled
+ IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection,
+ vec3(0.0), atmosphere, vec3(1.0), multipleScatteringRaySampleCount, 1.4,
+ rayLuminance, rayMultiScatteringFactor);
- float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount);
+ sharedLuminance[index] = rayLuminance;
+ sharedMultiScatteringFactor[index] = rayMultiScatteringFactor;
- for (int i = 0; i < multipleScatteringDirectionSampleCount; i++) {
- vec3 rayDirection = GetSphericalFibonacciDirection(i, multipleScatteringDirectionSampleCount);
+ barrier();
- vec3 rayLuminance;
- vec3 rayMultiScatteringFactor;
- IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection,
- vec3(0.0), atmosphere, uniforms.sunRadiance.rgb, multipleScatteringRaySampleCount, 1.4,
- rayLuminance, rayMultiScatteringFactor);
+ for (int stride = multipleScatteringDirectionSampleCount / 2; stride > 0; stride /= 2) {
+ if (index < stride) {
+ sharedLuminance[index] += sharedLuminance[index + stride];
+ sharedMultiScatteringFactor[index] += sharedMultiScatteringFactor[index + stride];
+ }
- inScatteredLuminance += rayLuminance * sampleWeight * atmosphereIsotropicPhase;
- multiScatteringFactor += rayMultiScatteringFactor * sampleWeight;
+ barrier();
}
+ if (index > 0)
+ return;
+
+ float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount);
+ vec3 inScatteredLuminance = sharedLuminance[0] * sampleWeight * atmosphereIsotropicPhase;
+ vec3 multiScatteringFactor = sharedMultiScatteringFactor[0] * sampleWeight;
+
vec3 clampedFactor = min(multiScatteringFactor, vec3(0.999));
vec3 multipleScattering = inScatteredLuminance / max(vec3(1.0) - clampedFactor, vec3(0.01));
diff --git a/data/shader/bloom/bloom.hsh b/data/shader/bloom/bloom.hsh
deleted file mode 100644
index e69de29bb..000000000
diff --git a/data/shader/bloom/bloomDownsample.csh b/data/shader/bloom/bloomDownsample.csh
index eb6b0a988..5b25a4f39 100644
--- a/data/shader/bloom/bloomDownsample.csh
+++ b/data/shader/bloom/bloomDownsample.csh
@@ -2,7 +2,6 @@ layout (local_size_x = 16, local_size_y = 16) in;
#include <../common/utility.hsh>
#include <../common/types.hsh>
-#include <../common/flatten.hsh>
layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D textureOut;
layout (set = 3, binding = 1) uniform sampler2D textureIn;
@@ -12,19 +11,6 @@ layout(push_constant) uniform constants {
float threshold;
} pushConstants;
-const uint supportSize = 2;
-const uint sharedDataSize = (2u * gl_WorkGroupSize.x + 2u * supportSize) * (2u * gl_WorkGroupSize.y + 2u * supportSize);
-const ivec2 unflattenedSharedDataSize = 2 * ivec2(gl_WorkGroupSize) + 2 * int(supportSize);
-
-shared vec3 sharedMemory[sharedDataSize];
-
-const ivec2 pixelOffsets[4] = ivec2[4](
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
AeF16 Luma(AeF16x3 color) {
const AeF16x3 luma = AeF16x3(0.299, 0.587, 0.114);
diff --git a/data/shader/bloom/bloomUpsample.csh b/data/shader/bloom/bloomUpsample.csh
index d533c1d9e..edd1f8c48 100644
--- a/data/shader/bloom/bloomUpsample.csh
+++ b/data/shader/bloom/bloomUpsample.csh
@@ -2,7 +2,8 @@
layout (local_size_x = 8, local_size_y = 8) in;
-layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D textureOut;
+// Holds the downsampled mip, the upsampled lower mip is added to it
+layout (set = 3, binding = 0, rgba16f) uniform image2D textureOut;
layout (set = 3, binding = 1) uniform sampler2D textureIn;
layout(push_constant) uniform constants {
@@ -27,10 +28,8 @@ void main() {
// Lower mip tex coord
vec2 texCoord = (coord + 0.5) / size;
- // Upper mip texel size
- vec2 texelSize = 1.0 / textureSize(textureIn, pushConstants.mipLevel);
- vec2 filterSize = vec2(pushConstants.filterSize);
- texelSize = max(filterSize, filterSize);
+ // Filter size in texture coordinates
+ vec2 texelSize = vec2(pushConstants.filterSize);
// We always sample at pixel border, not centers
AeF16x3 filter00 = Sample(texCoord + vec2(-texelSize.x, -texelSize.y));
@@ -53,7 +52,7 @@ void main() {
filtered /= AeF16(16.0);
if (pushConstants.additive > 0) {
- imageStore(textureOut, coord, vec4(filtered + filter11, 1.0));
+ imageStore(textureOut, coord, vec4(vec3(filtered) + imageLoad(textureOut, coord).rgb, 1.0));
}
else {
imageStore(textureOut, coord, vec4(filtered, 1.0));
diff --git a/data/shader/brdf/filterProbe.csh b/data/shader/brdf/filterProbe.csh
index 43a7153ec..3d6e2342e 100644
--- a/data/shader/brdf/filterProbe.csh
+++ b/data/shader/brdf/filterProbe.csh
@@ -35,8 +35,8 @@ vec3 CubeCoordToWorld(ivec3 cubeCoord, vec2 cubemapSize) {
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(filteredCubeMap).x ||
- pixel.y > imageSize(filteredCubeMap).y)
+ if (pixel.x >= imageSize(filteredCubeMap).x ||
+ pixel.y >= imageSize(filteredCubeMap).y)
return;
vec3 worldDirection = CubeCoordToWorld(ivec3(gl_GlobalInvocationID),
@@ -73,7 +73,7 @@ vec3 FilterDiffuse(vec3 worldDirection, ivec2 cubeMapSize) {
NdotL = saturate(NdotL);
if (NdotL > 0.0) {
- color.xyz += min(textureLod(cubeMap, L, 5.0).rgb, 5.0);
+ color.xyz += min(textureLod(cubeMap, L, 5.0).rgb * globalData.skyCubemapExposure, 5.0);
color.w += 1.0;
}
@@ -121,7 +121,7 @@ vec3 FilterSpecular(vec3 worldDirection, ivec2 cubeMapSize) {
lod = pushConstants.mipLevel == 0u ? 0.0 : lod;
- color.xyz += clamp(textureLod(cubeMap, L, lod).rgb, vec3(0.0), vec3(5.0)) * NdotL;
+ color.xyz += clamp(textureLod(cubeMap, L, lod).rgb * globalData.skyCubemapExposure, vec3(0.0), vec3(5.0)) * NdotL;
color.w += NdotL;
}
diff --git a/data/shader/clouds/clouds.hsh b/data/shader/clouds/clouds.hsh
index a9800249c..409c466bb 100644
--- a/data/shader/clouds/clouds.hsh
+++ b/data/shader/clouds/clouds.hsh
@@ -58,7 +58,7 @@ const float cloudTypeVariation = 0.55;
const float bottomTypeVariation = 0.12;
const float windSkew = 0.12;
-const float multiScatteringIntensity = 0.28;
+const float multiScatteringIntensity = 0.45;
const float multiScatteringAttenuation = 0.65;
const float multiScatteringContribution = 0.50;
const float multiScatteringEccentricityAttenuation = 0.60;
@@ -68,6 +68,15 @@ const float edgeAlbedo = 0.68;
const float edgeAlbedoCurve = 2.0;
const float ambientAlbedoMix = 0.35;
+// Cloud tops see the bright sky, bottoms are occluded by the cloud above and mostly see the ground
+const float ambientTopStrength = 0.6;
+const float ambientBottomStrength = 0.18;
+const float ambientGroundMix = 0.5;
+
+// Powder effect: surfaces which only received light close to the surface scatter less light back.
+// It darkens the creases of billowing clouds when the sun is behind the viewer.
+const float powderStrength = 0.65;
+
vec3 cloudPlanetCenter = cloudUniforms.planetCenter.xyz;
#define MULTISCATTER_OCTAVES 4
diff --git a/data/shader/clouds/integrate.csh b/data/shader/clouds/integrate.csh
index 355883aee..fdc57902d 100644
--- a/data/shader/clouds/integrate.csh
+++ b/data/shader/clouds/integrate.csh
@@ -27,8 +27,8 @@ vec4 ComputeVolumetricClouds(vec3 fragPos, float depth);
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(volumetricCloudImage).x ||
- pixel.y > imageSize(volumetricCloudImage).y)
+ if (pixel.x >= imageSize(volumetricCloudImage).x ||
+ pixel.y >= imageSize(volumetricCloudImage).y)
return;
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricCloudImage));
@@ -77,9 +77,7 @@ vec4 ComputeVolumetricClouds(vec3 fragPos, float depth) {
if (length(fragPos) < inDist && depth != 1.0)
return vec4(0.0, 0.0, 0.0, 1.0);
- float rayLength = cloudUniforms.distanceLimit;
- rayLength = outDist - inDist;
- rayLength = depth < 1.0 ? min(length(fragPos) - inDist, outDist - inDist) : outDist - inDist;
+ float rayLength = depth < 1.0 ? min(length(fragPos) - inDist, outDist - inDist) : outDist - inDist;
return IntegrateVolumetricClouds(globalData.cameraLocation.xyz, rayDirection, inDist,
rayLength, blueNoiseVec);
diff --git a/data/shader/clouds/integrate.hsh b/data/shader/clouds/integrate.hsh
index 12517fd0b..ea90967e7 100644
--- a/data/shader/clouds/integrate.hsh
+++ b/data/shader/clouds/integrate.hsh
@@ -27,24 +27,6 @@ void CalculateTexCoords(vec3 pos, out vec3 shapeTexCoords, out vec3 detailTexCoo
void CalculateRayLength(vec3 rayOrigin, vec3 rayDirection, out float minDist, out float maxDist) {
- /*
- // This is an option for the future to make the clouds wrap down at the distance limit into the horizon
- float radiusDiff = cloudUniforms.outerRadius - cloudUniforms.innerRadius;
-
- float outerRadius = cloudUniforms.distanceLimit;
- float innerRadius = cloudUniforms.distanceLimit - radiusDiff;
-
- float innerHeight = cloudUniforms.innerRadius - cloudUniforms.planetRadius;
-
- vec3 planetCenterDir = normalize(rayOrigin - cloudPlanetCenter);
- vec3 surfacePos = cloudPlanetCenter + planetCenterDir * cloudUniforms.planetRadius;
-
- vec3 spherePos = surfacePos - (innerRadius - innerHeight) * planetCenterDir;
- vec2 planetDist = IntersectSphere(rayOrigin, rayDirection, globalData.planetCenter.xyz, cloudUniforms.planetRadius);
- vec2 inDist = IntersectSphere(rayOrigin, rayDirection, spherePos, innerRadius);
- vec2 outDist = IntersectSphere(rayOrigin, rayDirection, spherePos, outerRadius);
- */
-
vec3 spherePos = cloudPlanetCenter;
vec2 planetDist = IntersectSphere(rayOrigin, rayDirection, cloudUniforms.planetCenter.xyz, cloudUniforms.planetRadius);
vec2 inDist = IntersectSphere(rayOrigin, rayDirection, spherePos, cloudUniforms.innerRadius);
@@ -136,11 +118,27 @@ vec3 ComputeAmbientColor(vec3 pos, float extinction) {
float distFromCenter = distance(pos, cloudPlanetCenter);
vec3 isotropicLightTop = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb;
+ vec3 isotropicLightBottom = textureLod(diffuseProbe, vec3(0.0, -1.0, 0.0), 0.0).rgb;
+
+ float heightFraction = saturate((distFromCenter - cloudUniforms.innerRadius) /
+ (cloudUniforms.outerRadius - cloudUniforms.innerRadius));
+
+ // The sky lights the tops, the bases only get light reflected from the ground below
+ vec3 topAmbient = ambientTopStrength * isotropicLightTop;
+ vec3 bottomAmbient = ambientBottomStrength * mix(isotropicLightTop, isotropicLightBottom, ambientGroundMix);
+ return mix(bottomAmbient, topAmbient, sqrt(heightFraction));
+
+}
+
+float ComputePowder(vec3 lightExtinction, float lightDotView) {
+
+ // Powder term 1 - exp(-2 * depth) with the optical depth -log(lightExtinction) towards the light
+ float extinctionToLight = dot(lightExtinction, vec3(0.3333));
+ float powder = 1.0 - extinctionToLight * extinctionToLight;
- float heightFraction = (distFromCenter - cloudUniforms.innerRadius) /
- (cloudUniforms.outerRadius - cloudUniforms.innerRadius);
- float ambientContribution = saturate(0.5);
- return 0.5 * isotropicLightTop * ambientContribution;
+ // Only applied when looking away from the sun, forward scattering is unaffected
+ float viewWeight = saturate(0.5 - lightDotView * 0.5);
+ return mix(1.0, mix(1.0 - powderStrength, 1.0, powder), viewWeight);
}
@@ -245,7 +243,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart
vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001);
vec4 stepExtinction = exp(-extinctionCoefficient * smallStepLength);
- float lightDotView = dot(cloudUniforms.light.direction.xyz, rayDirection);
+ // Cosine between the view ray and the direction to the sun, positive eccentricities scatter forward
+ float lightDotView = dot(-cloudUniforms.light.direction.xyz, rayDirection);
vec3 lightColor = cloudUniforms.light.color.rgb * cloudUniforms.light.intensity;
vec4 lightExtinction = GetExtinctionToLight(rayPos, i % 4, noiseVector);
@@ -253,7 +252,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart
cloudUniforms.eccentricitySecondPhase, cloudUniforms.phaseAlpha, lightDotView);
vec3 multipleScattering = ApproximateMultipleScattering(lightExtinction.rgb,
lightDotView);
- vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb;
+ vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb *
+ ComputePowder(lightExtinction.rgb, lightDotView);
vec3 multiScatterLighting = directAlbedo * multiScatteringIntensity *
lightColor * multipleScattering;
vec3 ambientLighting = ambientAlbedo * ComputeAmbientColor(rayPos, extinction.a);
diff --git a/data/shader/clouds/shadow.csh b/data/shader/clouds/shadow.csh
index 834cc876b..02d8e025e 100644
--- a/data/shader/clouds/shadow.csh
+++ b/data/shader/clouds/shadow.csh
@@ -27,8 +27,8 @@ vec2 ComputeVolumetricClouds(vec3 minDepthPos, vec3 maxDepthPos);
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(volumetricCloudShadowImage).x ||
- pixel.y > imageSize(volumetricCloudShadowImage).y)
+ if (pixel.x >= imageSize(volumetricCloudShadowImage).x ||
+ pixel.y >= imageSize(volumetricCloudShadowImage).y)
return;
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricCloudShadowImage));
diff --git a/data/shader/clouds/temporal.csh b/data/shader/clouds/temporal.csh
index a9c518928..bd105013d 100644
--- a/data/shader/clouds/temporal.csh
+++ b/data/shader/clouds/temporal.csh
@@ -277,8 +277,8 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
vec4 localNeighbourhoodMin, localNeighbourhoodMax;
@@ -302,7 +302,7 @@ void main() {
history = success && valid ? catmullRomHistory : history;
}
- vec4 historyValue = history;
+ vec4 historyValue = vec4(history.rgb * globalData.preExposure / globalData.lastPreExposure, history.a);
vec4 currentValue = texelFetch(currentTexture, pixel, 0);
float currentDepth = texelFetch(depthTexture, pixel, 0).r;
diff --git a/data/shader/common/denoiser.hsh b/data/shader/common/denoiser.hsh
new file mode 100644
index 000000000..58bc2ed4a
--- /dev/null
+++ b/data/shader/common/denoiser.hsh
@@ -0,0 +1,123 @@
+#include <../globals.hsh>
+#include
+#include
+
+// Hit distances are stored as h / (h + 1 m): bounded with misses as one and independent of the camera
+float EncodeHitDistance(float hitDistance) {
+
+ return hitDistance / (hitDistance + 1.0);
+
+}
+
+float DecodeHitDistance(float encodedHitDistance) {
+
+ return encodedHitDistance / max(1.0 - encodedHitDistance, 1e-3);
+
+}
+
+// The motion of the surface itself in pixels, without the part that the camera causes
+vec2 GetObjectMotion(sampler2D velocityTexture, ivec2 texel, float depth, vec2 resolution) {
+
+ vec2 texCoord = (vec2(texel) + 0.5) / resolution;
+ vec4 lastPosition = globalData.pvMatrixLast * vec4(ConvertDepth(depth, texCoord, globalData.ipvMatrixCurrent), 1.0);
+ vec2 cameraVelocity = (lastPosition.xy / lastPosition.w * 0.5 + 0.5) - texCoord;
+ return depth < 1.0 ? (texelFetch(velocityTexture, texel, 0).rg - cameraVelocity) * resolution : vec2(0.0);
+
+}
+
+// Squared motion of a neighbor relative to the center, only neighbors around the same depth count
+float GetNearbyMotionSquared(vec2 sampleMotion, vec2 centerMotion, float linearDepth, float sampleLinearDepth) {
+
+ if (abs(linearDepth - sampleLinearDepth) >= 0.5 + 0.1 * abs(linearDepth))
+ return 0.0;
+
+ vec2 relativeMotion = sampleMotion - centerMotion;
+ return dot(relativeMotion, relativeMotion);
+
+}
+
+// Moving neighbors change what the rays see without the reprojection noticing, below half a pixel it's swaying vegetation
+float LimitHistoryByNearbyMotion(float historyLength, float nearbyMotion) {
+
+ return mix(historyLength, min(historyLength, 4.0), saturate((nearbyMotion - 0.5) / 2.0));
+
+}
+
+bool IsOffscreen(vec2 uv) {
+
+ return uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0;
+
+}
+
+// Catmull-Rom with five bilinear taps, the corners of the 4x4 footprint are left out
+vec4 SampleCatmullRom(sampler2D historyTexture, vec2 uv, vec2 resolution) {
+
+ vec2 invResolution = 1.0 / resolution;
+ vec2 samplePixel = uv * resolution;
+
+ vec2 center = floor(samplePixel - 0.5) + 0.5;
+ vec2 f = samplePixel - center;
+
+ vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
+ vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
+ vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));
+ vec2 w3 = f * f * (-0.5 + 0.5 * f);
+
+ vec2 w12 = w1 + w2;
+ vec2 uv0 = (center - 1.0) * invResolution;
+ vec2 uv12 = (center + w2 / w12) * invResolution;
+ vec2 uv3 = (center + 2.0) * invResolution;
+
+ vec4 history = textureLod(historyTexture, vec2(uv12.x, uv0.y), 0.0) * (w12.x * w0.y)
+ + textureLod(historyTexture, vec2(uv0.x, uv12.y), 0.0) * (w0.x * w12.y)
+ + textureLod(historyTexture, uv12, 0.0) * (w12.x * w12.y)
+ + textureLod(historyTexture, vec2(uv3.x, uv12.y), 0.0) * (w3.x * w12.y)
+ + textureLod(historyTexture, vec2(uv12.x, uv3.y), 0.0) * (w12.x * w3.y);
+ float totalWeight = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
+
+ return history / totalWeight;
+
+}
+
+// Effective number of accumulated frames, blending reduces the noise variance to (1 - factor)^2 + factor^2 / historyLength
+float GetAccumulatedFrames(float factor, float historyLength) {
+
+ return 1.0 / (sqr(1.0 - factor) + sqr(factor) / max(historyLength, 1e-6));
+
+}
+
+// View space direction through a pixel with a view space depth of one, it is affine in the texture coordinates
+vec3 GetViewRay(vec2 texCoord) {
+
+ vec3 position = ConvertDepthToViewSpace(0.5, texCoord);
+ return position / position.z;
+
+}
+
+float Luma(vec3 color) {
+
+ const vec3 luma = vec3(0.299, 0.587, 0.114);
+ return dot(color, luma);
+
+}
+
+// The distance along the line from the history to the current color where it leaves the box
+float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) {
+
+ vec3 origin = history;
+ vec3 dir = current - history;
+
+ // Make sure dir isn't zero
+ dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x;
+ dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y;
+ dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z;
+
+ vec3 invDir = 1.0 / dir;
+
+ vec3 t0 = (boxMin - origin) * invDir;
+ vec3 t1 = (boxMax - origin) * invDir;
+
+ vec3 intersect = min(t0, t1);
+ return max(intersect.x, max(intersect.y, intersect.z));
+
+}
diff --git a/data/shader/common/light.hsh b/data/shader/common/light.hsh
index 886cf6d4d..a3ac44e9b 100644
--- a/data/shader/common/light.hsh
+++ b/data/shader/common/light.hsh
@@ -4,10 +4,4 @@ float GetDistanceAttenuation(float dist, float radius) {
return saturate(1.0 - pow(dist / radius, 4.0)) / (dist * dist);
-}
-
-float GetAngleAttenuation() {
-
-
-
}
\ No newline at end of file
diff --git a/data/shader/common/material.hsh b/data/shader/common/material.hsh
index 3c864e1a1..71363570f 100644
--- a/data/shader/common/material.hsh
+++ b/data/shader/common/material.hsh
@@ -42,8 +42,19 @@ struct Material {
bool transmissive;
bool vertexColors;
bool terrain;
+
+ // Only set for the hits of rays
+ uint blendMode;
+ // Of the side the ray enters relative to the one it comes from
+ float refractiveIndex;
};
+// Has to match MaterialBlendMode
+const uint blendModeNone = 0u;
+const uint blendModeAlpha = 1u;
+const uint blendModeAdditive = 2u;
+const uint blendModeMultiply = 3u;
+
struct PackedMaterial {
vec4 data0;
vec4 data1;
diff --git a/data/shader/common/opacity.hsh b/data/shader/common/opacity.hsh
new file mode 100644
index 000000000..387c775c8
--- /dev/null
+++ b/data/shader/common/opacity.hsh
@@ -0,0 +1,2 @@
+// Surfaces with a lower opacity are cut out, the same in all passes
+const float opacityCutoff = 0.2;
diff --git a/data/shader/common/rotation.hsh b/data/shader/common/rotation.hsh
new file mode 100644
index 000000000..1c3739cef
--- /dev/null
+++ b/data/shader/common/rotation.hsh
@@ -0,0 +1,11 @@
+// Rotates v like the rotation which turns the unit vector from into the unit vector to
+vec3 RotateLike(vec3 v, vec3 from, vec3 to) {
+
+ vec3 axis = cross(from, to);
+ float cosine = dot(from, to);
+ // Opposite vectors have no shortest rotation, the mirror image works for vectors orthogonal to them
+ if (cosine < -0.999)
+ return v - 2.0 * dot(v, from) * from;
+ return v * cosine + cross(axis, v) + axis * (dot(axis, v) / (1.0 + cosine));
+
+}
\ No newline at end of file
diff --git a/data/shader/common/stencil.hsh b/data/shader/common/stencil.hsh
index 2b27900a2..a01ba14f0 100644
--- a/data/shader/common/stencil.hsh
+++ b/data/shader/common/stencil.hsh
@@ -2,6 +2,7 @@ struct StencilFeatures {
bool responsivePixel;
bool waterPixel;
bool underWaterPixel;
+ bool noTemporalAccumulation;
};
StencilFeatures CreateStencilFeatures() {
@@ -11,6 +12,7 @@ StencilFeatures CreateStencilFeatures() {
features.responsivePixel = false;
features.waterPixel = false;
features.underWaterPixel = false;
+ features.noTemporalAccumulation = false;
return features;
@@ -21,12 +23,14 @@ uint EncodeStencilFeatures(StencilFeatures features) {
const uint responsivePixel = (1 << 0);
const uint waterPixel = (1 << 1);
const uint underWaterPixel = (1 << 2);
+ const uint noTemporalAccumulation = (1 << 3);
uint data = 0u;
data |= features.responsivePixel ? responsivePixel : 0u;
data |= features.waterPixel ? waterPixel : 0u;
data |= features.underWaterPixel ? underWaterPixel : 0u;
+ data |= features.noTemporalAccumulation ? noTemporalAccumulation : 0u;
return data;
@@ -37,12 +41,14 @@ StencilFeatures DecodeStencilFeatures(uint data) {
const uint responsivePixel = (1 << 0);
const uint waterPixel = (1 << 1);
const uint underWaterPixel = (1 << 2);
+ const uint noTemporalAccumulation = (1 << 3);
StencilFeatures features;
features.responsivePixel = (data & responsivePixel) > 0u;
features.waterPixel = (data & waterPixel) > 0u;
features.underWaterPixel = (data & underWaterPixel) > 0u;
+ features.noTemporalAccumulation = (data & noTemporalAccumulation) > 0u;
return features;
diff --git a/data/shader/common/texCoord.hsh b/data/shader/common/texCoord.hsh
new file mode 100644
index 000000000..2577c9593
--- /dev/null
+++ b/data/shader/common/texCoord.hsh
@@ -0,0 +1,9 @@
+#include <../globals.hsh>
+
+// Texture coordinates of a mesh as all passes use them: flipped for meshes with inverted UVs, animated and tiled by the material
+vec2 TransformTexCoord(vec2 texCoord, bool invertUVs, vec2 uvAnimation, float uvTiling) {
+
+ texCoord = invertUVs ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord;
+ return (texCoord + uvAnimation * globalData.time) * uvTiling;
+
+}
diff --git a/data/shader/common/traceScreenSpace.hsh b/data/shader/common/traceScreenSpace.hsh
index ea2979952..5e43cf1b4 100644
--- a/data/shader/common/traceScreenSpace.hsh
+++ b/data/shader/common/traceScreenSpace.hsh
@@ -11,282 +11,79 @@
#define point2 vec2
#define point3 vec3
-float distanceSquared(vec2 a, vec2 b) { a -= b; return dot(a, a); }
+// Returns true if the ray hit something, the hierarchical depth buffer is generated by the HiZRenderer
+bool traceScreenSpaceHiZ(point3 csOrig, vec3 csDir, sampler2D hiZTexture, int hiZLevelCount, vec2 depthBufferSize,
+ int maxIterations, float maxDistance, bool stopBehindGeometry, out point2 hitPixel, out point3 hitPoint) {
-bool intersectsDepthBuffer(float z, float minZ, float maxZ, float thickness, float strideCutoff) {
- /*
- * Based on how far away from the camera the depth is,
- * adding a bit of extra thickness can help improve some
- * artifacts. Driving this value up too high can cause
- * artifacts of its own.
- */
- float depthScale = min(1.0, -z * strideCutoff);
- thickness *= mix(0.0, 4.0, depthScale);
- return (maxZ >= z - thickness) && (minZ < z);
-}
-
-bool validPixel(vec2 hitPixel, vec2 resolution) {
-
- return hitPixel.x >= 0 && hitPixel.y >= 0 && hitPixel.x < resolution.x && hitPixel.y < resolution.y;
-
-}
-
-// Returns true if the ray hit something
-bool traceScreenSpace(
- // Camera-space ray origin, which must be within the view volume
- point3 csOrig,
-
- // Unit length camera-space ray direction
- vec3 csDir,
-
- // The camera-space Z buffer (all negative values)
- sampler2D csZBuffer,
-
- // Camera space thickness to ascribe to each pixel in the depth buffer
- float zThickness,
-
- // Step in horizontal or vertical pixels between samples. This is a float
- // because integer math is slow on GPUs, but should be set to an integer >= 1
- float stride,
-
- // Number between 0 and 1 for how far to bump the ray in stride units
- // to conceal banding artifacts
- float jitter,
-
- // Maximum number of iterations. Higher gives better images but may be slow
- const float maxSteps,
-
- // Maximum camera-space distance to trace before returning a miss
- float maxDistance,
-
- bool stopBehindGeometry,
-
- // Pixel coordinates of the first intersection with the scene
- out point2 hitPixel,
-
- // Camera space location of the ray hit
- out point3 hitPoint,
-
- out point3 minPoint,
-
- out point3 maxPoint) {
-
- mat4 ipMatrix = globalData.ipMatrix;
+ hitPixel = vec2(0.0);
+ hitPoint = vec3(0.0);
- // Clip to the near plane
+ // Clip to the near plane
float rayLength = ((csOrig.z + csDir.z * maxDistance) > -globalData.cameraNearPlane) ?
(-globalData.cameraNearPlane - csOrig.z) / csDir.z : maxDistance;
point3 csEndPoint = csOrig + csDir * rayLength;
- vec2 csZBufferSize = vec2(textureSize(csZBuffer, 0));
-
- // Project into homogeneous clip space
vec4 H0 = globalData.pMatrix * vec4(csOrig, 1.0);
vec4 H1 = globalData.pMatrix * vec4(csEndPoint, 1.0);
- float k0 = 1.0 / H0.w, k1 = 1.0 / H1.w;
-
- // The interpolated homogeneous version of the camera-space points
- point3 Q0 = csOrig * k0;
- point3 Q1 = csEndPoint * k1;
-
- // Screen-space endpoints
- point2 P0 = (H0.xy * k0) * 0.5 + 0.5;
- point2 P1 = 0.5 * (H1.xy * k1) + 0.5;
- P0 *= csZBufferSize;
- P1 *= csZBufferSize;
-
- // If the line is degenerate, make it cover at least one pixel
- // to avoid handling zero-pixel extent as a special case later
- P1 += vec2((distanceSquared(P0, P1) < 0.0001) ? 0.01 : 0.0);
- vec2 delta = P1 - P0;
+ vec3 S0 = vec3((H0.xy / H0.w * 0.5 + 0.5) * depthBufferSize, H0.z / H0.w);
+ vec3 S1 = vec3((H1.xy / H1.w * 0.5 + 0.5) * depthBufferSize, H1.z / H1.w);
+ vec3 D = S1 - S0;
- // Permute so that the primary iteration is in x to collapse
- // all quadrant-specific DDA cases later
- bool permute = false;
- if (abs(delta.x) < abs(delta.y)) {
- // This is a more-vertical line
- permute = true; delta = delta.yx; P0 = P0.yx; P1 = P1.yx;
- }
-
- float stepDir = sign(delta.x);
- float invdx = stepDir / delta.x;
+ vec2 safeD = mix(D.xy, vec2(1e-12), lessThan(abs(D.xy), vec2(1e-12)));
+ vec2 invD = 1.0 / safeD;
- // Track the derivatives of Q and k
- vec3 dQ = (Q1 - Q0) * invdx;
- float dk = (k1 - k0) * invdx;
- vec2 dP = vec2(stepDir, delta.y * invdx);
+ vec2 tBorder = (mix(vec2(0.0), depthBufferSize, greaterThan(D.xy, vec2(0.0))) - S0.xy) * invD;
+ float tEnd = min(1.0, min(tBorder.x, tBorder.y));
- // Scale derivatives by the desired pixel stride and then
- // offset the starting values by the jitter fraction
+ float pixelLength = max(abs(D.x), abs(D.y));
+ float tEpsilon = 0.01 / max(pixelLength, 1.0);
- const float strideOffset = 0.002;
- float strideScale = 1.0 - min(1.0, abs(csOrig.z) * strideOffset);
- stride = 1.0 + strideScale * stride;
+ vec2 stepDirection = vec2(greaterThan(D.xy, vec2(0.0)));
- P0 += dP;
- Q0 += dQ;
- k0 += dk;
+ // Skipping more than the origin pixel might miss surfaces next to the origin
+ vec2 tOriginExit = ((floor(S0.xy) + stepDirection) - S0.xy) * invD;
+ float t = min(min(tOriginExit.x, tOriginExit.y) + tEpsilon, 1.0);
- dP *= stride;
- dQ *= stride;
- dk *= stride;
+ int level = 0;
+ for (int i = 0; i < maxIterations && t < tEnd; i++) {
+ point2 P = S0.xy + D.xy * t;
+ float cellSize = float(1 << level);
+ vec2 cell = floor(P / cellSize);
+ vec2 minMaxDepth = texelFetch(hiZTexture, ivec2(cell), level).rg;
- P0 += dP * jitter;
- Q0 += dQ * jitter;
- k0 += dk * jitter;
+ vec2 tBoundary = ((cell + stepDirection) * cellSize - S0.xy) * invD;
+ float tExit = min(min(tBoundary.x, tBoundary.y), tEnd);
+ float rayDepth0 = S0.z + D.z * t;
+ float rayDepth1 = S0.z + D.z * tExit;
+ float rayDepthMin = min(rayDepth0, rayDepth1);
+ float rayDepthMax = max(rayDepth0, rayDepth1);
- // Slide P from P0 to P1, (now-homogeneous) Q from Q0 to Q1, k from k0 to k1
- point3 Q = Q0;
+ bool inFront = rayDepthMax < minMaxDepth.x;
+ bool behind = rayDepthMin > minMaxDepth.y;
- // Adjust end condition for iteration direction
- float end = P1.x * stepDir;
+ if (stopBehindGeometry && behind)
+ return false;
- float k = k0, stepCount = 0.0, prevZMaxEstimate = csOrig.z;
- float rayZMin = prevZMaxEstimate, rayZMax = prevZMaxEstimate;
- float sceneZMax = rayZMax + maxDistance;
- float sceneDepthMax = 0.0;
- point2 P = P0;
- for (;
- ((P.x * stepDir) <= end) && (stepCount < maxSteps) &&
- !intersectsDepthBuffer(sceneZMax, rayZMin, rayZMax, zThickness, strideOffset) &&
- (sceneZMax != 0);
- P += dP, Q.z += dQ.z, k += dk, ++stepCount) {
-
- rayZMin = prevZMaxEstimate;
- rayZMax = (dQ.z * 0.5 + Q.z) / (dk * 0.5 + k);
- prevZMaxEstimate = rayZMax;
- if (rayZMin > rayZMax) {
- float t = rayZMin; rayZMin = rayZMax; rayZMax = t;
+ if (inFront || behind) {
+ t = tExit + tEpsilon;
+ level = min(level + 1, hiZLevelCount - 1);
+ }
+ else if (level > 0) {
+ level--;
+ }
+ else {
+ if (minMaxDepth.x >= 1.0) {
+ t = tExit + tEpsilon;
+ continue;
+ }
+
+ hitPixel = cell;
+ vec2 texCoord = (cell + 0.5) / depthBufferSize;
+ hitPoint = ConvertDepthToViewSpace(rayDepth0, texCoord);
+ return true;
}
-
- hitPixel = permute ? P.yx : P;
- // You may need hitPixel.y = csZBufferSize.y - hitPixel.y; here if your vertical axis
- // is different than ours in screen space
- sceneDepthMax = texelFetch(csZBuffer, ivec2(hitPixel), 0).r;
- sceneZMax = ConvertDepthToViewSpaceDepth(sceneDepthMax, ipMatrix);
-
- // If we have a raytracing fallback we want to reject rays that go behind the depth buffer in
- // certain phases in the screen space trace.
- if (stopBehindGeometry && sceneZMax > rayZMax)
- return false;
}
- minPoint = Q0 + dQ * (stepCount - 2.0);
- maxPoint = Q0 + dQ * (stepCount - 1.0);
+ return false;
- minPoint /= (k - 2.0 * dk);
- maxPoint /= (k - 1.0 * dk);
-
- // Advance Q based on the number of steps
- Q.xy += dQ.xy * stepCount;
- hitPoint = Q * (1.0 / k);
-
- return (intersectsDepthBuffer(sceneZMax, rayZMin, rayZMax, zThickness, strideOffset))
- && validPixel(hitPixel, csZBufferSize) && sceneDepthMax < 1.0;
}
-
-bool traceScreenSpace(
- // Camera-space ray origin, which must be within the view volume
- point3 csOrig,
-
- // Unit length camera-space ray direction
- vec3 csDir,
-
- // The camera-space Z buffer (all negative values)
- sampler2D csZBuffer,
-
- // Camera space thickness to ascribe to each pixel in the depth buffer
- float zThickness,
-
- // Step in horizontal or vertical pixels between samples. This is a float
- // because integer math is slow on GPUs, but should be set to an integer >= 1
- float stride,
-
- // Number between 0 and 1 for how far to bump the ray in stride units
- // to conceal banding artifacts
- float jitter,
-
- // Maximum number of iterations. Higher gives better images but may be slow
- const float maxSteps,
-
- // Maximum camera-space distance to trace before returning a miss
- float maxDistance,
-
- // Pixel coordinates of the first intersection with the scene
- out point2 hitPixel,
-
- // Camera space location of the ray hit
- out point3 hitPoint) {
-
- point3 minPoint, maxPoint;
- return traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, false, hitPixel, hitPoint, minPoint, maxPoint);
-
-}
-
-bool traceScreenSpaceAdvanced(
- // Camera-space ray origin, which must be within the view volume
- point3 csOrig,
-
- // Unit length camera-space ray direction
- vec3 csDir,
-
- // The camera-space Z buffer (all negative values)
- sampler2D csZBuffer,
-
- // Camera space thickness to ascribe to each pixel in the depth buffer
- float zThickness,
-
- // Step in horizontal or vertical pixels between samples. This is a float
- // because integer math is slow on GPUs, but should be set to an integer >= 1
- float stride,
-
- // Number between 0 and 1 for how far to bump the ray in stride units
- // to conceal banding artifacts
- float jitter,
-
- // Maximum number of iterations. Higher gives better images but may be slow
- float maxSteps,
-
- // Maximum camera-space distance to trace before returning a miss
- float maxDistance,
-
- bool allowFallback,
-
- bool stopBehindGeometry,
-
- // Pixel coordinates of the first intersection with the scene
- out point2 hitPixel,
-
- // Camera space location of the ray hit
- out point3 hitPoint) {
-
- bool hit = false;
-
- point3 minPoint, maxPoint;
- if(traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, stopBehindGeometry, hitPixel, hitPoint, minPoint, maxPoint)) {
- hit = true;
- }
-
- if (!hit && !allowFallback)
- return false;
-
- hit = false;
- // maxSteps /= 2.0;
-
- csOrig = minPoint;
- csDir = normalize(maxPoint - minPoint);
- stride = max(1.0, stride / maxSteps);
- //zThickness /= (1.0 * maxSteps);
- //maxDistance = min(maxDistance, 20.0 * distance(maxPoint, minPoint));
-
- vec2 newHitPixel;
- vec3 newHitPoint;
- if (traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, false, newHitPixel, newHitPoint, minPoint, maxPoint)) {
- hitPixel = newHitPixel;
- hitPoint = newHitPoint;
- hit = true;
- }
-
- return hit;
-
-}
\ No newline at end of file
diff --git a/data/shader/common/upsample.hsh b/data/shader/common/upsample.hsh
new file mode 100644
index 000000000..dc3fae9c1
--- /dev/null
+++ b/data/shader/common/upsample.hsh
@@ -0,0 +1,55 @@
+#include
+
+// Upsampling of half resolution data: a work group loads the low resolution texels it covers into shared memory,
+// with a border of one texel
+const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2);
+const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2;
+
+// The low resolution texel the invocation loads, invocations beyond the tile return false
+bool GetUpsampleTileTexel(ivec2 lowResSize, out ivec2 texel) {
+
+ texel = ivec2(0);
+ if (gl_LocalInvocationIndex >= depthDataSize)
+ return false;
+
+ ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1);
+ texel = clamp(Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize) + workGroupOffset,
+ ivec2(0), lowResSize - 1);
+ return true;
+
+}
+
+const ivec2 offsets[9] = ivec2[9](
+ ivec2(-1, -1),
+ ivec2(0, -1),
+ ivec2(1, -1),
+ ivec2(-1, 0),
+ ivec2(0, 0),
+ ivec2(1, 0),
+ ivec2(-1, 1),
+ ivec2(0, 1),
+ ivec2(1, 1)
+);
+
+const ivec2 pixelOffsets[4] = ivec2[4](
+ ivec2(0, 0),
+ ivec2(1, 0),
+ ivec2(0, 1),
+ ivec2(1, 1)
+);
+
+// The index of the depth closest to the reference, the center wins ties
+int NearestDepth(float referenceDepth, float[9] depthVec) {
+
+ int idx = 4;
+ float nearest = distance(referenceDepth, depthVec[4]);
+ for (int i = 0; i < 9; i++) {
+ float dist = distance(referenceDepth, depthVec[i]);
+ if (dist < nearest) {
+ nearest = dist;
+ idx = i;
+ }
+ }
+ return idx;
+
+}
diff --git a/data/shader/common/utility.hsh b/data/shader/common/utility.hsh
index 5594ccf52..05b635280 100644
--- a/data/shader/common/utility.hsh
+++ b/data/shader/common/utility.hsh
@@ -130,6 +130,15 @@ float min4(vec4 value) {
}
+// 1 inside the screen, going to 0 at its edges over the fade distance in normalized device coordinates
+float EdgeFadeOut(vec2 screenPos, float fadeDist) {
+
+ screenPos = abs(screenPos * 2.0 - 1.0);
+ vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist;
+ return saturate(1.0 - max(fadeOut.x, fadeOut.y));
+
+}
+
vec3 Cartesian(vec2 spherical) {
float sinTheta = sin(spherical.x);
return normalize(vec3(
diff --git a/data/shader/culling/common.hsh b/data/shader/culling/common.hsh
new file mode 100644
index 000000000..b72d9edbf
--- /dev/null
+++ b/data/shader/culling/common.hsh
@@ -0,0 +1,97 @@
+// Has to match the structures in scene/GPUScene.h
+
+#define INSTANCE_VISIBLE 1u
+#define INSTANCE_DONT_CULL 2u
+#define INSTANCE_REVERSED_WINDING 4u
+
+#define INVALID_HISTORY_IDX 0xFFFFFFFFu
+
+#define MESH_DRAWABLE 1u
+#define MESH_CAST_SHADOW 2u
+#define MESH_IMPOSTOR 4u
+#define MESH_GEOMETRY 8u
+#define MESH_DRAW_EARLY 16u
+
+// Has to match MeshData::maxLodCount
+#define MAX_LOD_COUNT 5u
+
+#define DRAW_DEFAULT_WINDING 0u
+#define DRAW_REVERSED_WINDING 1u
+#define DRAW_IMPOSTOR 2u
+
+// Each view has a counter per winding and level of detail of a mesh, the one of the impostors comes after them
+#define IMPOSTOR_COUNTER (2u * MAX_LOD_COUNT)
+#define MESH_COUNTER_COUNT (2u * MAX_LOD_COUNT + 1u)
+
+// The culling result of an instance has a bit per view below its level of detail, GPUScene::maxCullViewCount views
+#define RESULT_LOD_SHIFT 24u
+
+struct Instance {
+ // Rows of the global matrix
+ mat3x4 matrix;
+ uint meshIdx;
+ uint flags;
+ uint historyIdx;
+ // Whether the main view saw the instance in its last occlusion test
+ uint visibleLastFrame;
+};
+
+struct CullMesh {
+ // The w components are the distance culling of the main and the shadow passes
+ vec4 aabbMin;
+ vec4 aabbMax;
+ float impostorDistance;
+ float impostorShadowDistance;
+ uint flags;
+ // Instances with a smaller bounding sphere in pixels are culled
+ float minScreenSize;
+ // The region of the indices of the mesh in each view, shared by its levels of detail, windings and impostors
+ uint regionOffset;
+ uint regionCapacity;
+ uint padding0;
+ uint lodCount;
+ // Errors of the levels from 1 on divided by their pixel error, an instance uses a level while the error times its
+ // scale and the focal length stays below its distance
+ vec4 lodErrors;
+};
+
+uint SelectLod(CullMesh mesh, float distance, float scale, float focalLength) {
+
+ uint lod = 0u;
+ float projection = scale * focalLength;
+ for (uint i = 1u; i < mesh.lodCount; i++) {
+ if (mesh.lodErrors[i - 1u] * projection > distance)
+ break;
+ lod = i;
+ }
+ return lod;
+
+}
+
+float GetMaxScale(mat3x4 matrix) {
+
+ return max(length(vec3(matrix[0].x, matrix[1].x, matrix[2].x)),
+ max(length(vec3(matrix[0].y, matrix[1].y, matrix[2].y)), length(vec3(matrix[0].z, matrix[1].z, matrix[2].z))));
+
+}
+
+struct CullView {
+ vec4 planes[6];
+ uint shadow;
+ uint indexOffset;
+ uint padding0;
+ uint counterOffset;
+};
+
+// The counter of the draw an instance is part of in a view
+uint GetDrawCounter(bool impostor, uint lod, bool reversedWinding) {
+
+ return impostor ? IMPOSTOR_COUNTER : 2u * lod + (reversedWinding ? DRAW_REVERSED_WINDING : DRAW_DEFAULT_WINDING);
+
+}
+
+vec3 GetInstancePosition(mat3x4 matrix) {
+
+ return vec3(matrix[0].w, matrix[1].w, matrix[2].w);
+
+}
diff --git a/data/shader/culling/cull.csh b/data/shader/culling/cull.csh
new file mode 100644
index 000000000..5915d716d
--- /dev/null
+++ b/data/shader/culling/cull.csh
@@ -0,0 +1,299 @@
+#include
+
+// Counts the visible instances of all views per draw and keeps in which views an instance is visible,
+// culling/indices.csh writes the indices once the counts are turned into offsets
+// The main view draws the instances visible in the last frame first, OCCLUSION then tests the others against that
+// depth, counts them in their own view and remembers the visibility for the next frame
+
+#ifdef OCCLUSION
+#include <../globals.hsh>
+#endif
+
+layout (local_size_x = 64) in;
+
+#ifdef OCCLUSION
+layout(std430, set = 3, binding = 0) buffer Instances {
+#else
+layout(std430, set = 3, binding = 0) readonly buffer Instances {
+#endif
+ Instance instances[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer Meshes {
+ CullMesh meshes[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer Views {
+ CullView views[];
+};
+
+layout(std430, set = 3, binding = 3) buffer Counters {
+ uint counters[];
+};
+
+#ifndef RAY_TRACING_INSTANCES
+// Per instance the views it is visible in (x) and drawn as an impostor in (y), with its level of detail in the high bits of y
+layout(std430, set = 3, binding = 4) buffer Results {
+ uvec2 results[];
+};
+#endif
+
+layout(push_constant) uniform constants {
+ vec4 cameraLocation;
+ uint instanceCount;
+ uint viewCount;
+ uint maxRayTracingInstanceCount;
+ uint includeObjectHistory;
+ // Viewport height in pixels divided by 2 * tan(fov / 2)
+ float focalLength;
+ // This view only gets the instances which were visible in the last frame
+ uint occlusionView;
+ uint firstView;
+ uint padding0;
+ ivec2 depthResolution;
+ int hiZLevelCount;
+ uint padding1;
+} PushConstants;
+
+#ifndef RAY_TRACING_INSTANCES
+// The instances of the occluded view within its frustum, starts with the indirect dispatch of the occlusion test
+layout(std430, set = 3, binding = 14) buffer OcclusionInstances {
+ uint occlusionGroupCountX;
+ uint occlusionGroupCountY;
+ uint occlusionGroupCountZ;
+ uint occlusionInstanceCount;
+ uint occlusionInstances[];
+};
+#endif
+
+#ifdef OCCLUSION
+// Hierarchical depth with the farthest depth in g
+layout(set = 3, binding = 13) uniform sampler2D hiZTexture;
+
+bool IsOccluded(vec3 aabbMin, vec3 aabbMax) {
+
+ vec2 ndcMin = vec2(1.0);
+ vec2 ndcMax = vec2(-1.0);
+ float closestDepth = 1.0;
+
+ for (int i = 0; i < 8; i++) {
+ vec3 corner = vec3((i & 1) != 0 ? aabbMax.x : aabbMin.x, (i & 2) != 0 ? aabbMax.y : aabbMin.y,
+ (i & 4) != 0 ? aabbMax.z : aabbMin.z);
+ vec4 clip = globalData.pvMatrixCurrent * vec4(corner, 1.0);
+ // Bounds crossing the near plane can't be projected
+ if (clip.w <= 0.0 || clip.z <= 0.0)
+ return false;
+
+ vec3 ndc = clip.xyz / clip.w;
+ ndcMin = min(ndcMin, ndc.xy);
+ ndcMax = max(ndcMax, ndc.xy);
+ closestDepth = min(closestDepth, ndc.z);
+ }
+
+ // One pixel more, the pixels at the border of the bounds are only partly covered
+ ivec2 maxPixel = PushConstants.depthResolution - 1;
+ ivec2 pixelMin = clamp(ivec2((ndcMin * 0.5 + 0.5) * vec2(PushConstants.depthResolution)) - 1, ivec2(0), maxPixel);
+ ivec2 pixelMax = clamp(ivec2((ndcMax * 0.5 + 0.5) * vec2(PushConstants.depthResolution)) + 1, ivec2(0), maxPixel);
+
+ // The bounds cover at most three texels per axis in this level
+ ivec2 size = pixelMax - pixelMin;
+ int level = findMSB(max(max(size.x, size.y), 1));
+ if (level >= PushConstants.hiZLevelCount)
+ return false;
+
+ ivec2 texelMin = pixelMin >> level;
+ ivec2 texelMax = pixelMax >> level;
+ for (int y = texelMin.y; y <= texelMax.y; y++) {
+ for (int x = texelMin.x; x <= texelMax.x; x++) {
+ if (closestDepth <= texelFetch(hiZTexture, ivec2(x, y), level).g)
+ return false;
+ }
+ }
+
+ return true;
+
+}
+#endif
+
+#ifdef RAY_TRACING_INSTANCES
+#include
+#elif !defined(OCCLUSION)
+// Closest distances (float bits) per mesh for the streaming: drawn instances to their bounds divided by their scale
+// for the textures, all instances to their positions or centers for the meshes
+layout(std430, set = 3, binding = 12) buffer MeshDistances {
+ uint meshDistances[];
+};
+
+void WriteMeshDistance(uint idx, float distance) {
+
+ uint distanceBits = floatBitsToUint(distance);
+ // Most instances are further away than the closest one, reading first skips their atomics
+ if (distanceBits < meshDistances[idx])
+ atomicMin(meshDistances[idx], distanceBits);
+
+}
+#endif
+
+bool Intersects(vec3 aabbMin, vec3 aabbMax, CullView view) {
+
+ for (int i = 0; i < 6; i++) {
+ vec4 plane = view.planes[i];
+ vec3 s = mix(aabbMin, aabbMax, greaterThanEqual(plane.xyz, vec3(0.0)));
+ if (plane.w + dot(plane.xyz, s) < 0.0)
+ return false;
+ }
+
+ return true;
+
+}
+
+float DistanceSqr(vec3 a, vec3 b) {
+
+ vec3 diff = a - b;
+ return dot(diff, diff);
+
+}
+
+void main() {
+
+#ifdef OCCLUSION
+ if (gl_GlobalInvocationID.x >= occlusionInstanceCount)
+ return;
+ uint idx = occlusionInstances[gl_GlobalInvocationID.x];
+#else
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= PushConstants.instanceCount)
+ return;
+#ifndef RAY_TRACING_INSTANCES
+ // Instances which return early aren't visible in any view
+ results[idx] = uvec2(0u);
+#endif
+#endif
+
+ Instance instance = instances[idx];
+ bool dontCull = (instance.flags & INSTANCE_DONT_CULL) != 0u;
+ if ((instance.flags & INSTANCE_VISIBLE) == 0u && !dontCull)
+ return;
+
+ CullMesh mesh = meshes[instance.meshIdx];
+
+ vec3 localCenter = 0.5 * (mesh.aabbMin.xyz + mesh.aabbMax.xyz);
+ vec3 localExtent = 0.5 * (mesh.aabbMax.xyz - mesh.aabbMin.xyz);
+
+ mat3x4 matrix = instance.matrix;
+ vec3 center = vec4(localCenter, 1.0) * matrix;
+ vec3 extent = vec3(dot(abs(matrix[0].xyz), localExtent), dot(abs(matrix[1].xyz), localExtent),
+ dot(abs(matrix[2].xyz), localExtent));
+
+ vec3 cameraLocation = PushConstants.cameraLocation.xyz;
+ float centerDistanceSqr = DistanceSqr(center, cameraLocation);
+ float positionDistanceSqr = DistanceSqr(GetInstancePosition(matrix), cameraLocation);
+ float boundsDistance = length(max(abs(cameraLocation - center) - extent, vec3(0.0)));
+ float maxScale = GetMaxScale(matrix);
+
+ bool geometry = (mesh.flags & MESH_GEOMETRY) != 0u;
+
+ // Instances smaller than the minimum screen size are culled, from the ray traced scene as well
+ float screenSizeSqr = 4.0 * dot(extent, extent) * PushConstants.focalLength * PushConstants.focalLength;
+ float minScreenSizeSqr = mesh.minScreenSize * mesh.minScreenSize * centerDistanceSqr;
+ bool largeEnough = dontCull || screenSizeSqr >= minScreenSizeSqr;
+
+#ifndef RAY_TRACING_INSTANCES
+#ifndef OCCLUSION
+ // The streaming hears of instances from half the minimum screen size on, so their meshes are resident once they
+ // get big enough
+ bool requested = dontCull || 4.0 * screenSizeSqr >= minScreenSizeSqr;
+
+ // Meshes which aren't drawable need the distances as well, to be loaded again. Instances that are never culled
+ // need their geometry at any distance
+ if (requested)
+ WriteMeshDistance(2u * instance.meshIdx + 1u, dontCull ? 0.0 : sqrt(min(positionDistanceSqr, centerDistanceSqr)));
+
+ bool withinCullingDistance = dontCull || centerDistanceSqr <= mesh.aabbMin.w * mesh.aabbMin.w;
+
+ // Instances drawn as impostors or culled by distance don't need the textures of the mesh
+ bool impostorOnly = (mesh.flags & MESH_IMPOSTOR) != 0u &&
+ (!geometry || positionDistanceSqr >= mesh.impostorDistance * mesh.impostorDistance);
+ if (geometry && largeEnough && !impostorOnly && withinCullingDistance)
+ WriteMeshDistance(2u * instance.meshIdx, boundsDistance / maxScale);
+#endif
+#endif
+
+ if ((mesh.flags & MESH_DRAWABLE) == 0u || !largeEnough)
+ return;
+
+ // All views and the ray traced instance use the same level of detail, shadows of another level would fall onto it.
+ // The occlusion test keeps the one of the first culling, the indices are written with it
+#ifdef OCCLUSION
+ uvec2 result = results[idx];
+ uint lod = result.y >> RESULT_LOD_SHIFT;
+#else
+ uint lod = mesh.lodCount > 1u ? SelectLod(mesh, boundsDistance, maxScale, PushConstants.focalLength) : 0u;
+#endif
+
+#ifdef RAY_TRACING_INSTANCES
+ if ((instance.flags & INSTANCE_VISIBLE) != 0u)
+ WriteRayTracingInstance(instance, lod, positionDistanceSqr, PushConstants.maxRayTracingInstanceCount,
+ PushConstants.includeObjectHistory > 0u);
+ return;
+#endif
+
+ bool reversedWinding = (instance.flags & INSTANCE_REVERSED_WINDING) != 0u;
+#ifndef OCCLUSION
+ uvec2 result = uvec2(0u, lod << RESULT_LOD_SHIFT);
+#endif
+
+ bool visibleLastFrame = instance.visibleLastFrame > 0u;
+ bool drawnEarly = (mesh.flags & MESH_DRAW_EARLY) != 0u && (visibleLastFrame || dontCull);
+ for (uint i = PushConstants.firstView; i < PushConstants.firstView + PushConstants.viewCount; i++) {
+ CullView view = views[i];
+ bool shadow = view.shadow > 0u;
+ if (shadow && (mesh.flags & MESH_CAST_SHADOW) == 0u)
+ continue;
+
+ if (!dontCull) {
+ float cullingDistance = shadow ? mesh.aabbMax.w : mesh.aabbMin.w;
+ if (centerDistanceSqr > cullingDistance * cullingDistance)
+ continue;
+ if (!Intersects(center - extent, center + extent, view))
+ continue;
+ }
+
+#ifdef OCCLUSION
+ bool visible = dontCull || !IsOccluded(center - extent, center + extent);
+ if (visible != visibleLastFrame)
+ instances[idx].visibleLastFrame = visible ? 1u : 0u;
+ if (!visible || drawnEarly)
+ continue;
+#elif !defined(RAY_TRACING_INSTANCES)
+ if (i == PushConstants.occlusionView) {
+ uint occlusionIdx = atomicAdd(occlusionInstanceCount, 1u);
+ occlusionInstances[occlusionIdx] = idx;
+ if (occlusionIdx % 64u == 0u) {
+ atomicAdd(occlusionGroupCountX, 1u);
+ occlusionGroupCountY = 1u;
+ occlusionGroupCountZ = 1u;
+ }
+
+ if (!drawnEarly)
+ continue;
+ }
+#endif
+
+ float impostorDistance = shadow ? mesh.impostorShadowDistance : mesh.impostorDistance;
+ // Meshes without resident geometry are drawn as impostors only
+ bool impostor = (mesh.flags & MESH_IMPOSTOR) != 0u &&
+ (!geometry || positionDistanceSqr >= impostorDistance * impostorDistance);
+
+ uint counterIdx = view.counterOffset + instance.meshIdx * MESH_COUNTER_COUNT;
+ atomicAdd(counters[counterIdx + GetDrawCounter(impostor, lod, reversedWinding)], 1u);
+ result.x |= 1u << i;
+ if (impostor)
+ result.y |= 1u << i;
+ }
+
+#ifndef RAY_TRACING_INSTANCES
+ results[idx] = result;
+#endif
+
+}
diff --git a/data/shader/culling/draws.csh b/data/shader/culling/draws.csh
new file mode 100644
index 000000000..232b50e27
--- /dev/null
+++ b/data/shader/culling/draws.csh
@@ -0,0 +1,84 @@
+#include
+
+// Writes the indirect draw commands of the culled instances, impostors are drawn without indices
+
+layout (local_size_x = 64) in;
+
+struct DrawRequest {
+ uint meshIdx;
+ uint view;
+ uint type;
+ uint indexCount;
+ uint firstIndex;
+ uint lod;
+ int vertexOffset;
+ uint padding0;
+};
+
+layout(std430, set = 3, binding = 0) readonly buffer Meshes {
+ CullMesh meshes[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer Views {
+ CullView views[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer Counters {
+ uint counters[];
+};
+
+layout(std430, set = 3, binding = 3) readonly buffer Requests {
+ DrawRequest requests[];
+};
+
+layout(std430, set = 3, binding = 4) writeonly buffer Commands {
+ uint commands[];
+};
+
+// The end of the indices of each draw
+layout(std430, set = 3, binding = 5) readonly buffer Offsets {
+ uint offsets[];
+};
+
+layout(push_constant) uniform constants {
+ uint firstRequest;
+ uint requestCount;
+} PushConstants;
+
+void main() {
+
+ if (gl_GlobalInvocationID.x >= PushConstants.requestCount)
+ return;
+
+ uint idx = PushConstants.firstRequest + gl_GlobalInvocationID.x;
+ DrawRequest request = requests[idx];
+ CullMesh mesh = meshes[request.meshIdx];
+ CullView view = views[request.view];
+
+ uint counterIdx = view.counterOffset + request.meshIdx * MESH_COUNTER_COUNT +
+ GetDrawCounter(request.type == DRAW_IMPOSTOR, request.lod, request.type == DRAW_REVERSED_WINDING);
+ uint instanceCount = counters[counterIdx];
+ uint firstInstance = offsets[counterIdx] - instanceCount;
+
+ // Indices beyond the region weren't written
+ uint regionEnd = view.indexOffset + mesh.regionOffset + mesh.regionCapacity;
+ instanceCount = min(instanceCount, regionEnd - min(firstInstance, regionEnd));
+
+ uint offset = idx * 5u;
+ if (request.type == DRAW_IMPOSTOR) {
+ // A quad per impostor
+ commands[offset + 0u] = 4u;
+ commands[offset + 1u] = instanceCount;
+ commands[offset + 2u] = 0u;
+ commands[offset + 3u] = firstInstance;
+ commands[offset + 4u] = 0u;
+ }
+ else {
+ commands[offset + 0u] = request.indexCount;
+ commands[offset + 1u] = instanceCount;
+ commands[offset + 2u] = request.firstIndex;
+ commands[offset + 3u] = uint(request.vertexOffset);
+ commands[offset + 4u] = firstInstance;
+ }
+
+}
diff --git a/data/shader/culling/indices.csh b/data/shader/culling/indices.csh
new file mode 100644
index 000000000..9ef85532e
--- /dev/null
+++ b/data/shader/culling/indices.csh
@@ -0,0 +1,83 @@
+#include
+
+// Writes the indices of the visible instances at the offsets of their draws, each offset ends up behind its draw
+// OCCLUSION writes the instances the occlusion test counted
+
+layout (local_size_x = 64) in;
+
+layout(std430, set = 3, binding = 0) readonly buffer Instances {
+ Instance instances[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer Meshes {
+ CullMesh meshes[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer Views {
+ CullView views[];
+};
+
+layout(std430, set = 3, binding = 3) readonly buffer Results {
+ uvec2 results[];
+};
+
+layout(std430, set = 3, binding = 4) buffer Offsets {
+ uint offsets[];
+};
+
+layout(std430, set = 3, binding = 5) writeonly buffer Indices {
+ uint indices[];
+};
+
+#ifdef OCCLUSION
+layout(std430, set = 3, binding = 6) readonly buffer OcclusionInstances {
+ uint occlusionGroupCountX;
+ uint occlusionGroupCountY;
+ uint occlusionGroupCountZ;
+ uint occlusionInstanceCount;
+ uint occlusionInstances[];
+};
+#endif
+
+layout(push_constant) uniform constants {
+ uint firstView;
+ uint viewCount;
+ uint meshCount;
+ uint instanceCount;
+} PushConstants;
+
+void main() {
+
+#ifdef OCCLUSION
+ if (gl_GlobalInvocationID.x >= occlusionInstanceCount)
+ return;
+ uint idx = occlusionInstances[gl_GlobalInvocationID.x];
+#else
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= PushConstants.instanceCount)
+ return;
+#endif
+
+ uvec2 result = results[idx];
+ uint viewMask = ((1u << PushConstants.viewCount) - 1u) << PushConstants.firstView;
+ if ((result.x & viewMask) == 0u)
+ return;
+
+ Instance instance = instances[idx];
+ CullMesh mesh = meshes[instance.meshIdx];
+ uint lod = result.y >> RESULT_LOD_SHIFT;
+ bool reversedWinding = (instance.flags & INSTANCE_REVERSED_WINDING) != 0u;
+
+ for (uint i = PushConstants.firstView; i < PushConstants.firstView + PushConstants.viewCount; i++) {
+ if ((result.x & (1u << i)) == 0u)
+ continue;
+
+ CullView view = views[i];
+ bool impostor = (result.y & (1u << i)) != 0u;
+ uint counterIdx = view.counterOffset + instance.meshIdx * MESH_COUNTER_COUNT + GetDrawCounter(impostor, lod, reversedWinding);
+ uint position = atomicAdd(offsets[counterIdx], 1u);
+ if (position < view.indexOffset + mesh.regionOffset + mesh.regionCapacity)
+ indices[position] = idx;
+ }
+
+}
diff --git a/data/shader/culling/instances.hsh b/data/shader/culling/instances.hsh
new file mode 100644
index 000000000..a1fa8f709
--- /dev/null
+++ b/data/shader/culling/instances.hsh
@@ -0,0 +1,31 @@
+#include
+
+layout(std430, set = 1, binding = 20) readonly buffer Instances {
+ Instance instances[];
+};
+
+// Matrices of the last frame of the instances which moved
+layout(std430, set = 1, binding = 21) readonly buffer InstanceHistory {
+ mat3x4 instanceHistory[];
+};
+
+layout(std430, set = 1, binding = 22) readonly buffer InstanceIndices {
+ uint instanceIndices[];
+};
+
+layout(std430, set = 1, binding = 23) readonly buffer ImpostorInstanceIndices {
+ uint impostorInstanceIndices[];
+};
+
+mat4 GetInstanceMatrix(uint idx) {
+
+ return mat4(transpose(instances[idx].matrix));
+
+}
+
+mat4 GetLastInstanceMatrix(uint idx) {
+
+ uint historyIdx = instances[idx].historyIdx;
+ return historyIdx != INVALID_HISTORY_IDX ? mat4(transpose(instanceHistory[historyIdx])) : GetInstanceMatrix(idx);
+
+}
diff --git a/data/shader/culling/offsets.csh b/data/shader/culling/offsets.csh
new file mode 100644
index 000000000..69f425b5c
--- /dev/null
+++ b/data/shader/culling/offsets.csh
@@ -0,0 +1,46 @@
+#include
+
+// Turns the counts of the draws of each mesh and view into offsets in the region of the mesh
+
+layout (local_size_x = 64) in;
+
+layout(std430, set = 3, binding = 0) readonly buffer Meshes {
+ CullMesh meshes[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer Views {
+ CullView views[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer Counters {
+ uint counters[];
+};
+
+layout(std430, set = 3, binding = 3) writeonly buffer Offsets {
+ uint offsets[];
+};
+
+layout(push_constant) uniform constants {
+ uint firstView;
+ uint viewCount;
+ uint meshCount;
+ uint instanceCount;
+} PushConstants;
+
+void main() {
+
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= PushConstants.viewCount * PushConstants.meshCount)
+ return;
+
+ uint meshIdx = idx % PushConstants.meshCount;
+ CullView view = views[PushConstants.firstView + idx / PushConstants.meshCount];
+
+ uint counterIdx = view.counterOffset + meshIdx * MESH_COUNTER_COUNT;
+ uint offset = view.indexOffset + meshes[meshIdx].regionOffset;
+ for (uint i = 0u; i < MESH_COUNTER_COUNT; i++) {
+ offsets[counterIdx + i] = offset;
+ offset += counters[counterIdx + i];
+ }
+
+}
diff --git a/data/shader/culling/rtinstances.hsh b/data/shader/culling/rtinstances.hsh
new file mode 100644
index 000000000..e2a918017
--- /dev/null
+++ b/data/shader/culling/rtinstances.hsh
@@ -0,0 +1,120 @@
+// Writes the hardware ray tracing instances of the scene instances within the ray tracing distance of their meshes.
+// The instances written on the host (terrain and animated meshes) come first. RTMesh has to match GPURTMesh in
+// RayTracingWorld.h, TLASInstance VkAccelerationStructureInstanceKHR and BVHInstance GPUBVHInstance in RTStructures.h
+
+#define RT_MESH_USABLE 1u
+#define RT_MESH_FORCE_OPAQUE 2u
+
+struct RTMesh {
+ uint blasOffset;
+ int materialOffset;
+ uint mask;
+ uint flags;
+ float cullingDistanceSqr;
+ // Nearer instances are deformed and written on the host
+ float deformDistanceSqr;
+ uvec2 blasAddress;
+ // First record of the mesh in the hit region of ray tracing pipelines
+ uint hitRecordOffset;
+ // The levels of detail from 1 on follow each other from this mesh on, lodCount includes level 0
+ uint lodOffset;
+ uint lodCount;
+ uint padding0;
+};
+
+struct TLASInstance {
+ vec4 transform[3];
+ uint customIndexAndMask;
+ uint bindingOffsetAndFlags;
+ uvec2 blasAddress;
+};
+
+struct BVHInstance {
+ mat3x4 inverseMatrix;
+ int meshOffset;
+ int materialOffset;
+ int nextInstance;
+ uint mask;
+ uvec2 deformedVertices;
+ uvec2 meshIndices;
+};
+
+layout(std430, set = 3, binding = 6) readonly buffer InstanceHistory {
+ mat3x4 instanceHistory[];
+};
+
+layout(std430, set = 3, binding = 7) readonly buffer RTMeshes {
+ RTMesh rtMeshes[];
+};
+
+layout(std430, set = 3, binding = 8) buffer RTInstanceCounter {
+ uint rtInstanceCounter;
+};
+
+layout(std430, set = 3, binding = 9) writeonly buffer TLASInstances {
+ TLASInstance tlasInstances[];
+};
+
+layout(std430, set = 3, binding = 10) writeonly buffer BVHInstances {
+ BVHInstance bvhInstances[];
+};
+
+layout(std430, set = 3, binding = 11) writeonly buffer LastMatrices {
+ mat3x4 lastMatrices[];
+};
+
+// VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR and VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR
+const uint cullDisableFlag = 1u;
+const uint forceOpaqueFlag = 4u;
+
+void WriteRayTracingInstance(Instance instance, uint lod, float distanceSqr, uint maxInstanceCount, bool includeObjectHistory) {
+
+ RTMesh mesh = rtMeshes[instance.meshIdx];
+ if ((mesh.flags & RT_MESH_USABLE) == 0u || distanceSqr > mesh.cullingDistanceSqr || distanceSqr < mesh.deformDistanceSqr)
+ return;
+
+ // Levels whose BLAS isn't usable yet fall back to the finest one that is
+ lod = min(lod, mesh.lodCount - 1u);
+ if (lod > 0u)
+ mesh = rtMeshes[mesh.lodOffset + lod - 1u];
+
+ uint instanceIdx = atomicAdd(rtInstanceCounter, 1u);
+ if (instanceIdx >= maxInstanceCount)
+ return;
+
+ mat3x4 matrix = instance.matrix;
+
+ TLASInstance tlasInstance;
+ tlasInstance.transform[0] = matrix[0];
+ tlasInstance.transform[1] = matrix[1];
+ tlasInstance.transform[2] = matrix[2];
+ tlasInstance.customIndexAndMask = (mesh.blasOffset & 0xFFFFFFu) | (mesh.mask << 24u);
+ uint flags = cullDisableFlag | ((mesh.flags & RT_MESH_FORCE_OPAQUE) != 0u ? forceOpaqueFlag : 0u);
+ tlasInstance.bindingOffsetAndFlags = (mesh.hitRecordOffset & 0xFFFFFFu) | (flags << 24u);
+ tlasInstance.blasAddress = mesh.blasAddress;
+ tlasInstances[instanceIdx] = tlasInstance;
+
+ vec3 position = GetInstancePosition(matrix);
+ mat3 rotationScale = transpose(mat3(matrix[0].xyz, matrix[1].xyz, matrix[2].xyz));
+ mat3 inverseRotationScale = inverse(rotationScale);
+ vec3 inverseTranslation = -(inverseRotationScale * position);
+ mat3 inverseRows = transpose(inverseRotationScale);
+
+ BVHInstance bvhInstance;
+ bvhInstance.inverseMatrix = mat3x4(vec4(inverseRows[0], inverseTranslation.x),
+ vec4(inverseRows[1], inverseTranslation.y), vec4(inverseRows[2], inverseTranslation.z));
+ bvhInstance.meshOffset = int(mesh.blasOffset);
+ bvhInstance.materialOffset = mesh.materialOffset;
+ bvhInstance.nextInstance = 0;
+ bvhInstance.mask = mesh.mask;
+ // Deformed instances are written on the host
+ bvhInstance.deformedVertices = uvec2(0u);
+ bvhInstance.meshIndices = uvec2(0u);
+ bvhInstances[instanceIdx] = bvhInstance;
+
+ if (includeObjectHistory) {
+ lastMatrices[instanceIdx] = instance.historyIdx != INVALID_HISTORY_IDX ?
+ instanceHistory[instance.historyIdx] : matrix;
+ }
+
+}
diff --git a/data/shader/culling/scatter.csh b/data/shader/culling/scatter.csh
new file mode 100644
index 000000000..3eb18090f
--- /dev/null
+++ b/data/shader/culling/scatter.csh
@@ -0,0 +1,34 @@
+#include
+
+layout (local_size_x = 64) in;
+
+layout(std430, set = 3, binding = 0) buffer Instances {
+ Instance instances[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer Updates {
+ Instance updates[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer UpdateIndices {
+ uint updateIndices[];
+};
+
+layout(push_constant) uniform constants {
+ uint updateCount;
+} PushConstants;
+
+void main() {
+
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= PushConstants.updateCount)
+ return;
+
+ uint instanceIdx = updateIndices[idx];
+ Instance update = updates[idx];
+ // Has to match GPUScene::keepVisibleLastFrame
+ if (update.visibleLastFrame == 2u)
+ update.visibleLastFrame = instances[instanceIdx].visibleLastFrame;
+ instances[instanceIdx] = update;
+
+}
diff --git a/data/shader/ddgi/copyEdge.csh b/data/shader/ddgi/copyEdge.csh
deleted file mode 100644
index 113e02b2a..000000000
--- a/data/shader/ddgi/copyEdge.csh
+++ /dev/null
@@ -1,69 +0,0 @@
-layout (local_size_x = 8, local_size_y = 8) in;
-
-#if defined(IRRADIANCE)
-layout (set = 3, binding = 0, rgb10_a2) uniform image2DArray image;
-#elif defined(RADIANCE)
-layout (set = 3, binding = 0, rgb10_a2) uniform image2DArray image;
-#else
-layout (set = 3, binding = 0, rg16f) uniform image2DArray image;
-#endif
-
-layout(push_constant) uniform constants {
- int probeRes;
-} PushConstants;
-
-ivec2 OctMapStitch(ivec2 pix, bool leftBorder, bool rightBorder,
- bool upBorder, bool downBorder) {
- // Check if we're in one of the corners
- if (leftBorder && upBorder) {
- return ivec2(PushConstants.probeRes, PushConstants.probeRes);
- }
- else if (rightBorder && upBorder) {
- return ivec2(1, PushConstants.probeRes);
- }
- else if (leftBorder && downBorder) {
- return ivec2(PushConstants.probeRes, 1);
- }
- else if (rightBorder && downBorder) {
- return ivec2(1, 1);
- }
- // Check on which side we are
- if (upBorder) {
- return ivec2(PushConstants.probeRes - pix.x + 1, 1);
- }
- if (downBorder) {
- return ivec2(PushConstants.probeRes - pix.x + 1, PushConstants.probeRes);
- }
- if (leftBorder) {
- return ivec2(1, PushConstants.probeRes - pix.y + 1);
- }
- if (rightBorder) {
- return ivec2(PushConstants.probeRes, PushConstants.probeRes - pix.y + 1);
- }
-}
-
-void main() {
-
- ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(image).x ||
- pixel.y > imageSize(image).y)
- return;
-
- int probeResWithBorder = PushConstants.probeRes + 2;
- ivec2 pix = pixel % ivec2(probeResWithBorder);
-
- bool leftBorder = pix.x == 0;
- bool rightBorder = pix.x == probeResWithBorder - 1;
-
- bool upBorder = pix.y == 0;
- bool downBorder = pix.y == probeResWithBorder - 1;
-
- if (leftBorder || rightBorder || upBorder || downBorder) {
- ivec2 offset = OctMapStitch(pix, leftBorder, rightBorder, upBorder, downBorder);
- ivec2 base = (pixel / ivec2(probeResWithBorder)) * probeResWithBorder;
-
- vec4 color = imageLoad(image, ivec3(base + offset, int(gl_GlobalInvocationID.z)));
- imageStore(image, ivec3(pixel, int(gl_GlobalInvocationID.z)), color);
- }
-
-}
\ No newline at end of file
diff --git a/data/shader/ddgi/ddgi.hsh b/data/shader/ddgi/ddgi.hsh
index a1788a9d7..8da2fbbd7 100644
--- a/data/shader/ddgi/ddgi.hsh
+++ b/data/shader/ddgi/ddgi.hsh
@@ -60,6 +60,10 @@ layout(std140, set = 2, binding = 27) uniform DDGIBuffer {
int volumeEnabled;
float volumeStorageScale;
+
+ // Bring the gamma encoded history and the stored probes to the current pre-exposure
+ float historyExposureScale;
+ float volumeExposureScale;
} ddgiData;
struct RayHit {
@@ -303,7 +307,7 @@ vec4 GetLocalIrradianceFromCascade(vec3 P, vec3 V, vec3 N, vec3 geometryNormal,
: vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0);
// Due to the texture format we loose a bit of energy
- irradiance *= 1.0989 / ddgiData.volumeStorageScale;
+ irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale;
return irradiance;
@@ -461,7 +465,7 @@ vec4 GetLocalRadianceFromCascade(vec3 P, vec3 V, vec3 N, vec3 geometryNormal, in
: vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0);
// Due to the texture format we loose a bit of energy
- irradiance *= 1.0989 / ddgiData.volumeStorageScale;
+ irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale;
return irradiance;
@@ -609,19 +613,24 @@ void GetLocalProbeLightingFromCascade(vec3 P, vec3 V, vec3 N, vec3 L, vec3 geome
vec3 irrCoord = GetProbeCoord(gridCell, cascadeIndex, irrOctCoord, irrRes, irrTexelSize, ddgiData.volumeIrradianceRes);
irradiance.rgb = pow(textureLod(irradianceVolume, irrCoord, 0).rgb, vec3(0.5 * ddgiData.volumeGamma));
+#ifdef RADIANCE_VOLUME
vec3 radCoord = GetProbeCoord(gridCell, cascadeIndex, radOctCoord, radRes, radTexelSize, ddgiData.volumeRadianceRes);
radiance.rgb = pow(textureLod(radianceVolume, radCoord, 0).rgb, vec3(0.5 * ddgiData.volumeGamma));
+#endif
float weightIgnoredState = weight;
weight = probeState != PROBE_STATE_INACTIVE ? weight : 0.0;
sumIrradiance += weight * irradiance.rgb;
- sumRadiance += weight * radiance.rgb;
sumWeight += weight;
sumIrradianceIgnoredState += weightIgnoredState * irradiance.rgb;
- sumRadianceIgnoredState += weightIgnoredState * radiance.rgb;
sumWeightIgnoredState += weightIgnoredState;
+
+#ifdef RADIANCE_VOLUME
+ sumRadiance += weight * radiance.rgb;
+ sumRadianceIgnoredState += weightIgnoredState * radiance.rgb;
+#endif
}
if (sumWeight == 0.0 && sumWeightIgnoredState == 0.0) return;
@@ -630,13 +639,13 @@ void GetLocalProbeLightingFromCascade(vec3 P, vec3 V, vec3 N, vec3 L, vec3 geome
irradiance = sumWeight > 0.0 ? vec4(sqr(sumIrradiance / sumWeight), 0.0)
: vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0);
// Due to the texture format we loose a bit of energy
- irradiance *= 1.0989 / ddgiData.volumeStorageScale;
+ irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale;
#ifdef RADIANCE_VOLUME
// If no probes are activated for the given geometry, at least use the information available
radiance = sumWeight > 0.0 ? vec4(sqr(sumRadiance / sumWeight), 0.0)
: vec4(sqr(sumRadianceIgnoredState / sumWeightIgnoredState), 0.0);
- radiance *= 1.0989 / ddgiData.volumeStorageScale;
+ radiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale;
#else
radiance = irradiance;
#endif
diff --git a/data/shader/ddgi/probeUpdate.csh b/data/shader/ddgi/probeUpdate.csh
index a43d2a4b5..d7df52200 100644
--- a/data/shader/ddgi/probeUpdate.csh
+++ b/data/shader/ddgi/probeUpdate.csh
@@ -24,7 +24,7 @@ layout (local_size_x = 6, local_size_y = 6) in;
#ifdef LOWER_RES_RADIANCE
layout (local_size_x = 14, local_size_y = 14) in;
#else
-layout (local_size_x = 30, local_size_y = 30) in;
+layout (local_size_x = 30, local_size_y = 10) in;
#endif
#else
#ifdef LOWER_RES_MOMENTS
@@ -34,12 +34,10 @@ layout (local_size_x = 14, local_size_y = 14) in;
#endif
#endif
-#if defined(IRRADIANCE)
-layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray irradiance;
-#elif defined(RADIANCE)
-layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray radiance;
+#if defined(IRRADIANCE) || defined(RADIANCE)
+layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray probeImage;
#else
-layout (set = 3, binding = 0, rg16f) writeonly uniform image2DArray moment;
+layout (set = 3, binding = 0, rg16f) writeonly uniform image2DArray probeImage;
#endif
layout(std430, set = 3, binding = 1) buffer RayHits {
@@ -56,6 +54,13 @@ layout(std430, set = 3, binding = 3) buffer HistoryProbeOffsets {
const uint sharedSize = 128;
+#if defined(RADIANCE) && !defined(LOWER_RES_RADIANCE)
+// Large probes are split into slices of rows, one work group each, such that several groups fit on a compute unit
+const int probeSliceCount = 3;
+#else
+const int probeSliceCount = 1;
+#endif
+
#if defined(IRRADIANCE) || defined(RADIANCE)
struct RayData {
// This seems to be a better layout than two vec3's
@@ -76,12 +81,86 @@ struct RayData {
shared RayData rayData[sharedSize];
-vec4 GetHistoryFromHigherCascade(ivec2 pixel, int cascadeIndex) {
+#ifdef RADIANCE
+// Each ray is linked into the lists of the texels within its weight cone, such that a texel only iterates its own rays
+#ifdef LOWER_RES_RADIANCE
+const int rayTexelReach = 1;
+#else
+const int rayTexelReach = 2;
+#endif
+const int rayTexelWidth = 2 * rayTexelReach + 1;
+const uint texelsPerRay = uint(rayTexelWidth * rayTexelWidth);
+const uint invalidRayNode = 0xFFFFFFFFu;
+// Only rays within ~7 degrees pass the weight threshold
+const float radianceCosThreshold = 0.992;
+
+shared AeF16x4 texelDirections[gl_WorkGroupSize.x * gl_WorkGroupSize.y];
+shared uint texelRayHeads[gl_WorkGroupSize.x * gl_WorkGroupSize.y];
+shared ivec2 rayTexels[sharedSize];
+shared uint rayNodeNext[sharedSize * texelsPerRay];
+
+// Maps a texel outside of the octahedral map to the adjacent texel across the fold
+ivec2 WrapOctahedronTexel(ivec2 texel, ivec2 res) {
+
+ if (texel.x < 0 || texel.x >= res.x) {
+ texel.x = texel.x < 0 ? -texel.x - 1 : 2 * res.x - 1 - texel.x;
+ texel.y = res.y - 1 - texel.y;
+ }
+ if (texel.y < 0 || texel.y >= res.y) {
+ texel.y = texel.y < 0 ? -texel.y - 1 : 2 * res.y - 1 - texel.y;
+ texel.x = res.x - 1 - texel.x;
+ }
+
+ return texel;
+
+}
+
+// Each node is a pair of a ray and a texel in the neighborhood of the ray's texel
+void LinkRayNode(uint node, ivec2 res, int sliceOffset) {
+
+ uint rayIdx = node / texelsPerRay;
+ uint neighbor = node % texelsPerRay;
+
+ ivec2 rayTexel = rayTexels[rayIdx];
+ ivec2 texel = rayTexel + ivec2(neighbor % uint(rayTexelWidth), neighbor / uint(rayTexelWidth)) - ivec2(rayTexelReach);
+ ivec2 wrappedTexel = WrapOctahedronTexel(texel, res);
+ // Near the middle of an edge the fold maps back into the neighborhood, link these texels once
+ if (wrappedTexel != texel && all(lessThanEqual(abs(wrappedTexel - rayTexel), ivec2(rayTexelReach))))
+ return;
- ivec3 workGroup = ivec3(gl_WorkGroupID.xyz);
- workGroup.y %= ddgiData.volumeProbeCount.y;
+ ivec2 sliceTexel = wrappedTexel - ivec2(0, sliceOffset);
+ if (sliceTexel.y < 0 || sliceTexel.y >= int(gl_WorkGroupSize.y))
+ return;
- vec3 probePosition = vec3(workGroup) * ddgiData.cascades[cascadeIndex].cellSize.xyz + ddgiData.cascades[cascadeIndex].volumeMin.xyz;
+ uint texelIdx = uint(sliceTexel.y * res.x + sliceTexel.x);
+ if (dot(texelDirections[texelIdx].rgb, rayData[rayIdx].direction.rgb) < AeF16(radianceCosThreshold))
+ return;
+
+ rayNodeNext[node] = atomicExchange(texelRayHeads[texelIdx], node);
+
+}
+
+void AccumulateRadiance(uint rayIdx, AeF16x3 N, bool reset, inout AeF16x4 result) {
+
+ AeF16 cosTheta = dot(N, rayData[rayIdx].direction.rgb);
+ if (!reset && cosTheta < AeF16(radianceCosThreshold))
+ return;
+
+ AeF16 weight = pow(max(AeF16(0.0), cosTheta), AeF16(256.0));
+
+ AeF16x3 radiance = rayData[rayIdx].radiance.xyz;
+
+ if (reset || weight > 0.15)
+ result += AeF16x4(radiance, AeF16(1.0)) * weight;
+
+}
+#endif
+
+vec4 GetHistoryFromHigherCascade(ivec2 pixel, ivec3 probeGroup, int cascadeIndex) {
+
+ probeGroup.y %= ddgiData.volumeProbeCount.y;
+
+ vec3 probePosition = vec3(probeGroup) * ddgiData.cascades[cascadeIndex].cellSize.xyz + ddgiData.cascades[cascadeIndex].volumeMin.xyz;
// Note: Cascades are orderd from biggest (index 0) to smallest (index cascadeCount - 1)
cascadeIndex = max(cascadeIndex - 1, 0);
@@ -119,16 +198,47 @@ vec4 GetHistoryFromHigherCascade(ivec2 pixel, int cascadeIndex) {
}
+// Border texels repeat the mirrored interior texels of the same edge, such that bilinear filtering wraps around the octahedron
+void StoreProbeTexel(ivec2 pix, ivec2 res, ivec2 resOffset, int layer, vec4 value) {
+
+ ivec2 tileOffset = resOffset - ivec2(1);
+ ivec2 texel = pix + ivec2(1);
+ ivec2 mirrored = res + ivec2(1) - texel;
+
+ imageStore(probeImage, ivec3(tileOffset + texel, layer), value);
+
+ if (texel.y == 1)
+ imageStore(probeImage, ivec3(tileOffset + ivec2(mirrored.x, 0), layer), value);
+ if (texel.y == res.y)
+ imageStore(probeImage, ivec3(tileOffset + ivec2(mirrored.x, res.y + 1), layer), value);
+ if (texel.x == 1)
+ imageStore(probeImage, ivec3(tileOffset + ivec2(0, mirrored.y), layer), value);
+ if (texel.x == res.x)
+ imageStore(probeImage, ivec3(tileOffset + ivec2(res.x + 1, mirrored.y), layer), value);
+
+ bool cornerX = texel.x == 1 || texel.x == res.x;
+ bool cornerY = texel.y == 1 || texel.y == res.y;
+ if (cornerX && cornerY) {
+ ivec2 corner = mix(ivec2(0), res + ivec2(1), equal(texel, ivec2(1)));
+ imageStore(probeImage, ivec3(tileOffset + corner, layer), value);
+ }
+
+}
+
void main() {
- uint baseIdx = Flatten3D(ivec3(gl_WorkGroupID.xzy), ivec3(gl_NumWorkGroups.xzy));
+ ivec3 probeGroup = ivec3(int(gl_WorkGroupID.x) / probeSliceCount, gl_WorkGroupID.yz);
+ ivec3 probeGroupCount = ivec3(int(gl_NumWorkGroups.x) / probeSliceCount, gl_NumWorkGroups.yz);
+ int sliceOffset = (int(gl_WorkGroupID.x) % probeSliceCount) * int(gl_WorkGroupSize.y);
+
+ uint baseIdx = Flatten3D(probeGroup.xzy, probeGroupCount.xzy);
int cascadeIndex = GetProbeCascadeIndex(baseIdx);
bool reset;
ivec3 historyProbeCoord;
- GetProbeHistoryInfo(ivec3(gl_WorkGroupID.xyz), cascadeIndex, historyProbeCoord, reset);
+ GetProbeHistoryInfo(probeGroup, cascadeIndex, historyProbeCoord, reset);
- uint historyBaseIdx = Flatten3D(ivec3(historyProbeCoord.xzy), ivec3(gl_NumWorkGroups.xzy));
+ uint historyBaseIdx = Flatten3D(ivec3(historyProbeCoord.xzy), probeGroupCount.xzy);
uint probeState = floatBitsToUint(historyProbeStates[historyBaseIdx].x);
float probeAge = probeStates[baseIdx].w;
@@ -147,13 +257,16 @@ void main() {
ivec2 res = ivec2(ddgiData.volumeMomentsRes);
#endif
- ivec2 pix = ivec2(gl_LocalInvocationID);
+ ivec2 pix = ivec2(gl_LocalInvocationID) + ivec2(0, sliceOffset);
vec2 coord = (vec2(pix) + vec2(0.5)) / vec2(res);
AeF16x3 N = AeF16x3(OctahedronToUnitVector(coord));
+#ifdef RADIANCE
+ texelDirections[gl_LocalInvocationIndex] = AeF16x4(N, 0.0);
+#endif
- ivec2 resOffset = (res + ivec2(2)) * ivec2(gl_WorkGroupID.xz) + ivec2(1);
- ivec3 volumeCoord = ivec3(resOffset + pix, int(gl_WorkGroupID.y));
+ ivec2 resOffset = (res + ivec2(2)) * probeGroup.xz + ivec2(1);
+ ivec3 volumeCoord = ivec3(resOffset + pix, probeGroup.y);
AeF16 cellLength = AeF16(length(ddgiData.cascades[cascadeIndex].cellSize.xyz));
AeF16 maxDepth = cellLength * AeF16(0.75);
@@ -166,6 +279,10 @@ void main() {
// We might not have a multiple of shared size in terms of rays
uint loadRayCount = min(sharedSize, probeRayCount - i);
+#ifdef RADIANCE
+ texelRayHeads[gl_LocalInvocationIndex] = invalidRayNode;
+#endif
+
// Load rays cooperatively
for (uint j = gl_LocalInvocationIndex; j < loadRayCount; j += groupSize) {
RayHit hit = UnpackRayHit(hits[rayBaseIdx + i + j]);
@@ -173,6 +290,9 @@ void main() {
#if defined(IRRADIANCE) || defined(RADIANCE)
rayData[j].radiance.rgb = hit.radiance.rgb;
rayData[j].direction.a = hit.radiance.a;
+#ifdef RADIANCE
+ rayTexels[j] = min(ivec2(UnitVectorToOctahedron(vec3(hit.direction.xyz)) * vec2(res)), res - ivec2(1));
+#endif
#else
#ifndef AE_HALF_FLOAT
float dist = hit.radiance.a;
@@ -191,9 +311,27 @@ void main() {
barrier();
+#ifdef RADIANCE
+ if (!reset) {
+ for (uint node = gl_LocalInvocationIndex; node < loadRayCount * texelsPerRay; node += groupSize)
+ LinkRayNode(node, res, sliceOffset);
+ barrier();
+ }
+#endif
+
float maxWeight = 0.0;
// Iterate over all rays in the shared memory
+#ifdef RADIANCE
+ if (!reset) {
+ for (uint node = texelRayHeads[gl_LocalInvocationIndex]; node != invalidRayNode; node = rayNodeNext[node])
+ AccumulateRadiance(node / texelsPerRay, N, reset, result);
+ }
+ else {
+ for (uint j = 0; j < loadRayCount; j++)
+ AccumulateRadiance(j, N, reset, result);
+ }
+#else
for (uint j = 0; j < loadRayCount; j++) {
#if defined(IRRADIANCE)
@@ -223,14 +361,6 @@ void main() {
newProbeOffset -= rayData[j].direction.xyz * (probeOffsetDistance - dist) * 0.001 * probeOffset.w / probeOffsetDistance;
}
}
-#elif defined(RADIANCE)
- AeF16 weight = max(AeF16(0.0), dot(N, rayData[j].direction.rgb));
- weight = pow(weight, AeF16(256.0));
-
- AeF16x3 radiance = rayData[j].radiance.xyz;
-
- if (reset ||weight > 0.15)
- result += AeF16x4(radiance, AeF16(1.0)) * weight;
#else
AeF16 weight = max(AeF16(0.0), dot(N, rayData[j].direction.xyz));
@@ -242,6 +372,7 @@ void main() {
}
#endif
}
+#endif
barrier();
@@ -256,8 +387,9 @@ void main() {
#if defined(IRRADIANCE)
vec3 lastResult = texelFetch(irradianceVolume, historyVolumeCoord, 0).rgb;
if (probeState == PROBE_STATE_NEW || reset) {
- lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rgb;
+ lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rgb;
}
+ lastResult *= ddgiData.historyExposureScale;
vec3 resultOut = lastResult;
if (result.w > 0.0) {
vec4 fullResult = vec4(result);
@@ -271,7 +403,7 @@ void main() {
resultOut = mix(fullResult.xyz, lastResult, hysteresis);
}
}
- imageStore(irradiance, volumeCoord, vec4(resultOut, 0.0));
+ StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0));
if (gl_LocalInvocationIndex == 0) {
vec3 maxOffset = ddgiData.cascades[cascadeIndex].cellSize.xyz * 0.5;
@@ -282,8 +414,9 @@ void main() {
#elif defined(RADIANCE)
vec3 lastResult = texelFetch(radianceVolume, historyVolumeCoord, 0).rgb;
if (probeState == PROBE_STATE_NEW || reset) {
- lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rgb;
+ lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rgb;
}
+ lastResult *= ddgiData.historyExposureScale;
vec3 resultOut = lastResult;
if (result.w > 0.0) {
vec4 fullResult = vec4(result);
@@ -297,11 +430,11 @@ void main() {
resultOut = mix(fullResult.xyz, lastResult, hysteresis);
}
}
- imageStore(radiance, volumeCoord, vec4(resultOut, 0.0));
+ StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0));
#else
vec2 lastResult = texelFetch(momentsVolume, historyVolumeCoord, 0).rg;
if (probeState == PROBE_STATE_NEW || reset) {
- lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rg;
+ lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rg;
}
vec2 resultOut = lastResult;
if (result.w > 0.0) {
@@ -315,7 +448,7 @@ void main() {
}
}
- imageStore(moment, volumeCoord, vec4(resultOut, 0.0, 0.0));
+ StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0, 0.0));
#endif
}
\ No newline at end of file
diff --git a/data/shader/ddgi/rayHit.csh b/data/shader/ddgi/rayHit.csh
index 934513bb0..b98a00fc7 100644
--- a/data/shader/ddgi/rayHit.csh
+++ b/data/shader/ddgi/rayHit.csh
@@ -3,9 +3,7 @@
// Journal of Computer Graphics Techniques Vol 8.2 (2019).
// Majercik, Zander, et al. "Scaling Probe-Based Real-Time Dynamic Global Illumination for Production."
// arXiv preprint arXiv:2009.10796 (2020).
-#ifdef USE_SHADOW_MAP
-#define SHADOW_FILTER_1x1
-#endif
+#define LOCAL_STACK
#include <../raytracer/lights.hsh>
#include <../raytracer/tracing.hsh>
@@ -21,14 +19,14 @@
#include <../brdf/importanceSample.hsh>
#include <../brdf/surface.hsh>
-#include <../shadow.hsh>
#include <../clouds/shadow.hsh>
#include
#include
+#include
+#ifndef RAY_TRACING_PIPELINE
layout (local_size_x = 32) in;
-
-layout(set = 3, binding = 0) uniform sampler2DArrayShadow cascadeMaps;
+#endif
#ifdef CLOUD_SHADOWS
layout(set = 3, binding = 1) uniform sampler2D cloudMap;
@@ -39,15 +37,27 @@ layout(std430, set = 3, binding = 2) buffer RayHits {
PackedRayHit hits[];
};
+#ifdef DEFERRED_SHADOW_RAYS
+layout(std430, set = 3, binding = 4) buffer ShadowRays {
+ PackedShadowRay shadowRays[];
+};
+
+layout(std430, set = 3, binding = 5) buffer ShadowRayCount {
+ uint shadowRayCount;
+};
+#endif
+
layout(std140, set = 3, binding = 3) uniform UniformBuffer {
float seed;
- Shadow shadow;
} Uniforms;
vec3 EvaluateHit(inout Ray ray);
vec3 EvaluateDirectLight(inout Surface surface);
bool CheckVisibility(Surface surface, float lightDistance);
+bool hasShadowRay = false;
+PackedShadowRay shadowRay;
+
void main() {
if (IsRayInvocationValid()) {
@@ -55,10 +65,20 @@ void main() {
vec3 radiance = vec3(0.0);
if (ray.ID >= 0) {
+ TraceBufferedRay(ray);
radiance = EvaluateHit(ray);
// Probes store the lighting scaled, the lookup restores it
radiance *= ddgiData.volumeStorageScale;
+
+#ifdef DEFERRED_SHADOW_RAYS
+ if (hasShadowRay) {
+ uint shadowRayIdx = atomicAdd(shadowRayCount, 1u);
+ shadowRays[shadowRayIdx].origin = shadowRay.origin;
+ shadowRays[shadowRayIdx].direction = shadowRay.direction;
+ shadowRays[shadowRayIdx].radiance = vec4(shadowRay.radiance.rgb * ddgiData.volumeStorageScale, uintBitsToFloat(uint(ray.ID)));
+ }
+#endif
RayHit hit;
#ifndef AE_HALF_FLOAT
@@ -86,12 +106,8 @@ vec3 EvaluateHit(inout Ray ray) {
return SampleEnvironmentMap(ray.direction, 4).rgb;
}
- // Unpack the compressed triangle and extract surface parameters
- Instance instance = GetInstance(ray);
- Triangle tri = GetTriangle(ray, instance);
-
bool backfaceHit;
- Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, 4);
+ Surface surface = GetHitSurface(ray, false, backfaceHit, 4);
// Indicates backface hit
if (backfaceHit) {
@@ -102,8 +118,14 @@ vec3 EvaluateHit(inout Ray ray) {
radiance += surface.material.emissiveColor;
// Evaluate direct light
- radiance += EvaluateDirectLight(surface);
-
+ vec3 direct = EvaluateDirectLight(surface);
+ if (hasShadowRay)
+ shadowRay.radiance = vec4(direct, 0.0);
+ else
+ radiance += direct;
+
+ // Without RADIANCE_VOLUME the probe radiance falls back to the irradiance, the large radiance
+ // probes are too expensive to sample at incoherent hits for the small specular part of the bounce
vec4 probeIrradiance, probeRadiance;
GetLocalProbeLighting(surface.P, surface.V, surface.N, surface.N, surface.geometryNormal, probeIrradiance, probeRadiance);
@@ -129,7 +151,7 @@ vec3 EvaluateDirectLight(inout Surface surface) {
return vec3(0.0);
float curSeed = Uniforms.seed;
- float raySeed = float(gl_GlobalInvocationID.x);
+ float raySeed = float(INVOCATION_ID.x);
float lightPdf;
Light light = GetLight(surface, raySeed, curSeed, lightPdf);
@@ -149,27 +171,17 @@ vec3 EvaluateDirectLight(inout Surface surface) {
// Check for visibilty. This is important to get an
// estimate of the solid angle of the light from point P
// on the surface.
- if (light.type == uint(DIRECTIONAL_LIGHT)) {
-#ifdef USE_SHADOW_MAP
- float shadowFactor = CalculateShadowWorldSpace(Uniforms.shadow, cascadeMaps, surface.P,
- lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal)));
- radiance *= shadowFactor;
-#else
- if (light.castShadow)
- radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0;
+ if (light.castShadow)
+ radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0;
#ifdef CLOUD_SHADOWS
+ if (light.type == uint(DIRECTIONAL_LIGHT)) {
vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0));
float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap);
radiance *= cloudShadowFactor;
-#endif
-#endif
- }
- else {
- if (light.castShadow)
- radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0;
}
+#endif
return reflectance * radiance * lightSurface.NdotL / lightPdf;
@@ -182,7 +194,14 @@ bool CheckVisibility(Surface surface, float lightDistance) {
ray.direction = surface.L;
float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0;
ray.origin = surface.P + surface.geometryNormal * (side * EPSILON);
+#ifdef DEFERRED_SHADOW_RAYS
+ hasShadowRay = true;
+ shadowRay.origin = vec4(ray.origin, lightDistance - 2.0 * EPSILON);
+ shadowRay.direction = vec4(ray.direction, 0.0);
+ return true;
+#else
return HitAny(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON) == false;
+#endif
}
else {
return false;
diff --git a/data/shader/ddgi/rayHit.rgen b/data/shader/ddgi/rayHit.rgen
new file mode 100644
index 000000000..109e29376
--- /dev/null
+++ b/data/shader/ddgi/rayHit.rgen
@@ -0,0 +1,7 @@
+// Traces and shades the probe rays as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_shader_invocation_reorder : require
+
+#define RAY_TRACING_PIPELINE
+
+#include
diff --git a/data/shader/ddgi/rayShadow.csh b/data/shader/ddgi/rayShadow.csh
new file mode 100644
index 000000000..96ec38be2
--- /dev/null
+++ b/data/shader/ddgi/rayShadow.csh
@@ -0,0 +1,38 @@
+#define LOCAL_STACK
+
+#include <../raytracer/tracing.hsh>
+#include
+#include
+
+layout (local_size_x = 32) in;
+
+layout(std430, set = 3, binding = 2) buffer RayHits {
+ PackedRayHit hits[];
+};
+
+layout(std430, set = 3, binding = 4) buffer ShadowRays {
+ PackedShadowRay shadowRays[];
+};
+
+layout(std430, set = 3, binding = 5) buffer ShadowRayCount {
+ uint shadowRayCount;
+};
+
+void main() {
+
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= shadowRayCount)
+ return;
+
+ Ray ray;
+ ray.origin = shadowRays[idx].origin.xyz;
+ ray.direction = shadowRays[idx].direction.xyz;
+
+ if (!HitAny(ray, INSTANCE_MASK_SHADOW, 0.0, shadowRays[idx].origin.w)) {
+ uint hitIdx = floatBitsToUint(shadowRays[idx].radiance.w);
+ RayHit hit = UnpackRayHit(hits[hitIdx]);
+ hit.radiance.rgb = AeF16x3(vec3(hit.radiance.rgb) + shadowRays[idx].radiance.rgb);
+ hits[hitIdx] = PackRayHit(hit);
+ }
+
+}
diff --git a/data/shader/ddgi/shadowRay.hsh b/data/shader/ddgi/shadowRay.hsh
new file mode 100644
index 000000000..e1836fb0f
--- /dev/null
+++ b/data/shader/ddgi/shadowRay.hsh
@@ -0,0 +1,7 @@
+struct PackedShadowRay {
+ // xyz: origin, w: maximum distance
+ vec4 origin;
+ vec4 direction;
+ // rgb: direct light if the light is visible, w: index of the ray hit
+ vec4 radiance;
+};
diff --git a/data/shader/deferred/direct.csh b/data/shader/deferred/direct.csh
index 7685cd2eb..d5e9c02ab 100644
--- a/data/shader/deferred/direct.csh
+++ b/data/shader/deferred/direct.csh
@@ -14,6 +14,7 @@ layout (local_size_x = 16, local_size_y = 16) in;
#include <../common/convert.hsh>
#include <../common/utility.hsh>
+#include <../common/light.hsh>
#include <../brdf/brdfEval.hsh>
#include <../common/octahedron.hsh>
#include <../clouds/shadow.hsh>
@@ -29,13 +30,12 @@ layout(set = 3, binding = 2) uniform sampler2D cloudMap;
layout(set = 3, binding = 4) uniform sampler shadowSampler;
+#include
+
layout(std430, set = 3, binding = 6) buffer LightBucketsBuffer {
int lightBuckets[];
};
-layout(set = 3, binding = 7) uniform texture2DArray cascadeMaps[8];
-layout(set = 3, binding = 15) uniform textureCube cubeMaps[8];
-
layout(push_constant) uniform constants {
int lightCount;
int lightBucketCount;
@@ -45,9 +45,6 @@ layout(push_constant) uniform constants {
shared uint sharedLightBuckets[lightBucketCount];
-vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain);
-float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain);
-
void LoadGroupSharedData() {
int lightBucketOffset = GetLightBucketsGroupOffset();
@@ -102,17 +99,14 @@ void main() {
Light light = lights[offsetIdx + j];
-#ifndef AE_BINDLESS
- light.shadow.mapIdx = int(offsetIdx + j);
-#endif
bool isMain = i + j == 0u ? true : false;
- direct += EvaluateLight(light, surface, geometryNormal, isMain);
+ direct += EvaluateLight(light, surface, geometryNormal, isMain, pixel, texCoord);
}
}
if (dot(surface.material.emissiveColor, vec3(1.0)) > 0.01) {
- direct += surface.material.emissiveColor;
+ direct += surface.material.emissiveColor * globalData.preExposure;
}
}
@@ -120,137 +114,3 @@ void main() {
imageStore(image, pixel, vec4(direct, 1.0));
}
-
-uint GetLightType(Light light) {
-
- return floatBitsToUint(light.color.a);
-
-}
-
-vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain) {
-
- uint lightType = GetLightType(light);
-
- float attenuation = 1.0;
- float radius = light.direction.w;
-
- if (lightType == DIRECTIONAL_LIGHT) {
- surface.L = normalize(-light.direction.xyz);
- }
- else if (lightType == POINT_LIGHT) {
- vec3 pointToLight = light.location.xyz - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- float dist = sqrt(sqrDistance);
-
- attenuation = saturate(1.0 - pow(dist / radius, 4.0)) / sqrDistance;
-
- surface.L = pointToLight / dist;
- }
- else if (lightType == SPOT_LIGHT) {
- vec3 pointToLight = light.location.xyz - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- float dist = sqrt(sqrDistance);
-
- surface.L = pointToLight / dist;
-
- float strength = dot(surface.L, normalize(-light.direction.xyz));
- float angleAttenuation = saturate(strength * light.specific0 + light.specific1);
- float distAttenuation = saturate(1.0 - pow(dist / radius, 4.0)) / sqrDistance;
- attenuation = distAttenuation * sqr(angleAttenuation);
- }
-
- if (attenuation == 0.0)
- return vec3(0.0);
-
- float shadowFactor = GetShadowFactor(light, surface, lightType, geometryNormal, isMain);
-
- UpdateSurface(surface);
-
- // Direct diffuse + specular BRDF
- vec3 directDiffuse = EvaluateDiffuseBRDF(surface);
- vec3 directSpecular = EvaluateSpecularBRDF(surface);
-
- vec3 direct = directDiffuse + directSpecular;
-
- vec3 radiance = light.color.rgb * light.intensity * attenuation;
- direct = direct * radiance * surface.NdotL * shadowFactor;
-
- if (surface.material.transmissive) {
- Surface backSurface = CreateSurface(surface.V, -surface.N, surface.L, surface.material);
-
- float viewDependency = saturate(dot(-surface.V, surface.L));
- // viewDependency = sqr(viewDependency);
-
- // Direct diffuse BRDF backside
- directDiffuse = viewDependency * surface.material.transmissiveColor * EvaluateDiffuseBRDF(backSurface);
- // Need to change this back
- // direct += directDiffuse * radiance * backSurface.NdotL * shadowFactorTransmissive;
- direct += directDiffuse * radiance * backSurface.NdotL * shadowFactor;
- }
-
- return direct;
-
-}
-
-float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain) {
-
- if (light.shadow.mapIdx < 0)
- return 1.0;
-
- ivec2 pixel = ivec2(gl_GlobalInvocationID);
-
- float shadowFactor = 1.0;
-
- vec3 shadowNormal = surface.material.transmissive ? dot(surface.L, geometryNormal) < 0.0 ?
- -geometryNormal : geometryNormal : geometryNormal;
-
- if (lightType == DIRECTIONAL_LIGHT) {
-#ifdef AE_BINDLESS
- shadowFactor = CalculateCascadedShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
- shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#else
- shadowFactor = CalculateCascadedShadow(light.shadow, cascadeMaps[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
- shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#endif
- }
- else if (lightType == POINT_LIGHT) {
-#ifdef AE_BINDLESS
- shadowFactor = CalculatePointShadow(light.shadow, bindlessCubemaps[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#else
- shadowFactor = CalculatePointShadow(light.shadow, cubeMaps[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#endif
- }
- else if (lightType == SPOT_LIGHT) {
-#ifdef AE_BINDLESS
- shadowFactor = CalculateSpotShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
- shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#else
- shadowFactor = CalculateSpotShadow(light.shadow, cascadeMaps[nonuniformEXT(light.shadow.mapIdx)],
- shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
- shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
-#endif
- }
-
- if (isMain) {
-#ifdef CLOUD_SHADOWS
- float cloudShadowFactor = CalculateCloudShadow(surface.P, cloudShadowUniforms.cloudShadow, cloudMap);
-
- shadowFactor *= cloudShadowFactor;
-#endif
- float shadowFactorTransmissive = shadowFactor;
-#ifdef SCREEN_SPACE_SHADOWS
- ivec2 resolution = imageSize(image);
- vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
- float sssFactor = textureLod(sssTexture, texCoord, 0).r;
- shadowFactor = min(sssFactor, shadowFactor);
-#endif
- }
-
- return shadowFactor;
-
-}
\ No newline at end of file
diff --git a/data/shader/deferred/directLight.hsh b/data/shader/deferred/directLight.hsh
new file mode 100644
index 000000000..3f684d822
--- /dev/null
+++ b/data/shader/deferred/directLight.hsh
@@ -0,0 +1,119 @@
+// The light of a light source on a surface. The includer declares shadowSampler, cloudMap with CLOUD_SHADOWS and
+// sssTexture with SCREEN_SPACE_SHADOWS, the pixel selects the shadow filter noise
+
+float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord);
+
+uint GetLightType(Light light) {
+
+ return floatBitsToUint(light.color.a);
+
+}
+
+vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord) {
+
+ uint lightType = GetLightType(light);
+
+ float attenuation = 1.0;
+ float radius = light.direction.w;
+
+ if (lightType == DIRECTIONAL_LIGHT) {
+ surface.L = normalize(-light.direction.xyz);
+ }
+ else if (lightType == POINT_LIGHT) {
+ vec3 pointToLight = light.location.xyz - surface.P;
+ float dist = length(pointToLight);
+
+ attenuation = GetDistanceAttenuation(dist, radius);
+
+ surface.L = pointToLight / dist;
+ }
+ else if (lightType == SPOT_LIGHT) {
+ vec3 pointToLight = light.location.xyz - surface.P;
+ float dist = length(pointToLight);
+
+ surface.L = pointToLight / dist;
+
+ float strength = dot(surface.L, normalize(-light.direction.xyz));
+ float angleAttenuation = saturate(strength * light.specific0 + light.specific1);
+ float distAttenuation = GetDistanceAttenuation(dist, radius);
+ attenuation = distAttenuation * sqr(angleAttenuation);
+ }
+
+ if (attenuation == 0.0)
+ return vec3(0.0);
+
+ if (dot(surface.N, surface.L) <= 0.0 && !surface.material.transmissive)
+ return vec3(0.0);
+
+ float shadowFactor = GetShadowFactor(light, surface, lightType, geometryNormal, isMain, pixel, texCoord);
+
+ UpdateSurface(surface);
+
+ // Direct diffuse + specular BRDF
+ vec3 directDiffuse = EvaluateDiffuseBRDF(surface);
+ vec3 directSpecular = EvaluateSpecularBRDF(surface);
+#ifdef TRANSLUCENT_PASS
+ // Translucent surfaces scatter light by their opacity, glass reflects it regardless of the opacity
+ directDiffuse *= surface.material.opacity;
+#endif
+
+ vec3 direct = directDiffuse + directSpecular;
+
+ vec3 radiance = light.color.rgb * light.intensity * attenuation;
+ direct = direct * radiance * surface.NdotL * shadowFactor;
+
+ if (surface.material.transmissive) {
+ Surface backSurface = CreateSurface(surface.V, -surface.N, surface.L, surface.material);
+
+ float viewDependency = saturate(dot(-surface.V, surface.L));
+ // viewDependency = sqr(viewDependency);
+
+ // Direct diffuse BRDF backside
+ directDiffuse = viewDependency * surface.material.transmissiveColor * EvaluateDiffuseBRDF(backSurface);
+ direct += directDiffuse * radiance * backSurface.NdotL * shadowFactor;
+ }
+
+ return direct;
+
+}
+
+float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord) {
+
+ if (light.shadow.mapIdx < 0)
+ return 1.0;
+
+ float shadowFactor = 1.0;
+
+ vec3 shadowNormal = surface.material.transmissive ? dot(surface.L, geometryNormal) < 0.0 ?
+ -geometryNormal : geometryNormal : geometryNormal;
+
+ if (lightType == DIRECTIONAL_LIGHT) {
+ shadowFactor = CalculateCascadedShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)],
+ shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
+ shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
+ }
+ else if (lightType == POINT_LIGHT) {
+ shadowFactor = CalculatePointShadow(light.shadow, bindlessCubemaps[nonuniformEXT(light.shadow.mapIdx)],
+ shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
+ }
+ else if (lightType == SPOT_LIGHT) {
+ shadowFactor = CalculateSpotShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)],
+ shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0),
+ shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal)));
+ }
+
+ if (isMain) {
+#ifdef CLOUD_SHADOWS
+ float cloudShadowFactor = CalculateCloudShadow(surface.P, cloudShadowUniforms.cloudShadow, cloudMap);
+
+ shadowFactor *= cloudShadowFactor;
+#endif
+#ifdef SCREEN_SPACE_SHADOWS
+ float sssFactor = textureLod(sssTexture, texCoord, 0).r;
+ shadowFactor = min(sssFactor, shadowFactor);
+#endif
+ }
+
+ return shadowFactor;
+
+}
\ No newline at end of file
diff --git a/data/shader/deferred/geometry.fsh b/data/shader/deferred/geometry.fsh
index daa70129d..e35bcc6c2 100644
--- a/data/shader/deferred/geometry.fsh
+++ b/data/shader/deferred/geometry.fsh
@@ -1,8 +1,47 @@
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
#include <../globals.hsh>
+#include <../common/opacity.hsh>
+#include <../common/material.hsh>
#include
+#include
+#if defined(TRANSLUCENT)
+#include <../translucent/translucent.hsh>
+
+layout (location = 0) out vec4 colorFS;
+layout (location = 1) out vec4 coverageFS;
+layout (location = 2) out vec4 blendedVelocityFS;
+
+vec3 baseColorFS;
+vec2 normalFS;
+vec2 geometryNormalFS;
+vec3 roughnessMetalnessAoFS;
+vec3 emissiveFS;
+uint materialIdxFS;
+vec2 velocityFS;
+#elif defined(FRONT_LAYER)
+// The channels of the G-buffer which the reflections read
+layout (location = 0) out vec2 normalFS;
+layout (location = 1) out vec2 geometryNormalFS;
+layout (location = 2) out vec3 roughnessMetalnessAoFS;
+layout (location = 3) out uint materialIdxFS;
+layout (location = 4) out vec2 velocityFS;
+
+vec3 baseColorFS;
+vec3 emissiveFS;
+#elif defined(REFRACTION_BACK_FACES)
+// The normal pointing out of the surface where refracted rays leave it, the depth is written as well
+layout (location = 0) out vec2 backNormalFS;
+
+vec3 baseColorFS;
+vec2 normalFS;
+vec2 geometryNormalFS;
+vec3 roughnessMetalnessAoFS;
+vec3 emissiveFS;
+uint materialIdxFS;
+vec2 velocityFS;
+#else
layout (location = 0) out vec3 baseColorFS;
layout (location = 1) out vec2 normalFS;
layout (location = 2) out vec2 geometryNormalFS;
@@ -10,6 +49,7 @@ layout (location = 3) out vec3 roughnessMetalnessAoFS;
layout (location = 4) out vec3 emissiveFS;
layout (location = 5) out uint materialIdxFS;
layout (location = 6) out vec2 velocityFS;
+#endif
layout(location=0) in vec3 positionVS;
layout(location=1) in vec3 normalVS;
@@ -28,29 +68,16 @@ layout(location=5) in vec4 vertexColorsVS;
layout(location=7) in mat3 TBN;
#endif
-layout(push_constant) uniform constants {
- uint vegetation;
- uint invertUVs;
- uint twoSided;
- uint staticMesh;
- uint materialIdx;
- float normalScale;
- float displacementScale;
- float windTextureLod;
- float windBendScale;
- float windWiggleScale;
- float uvAnimationX;
- float uvAnimationY;
- float uvTiling;
- uint baseColorTextureIdx;
- uint opacityTextureIdx;
- uint normalTextureIdx;
- uint roughnessTextureIdx;
- uint metalnessTextureIdx;
- uint aoTextureIdx;
- uint heightTextureIdx;
- uint emissiveTextureIdx;
-} PushConstants;
+#ifdef MATERIAL_GRAPH_SURFACE
+layout(location=10) in vec3 objectPositionVS;
+layout(location=11) in vec3 instancePositionVS;
+layout(location=12) in vec3 objectNormalVS;
+#endif
+
+layout(location=13) flat in uint lodVS;
+#ifdef DRAW_DATA
+layout(location=14) flat in uint drawIdxVS;
+#endif
vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) {
#ifdef HEIGHT_MAP
@@ -63,20 +90,20 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) {
// depth of current layer
float currentLayerDepth = 0.0;
// the amount to shift the texture coordinates per layer (from vector P)
- vec2 P = viewDir.xy / viewDir.z * PushConstants.displacementScale;
+ vec2 P = viewDir.xy / viewDir.z * DrawValue(displacementScale);
vec2 deltaTexCoords = P / numLayers;
vec2 currentTexCoords = texCoords;
vec2 ddx = dFdx(texCoords);
vec2 ddy = dFdy(texCoords);
- float currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r;
+ float currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r;
while(currentLayerDepth < currentDepthMapValue) {
// shift texture coordinates along direction of P
currentTexCoords -= deltaTexCoords;
// get depthmap value at current texture coordinates
- currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r;
+ currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r;
// get depth of next layer
currentLayerDepth += layerDepth;
}
@@ -85,7 +112,7 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) {
// get depth after and before collision for linear interpolation
float afterDepth = currentDepthMapValue - currentLayerDepth;
- float beforeDepth = 1.0 - SampleHeight(prevTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r - currentLayerDepth + layerDepth;
+ float beforeDepth = 1.0 - SampleHeight(prevTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r - currentLayerDepth + layerDepth;
// interpolation of texture coordinates
float weight = afterDepth / (afterDepth - beforeDepth);
@@ -100,10 +127,64 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) {
void main() {
+#ifdef DRAW_DATA
+ drawIdx = drawIdxVS;
+#endif
+
+ // The coverage of translucent surfaces, the others are cut out by it
+ float opacity = 1.0;
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ vec2 graphTexCoord = vec2(0.0);
+ vec4 graphColor = vec4(1.0);
+#ifdef TEX_COORDS
+ graphTexCoord = texCoordVS;
+#endif
+#ifdef VERTEX_COLORS
+ graphColor = vertexColorsVS;
+#endif
+
+ float graphFrontFacing = gl_FrontFacing ? 1.0 : -1.0;
+ vec3 graphGeometryNormal = normalize(normalVS) * (DrawValue(twoSided) > 0 ? graphFrontFacing : 1.0);
+ mat3 graphTangentFrame = mat3(1.0);
+#if defined(MATERIAL_GRAPH_WRITES_NORMAL) || defined(MATERIAL_GRAPH_USES_TANGENTS)
+#ifdef NORMAL_MAP
+ graphTangentFrame = TBN;
+#else
+ graphTangentFrame = MaterialGraphCotangentFrame(graphGeometryNormal, positionVS, graphTexCoord);
+#endif
+#endif
+
+ MaterialSurfaceInput surfaceInput = CreateMaterialSurfaceInput(objectPositionVS, normalize(objectNormalVS),
+ vec3(globalData.ivMatrix * vec4(positionVS, 1.0)), normalize(mat3(globalData.ivMatrix) * graphGeometryNormal),
+ instancePositionVS, graphTangentFrame, graphTexCoord, 0.5 * ndcCurrentVS.xy / ndcCurrentVS.z + 0.5,
+ graphColor, graphFrontFacing, PushConstants.materialGraphOffset);
+ MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceInput);
+
+#if defined(MATERIAL_GRAPH_HAS_OPACITY) && defined(TRANSLUCENT_PASS)
+ opacity = surface.opacity;
+#elif defined(MATERIAL_GRAPH_OPACITY)
+ if (surface.opacity < opacityCutoff)
+ discard;
+#endif
+
+ baseColorFS = surface.baseColor;
+ emissiveFS = surface.emissive;
+ roughnessMetalnessAoFS = vec3(surface.roughness, surface.metalness, surface.ao);
+ geometryNormalFS = EncodeNormal(graphGeometryNormal);
+
+#ifdef MATERIAL_GRAPH_WRITES_NORMAL
+ vec3 graphNormal = normalize(graphTangentFrame * surface.normal);
+ graphNormal *= dot(graphGeometryNormal, graphNormal) < 0.0 ? -1.0 : 1.0;
+ normalFS = EncodeNormal(graphNormal);
+#else
+ normalFS = geometryNormalFS;
+#endif
+#else
#ifdef TEX_COORDS
vec2 texCoords = texCoordVS;
#endif
-
+
// Check if usage is valid (otherwise texCoords won't be used)
#if defined(HEIGHT_MAP) && (defined(BASE_COLOR_MAP) || defined(NORMAL_MAP) || defined(ROUGHNESS_MAP) || defined(METALNESS_MAP) || defined(AO_MAP) || defined(EMISSIVE_MAP))
vec3 viewDir = normalize(transpose(TBN) * -positionVS);
@@ -113,24 +194,25 @@ void main() {
baseColorFS = vec3(1.0);
#if (defined(OPACITY_MAP) || defined(VERTEX_COLORS))
- float opacity = 1.0;
#ifdef OPACITY_MAP
- opacity *= SampleOpacity(texCoords, PushConstants.opacityTextureIdx, globalData.mipLodBias);
+ opacity *= SampleOpacity(texCoords, DrawValue(opacityTextureIdx), globalData.mipLodBias);
#endif
#ifdef VERTEX_COLORS
// opacity *= vertexColorsVS.a;
#endif
- if (opacity < 0.2)
+#ifndef TRANSLUCENT_PASS
+ if (opacity < opacityCutoff)
discard;
#endif
+#endif
#ifdef BASE_COLOR_MAP
- vec3 textureColor = SampleBaseColor(texCoords, PushConstants.baseColorTextureIdx, globalData.mipLodBias);
+ vec3 textureColor = SampleBaseColor(texCoords, DrawValue(baseColorTextureIdx), globalData.mipLodBias);
baseColorFS *= textureColor.rgb;
#endif
#ifdef EMISSIVE_MAP
- vec3 emissiveColor = SampleEmissive(texCoords, PushConstants.emissiveTextureIdx, globalData.mipLodBias);
+ vec3 emissiveColor = SampleEmissive(texCoords, DrawValue(emissiveTextureIdx), globalData.mipLodBias);
emissiveFS = emissiveColor.rgb;
#endif
@@ -141,16 +223,16 @@ void main() {
vec3 geometryNormal = normalize(normalVS);
#ifdef NORMAL_MAP
- vec3 normalColor = SampleNormal(texCoords, PushConstants.normalTextureIdx, globalData.mipLodBias);
- vec3 normal = mix(geometryNormal, normalize(TBN * normalColor), PushConstants.normalScale);
+ vec3 normalColor = SampleNormal(texCoords, DrawValue(normalTextureIdx), globalData.mipLodBias);
+ vec3 normal = mix(geometryNormal, normalize(TBN * normalColor), DrawValue(normalScale));
// We want the normal always to face the camera for two sided materials
- geometryNormal *= PushConstants.twoSided > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0;
+ geometryNormal *= DrawValue(twoSided) > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0;
normal *= dot(geometryNormal, normal) < 0.0 ? -1.0 : 1.0;
normalFS = EncodeNormal(normal);
#else
// We want the normal always to face the camera for two sided materials
- geometryNormal *= PushConstants.twoSided > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0;
+ geometryNormal *= DrawValue(twoSided) > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0;
#endif
@@ -165,16 +247,17 @@ void main() {
float aoFactor = 1.0;
#ifdef ROUGHNESS_MAP
- roughnessFactor *= SampleRoughness(texCoords, PushConstants.roughnessTextureIdx, globalData.mipLodBias);
+ roughnessFactor *= SampleRoughness(texCoords, DrawValue(roughnessTextureIdx), globalData.mipLodBias);
roughnessMetalnessAoFS.r = roughnessFactor;
#endif
#ifdef METALNESS_MAP
- metalnessFactor *= SampleMetalness(texCoords, PushConstants.metalnessTextureIdx, globalData.mipLodBias);
+ metalnessFactor *= SampleMetalness(texCoords, DrawValue(metalnessTextureIdx), globalData.mipLodBias);
roughnessMetalnessAoFS.g = metalnessFactor;
#endif
#ifdef AO_MAP
- aoFactor *= SampleAo(texCoords, PushConstants.aoTextureIdx, globalData.mipLodBias);
+ aoFactor *= SampleAo(texCoords, DrawValue(aoTextureIdx), globalData.mipLodBias);
roughnessMetalnessAoFS.b = aoFactor;
+#endif
#endif
// Calculate velocity
@@ -186,6 +269,59 @@ void main() {
velocityFS = (ndcL - ndcC) * 0.5;
- materialIdxFS = PushConstants.materialIdx;
-
+ materialIdxFS = DrawValue(materialIdx);
+
+ if (globalData.debugMeshLods > 0u) {
+ const vec3 lodColors[5] = vec3[](vec3(1.0), vec3(0.1, 0.9, 0.1), vec3(0.1, 0.4, 1.0), vec3(1.0, 0.8, 0.1),
+ vec3(1.0, 0.1, 0.1));
+ baseColorFS = lodColors[min(lodVS, 4u)] * (0.5 + 0.5 * dot(baseColorFS, vec3(0.333)));
+ }
+
+#ifdef TRANSLUCENT_PASS
+ // The material holds the factors of the maps like in the deferred passes, see deferred/deferred.hsh
+ Material material = UnpackMaterial(materialIdxFS);
+ opacity *= material.opacity;
+#endif
+
+#if defined(FRONT_LAYER) || defined(REFRACTION_BACK_FACES)
+ // Only surfaces with some coverage reflect, refracting ones are clear glass without it like in the path tracer
+ if (opacity <= 0.0 && PushConstants.refractiveIndex == 1.0)
+ discard;
+#endif
+
+#ifdef REFRACTION_BACK_FACES
+ vec3 backNormal = DecodeNormal(normalFS);
+ backNormalFS = EncodeNormal(dot(backNormal, positionVS) < 0.0 ? -backNormal : backNormal);
+#endif
+
+#ifdef TRANSLUCENT
+ if (material.baseColorMap || material.vertexColors)
+ material.baseColor *= baseColorFS;
+ if (material.roughnessMap)
+ material.roughness *= roughnessMetalnessAoFS.r;
+ if (material.metalnessMap)
+ material.metalness *= roughnessMetalnessAoFS.g;
+ if (material.aoMap)
+ material.ao *= roughnessMetalnessAoFS.b;
+ if (material.emissiveMap)
+ material.emissiveColor *= emissiveFS;
+
+ vec3 shadingGeometryNormal = DecodeNormal(geometryNormalFS);
+ vec3 shadingNormal = material.normalMap ? DecodeNormal(normalFS) : shadingGeometryNormal;
+
+ float coverage;
+ colorFS = ShadeTranslucent(material, shadingNormal, shadingGeometryNormal, positionVS, saturate(opacity),
+ PushConstants.refractiveIndex, PushConstants.thickness, coverage);
+ coverageFS = vec4(coverage, 0.0, 0.0, coverage);
+ // The upscaler reprojects by the surface as much as it covers the background, light added or multiplied keeps
+ // the motion of the background
+#if defined(BLEND_ALPHA)
+ blendedVelocityFS = vec4(velocityFS * coverage, 0.0, coverage);
+#elif defined(BLEND_ADDITIVE)
+ blendedVelocityFS = vec4(0.0);
+#else
+ blendedVelocityFS = vec4(1.0);
+#endif
+#endif
+
}
diff --git a/data/shader/deferred/geometry.hsh b/data/shader/deferred/geometry.hsh
new file mode 100644
index 000000000..302c4d587
--- /dev/null
+++ b/data/shader/deferred/geometry.hsh
@@ -0,0 +1,59 @@
+// Translucent surfaces are blended (TRANSLUCENT), write the closest one for the reflections (FRONT_LAYER) or the back
+// faces where refracted rays leave them (REFRACTION_BACK_FACES) instead of being cut out
+#if defined(TRANSLUCENT) || defined(FRONT_LAYER) || defined(REFRACTION_BACK_FACES)
+#define TRANSLUCENT_PASS
+#endif
+
+// Has to match OpaqueRenderer::DrawData, multi draws read it from a buffer instead of the push constants
+struct GeometryDraw {
+ uint invertUVs;
+ uint twoSided;
+ uint staticMesh;
+ uint materialIdx;
+ float normalScale;
+ float displacementScale;
+ float windTextureLod;
+ float windBendScale;
+ float windWiggleScale;
+ float uvAnimationX;
+ float uvAnimationY;
+ float uvTiling;
+ uint baseColorTextureIdx;
+ uint opacityTextureIdx;
+ uint normalTextureIdx;
+ uint roughnessTextureIdx;
+ uint metalnessTextureIdx;
+ uint aoTextureIdx;
+ uint heightTextureIdx;
+ uint emissiveTextureIdx;
+ // Level of detail of host culled draws, the commands of a GPU culled draw add their level
+ uint lod;
+};
+
+layout(push_constant) uniform constants {
+ GeometryDraw draw;
+ uint deformOffset;
+ uint jointCount;
+ uint instanceOffset;
+ // With DRAW_DATA the data of a draw is at firstDraw + gl_DrawID, the draws of a multi draw follow each other
+ uint firstDraw;
+#ifdef TRANSLUCENT_PASS
+ // See TranslucentRenderer::PushConstants, 1 without refraction
+ float refractiveIndex;
+ float thickness;
+#endif
+#ifdef MATERIAL_GRAPH
+ uint materialGraphOffset;
+#endif
+} PushConstants;
+
+#ifdef DRAW_DATA
+layout(std430, set = 3, binding = 10) readonly buffer GeometryDraws {
+ GeometryDraw geometryDraws[];
+};
+
+uint drawIdx;
+#define DrawValue(name) geometryDraws[drawIdx].name
+#else
+#define DrawValue(name) PushConstants.draw.name
+#endif
diff --git a/data/shader/deferred/geometry.vsh b/data/shader/deferred/geometry.vsh
index fe7dcd91e..fce7e8748 100644
--- a/data/shader/deferred/geometry.vsh
+++ b/data/shader/deferred/geometry.vsh
@@ -1,5 +1,10 @@
#include <../wind.hsh>
#include <../globals.hsh>
+#include <../common/packing.hsh>
+#include <../common/rotation.hsh>
+#include <../common/texCoord.hsh>
+#include <../common/opacity.hsh>
+#include
// New naming convention:
// Vertex attributes v[Name]
@@ -25,6 +30,18 @@ layout(location=3) in vec4 vTangent;
layout(location=4) in vec4 vVertexColors;
#endif
+#ifdef SKINNED
+layout(location=5) in uvec4 vJoints;
+layout(location=6) in vec4 vWeights;
+#endif
+
+#ifdef TEX_COORDS_1
+layout(location=7) in vec2 vTexCoord1;
+#endif
+
+#ifdef INSTANCE_BUFFER
+#include <../culling/instances.hsh>
+#else
layout(std430, set = 1, binding = 1) readonly buffer CurrentMatrices {
mat3x4 currentMatrices[];
};
@@ -32,6 +49,32 @@ layout(std430, set = 1, binding = 1) readonly buffer CurrentMatrices {
layout(std430, set = 1, binding = 2) readonly buffer LastMatrices {
mat3x4 lastMatrices[];
};
+#endif
+
+#ifdef SKINNED
+layout(std430, set = 1, binding = 4) readonly buffer CurrentJointMatrices {
+ mat3x4 currentJointMatrices[];
+};
+
+layout(std430, set = 1, binding = 5) readonly buffer LastJointMatrices {
+ mat3x4 lastJointMatrices[];
+};
+#endif
+
+#ifdef SOFT_BODY
+// Positions with the packed normal in w, each instance has the offset of its vertices
+layout(std430, set = 1, binding = 24) readonly buffer CurrentSoftBodyVertices {
+ vec4 currentSoftBodyVertices[];
+};
+
+layout(std430, set = 1, binding = 25) readonly buffer LastSoftBodyVertices {
+ vec4 lastSoftBodyVertices[];
+};
+
+layout(std430, set = 1, binding = 26) readonly buffer SoftBodyVertexOffsets {
+ uint softBodyVertexOffsets[];
+};
+#endif
// Vertex out parameters
layout(location=0) out vec3 positionVS;
@@ -51,61 +94,151 @@ layout(location=5) out vec4 vertexColorsVS;
layout(location=7) out mat3 TBN;
#endif
-layout(set = 3, binding = 8) uniform sampler2D windNoiseMap;
+#ifdef MATERIAL_GRAPH_SURFACE
+layout(location=10) out vec3 objectPositionVS;
+layout(location=11) out vec3 instancePositionVS;
+layout(location=12) out vec3 objectNormalVS;
+#endif
-layout(push_constant) uniform constants {
- uint vegetation;
- uint invertUVs;
- uint twoSided;
- uint staticMesh;
- uint materialIdx;
- float normalScale;
- float displacementScale;
- float windTextureLod;
- float windBendScale;
- float windWiggleScale;
- float uvAnimationX;
- float uvAnimationY;
- float uvTiling;
- uint baseColorTextureIdx;
- uint opacityTextureIdx;
- uint normalTextureIdx;
- uint roughnessTextureIdx;
- uint metalnessTextureIdx;
- uint aoTextureIdx;
- uint heightTextureIdx;
- uint emissiveTextureIdx;
-} PushConstants;
+layout(location=13) flat out uint lodVS;
+#ifdef DRAW_DATA
+layout(location=14) flat out uint drawIdxVS;
+#endif
+
+layout(set = 3, binding = 8) uniform sampler2D windNoiseMap;
// Functions
void main() {
+#ifdef DRAW_DATA
+ drawIdx = PushConstants.firstDraw + uint(gl_DrawID);
+ drawIdxVS = drawIdx;
+ lodVS = PushConstants.draw.lod + DrawValue(lod);
+#else
+ lodVS = PushConstants.draw.lod + uint(gl_DrawID);
+#endif
+
+#ifdef INSTANCE_BUFFER
+ uint instanceIdx = instanceIndices[gl_InstanceIndex];
+ mat4 mMatrix = GetInstanceMatrix(instanceIdx);
+ mat4 mMatrixLast = DrawValue(staticMesh) > 0 ? mMatrix : GetLastInstanceMatrix(instanceIdx);
+#else
mat4 mMatrix = mat4(transpose(currentMatrices[gl_InstanceIndex]));
- mat4 mMatrixLast = PushConstants.staticMesh > 0 ? mMatrix : mat4(transpose(lastMatrices[gl_InstanceIndex]));
+ mat4 mMatrixLast = DrawValue(staticMesh) > 0 ? mMatrix : mat4(transpose(lastMatrices[gl_InstanceIndex]));
+#endif
#ifdef TEX_COORDS
- texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord;
- texCoordVS += vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY) * globalData.time;
- texCoordVS *= PushConstants.uvTiling;
+ texCoordVS = TransformTexCoord(vTexCoord, DrawValue(invertUVs) > 0,
+ vec2(DrawValue(uvAnimationX), DrawValue(uvAnimationY)), DrawValue(uvTiling));
#endif
mat4 mvMatrix = globalData.vMatrix * mMatrix;
vec3 position = vPosition;
vec3 lastPosition = vPosition;
+ vec3 normal = vNormal.xyz;
+#if defined(NORMAL_MAP) || defined(HEIGHT_MAP)
+ vec3 tangent = vTangent.xyz;
+#endif
- if (PushConstants.vegetation > 0) {
+#ifdef SKINNED
+ uint jointOffset = PushConstants.deformOffset + (gl_InstanceIndex - PushConstants.instanceOffset) * PushConstants.jointCount;
+ vec4 weights = vWeights / dot(vWeights, vec4(1.0));
- // This is not well optimized and could use some work
- vec3 windPosition = vec3(mMatrix * vec4(position, 1.0));
- vec2 windDir = normalize((inverse(mMatrix) * vec4(globalData.windDir.x, 0.0, globalData.windDir.y, 0.0)).xz);
- position = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale,
- PushConstants.windWiggleScale, PushConstants.windTextureLod, globalData.time, windPosition);
- lastPosition = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale,
- PushConstants.windWiggleScale, PushConstants.windTextureLod,
- globalData.time - globalData.deltaTime, windPosition);
+ mat3x4 skinMatrix = weights.x * currentJointMatrices[jointOffset + vJoints.x] +
+ weights.y * currentJointMatrices[jointOffset + vJoints.y] +
+ weights.z * currentJointMatrices[jointOffset + vJoints.z] +
+ weights.w * currentJointMatrices[jointOffset + vJoints.w];
+ mat3x4 lastSkinMatrix = weights.x * lastJointMatrices[jointOffset + vJoints.x] +
+ weights.y * lastJointMatrices[jointOffset + vJoints.y] +
+ weights.z * lastJointMatrices[jointOffset + vJoints.z] +
+ weights.w * lastJointMatrices[jointOffset + vJoints.w];
+ position = vec4(vPosition, 1.0) * skinMatrix;
+ lastPosition = vec4(vPosition, 1.0) * lastSkinMatrix;
+ normal = vec4(normal, 0.0) * skinMatrix;
+#if defined(NORMAL_MAP) || defined(HEIGHT_MAP)
+ tangent = vec4(tangent, 0.0) * skinMatrix;
+#endif
+#endif
+
+#ifdef SOFT_BODY
+ uint softBodyVertex = softBodyVertexOffsets[PushConstants.deformOffset + gl_InstanceIndex -
+ PushConstants.instanceOffset] + gl_VertexIndex;
+ vec4 softBodyCurrent = currentSoftBodyVertices[softBodyVertex];
+ position = softBodyCurrent.xyz;
+ lastPosition = lastSoftBodyVertices[softBodyVertex].xyz;
+ normal = unpackUnitVector(floatBitsToInt(softBodyCurrent.w)).xyz;
+#if defined(NORMAL_MAP) || defined(HEIGHT_MAP)
+ // Turned like the normal, so it stays along the surface while the cloth turns
+ tangent = RotateLike(tangent, normalize(vNormal.xyz), normal);
+#endif
+#endif
+
+#ifdef MATERIAL_GRAPH
+ vec2 graphTexCoord = vec2(0.0);
+ vec2 graphTexCoord1 = vec2(0.0);
+ vec3 graphTangent = vec3(1.0, 0.0, 0.0);
+ vec4 graphColor = vec4(1.0);
+#ifdef TEX_COORDS
+ graphTexCoord = texCoordVS;
+#endif
+#ifdef TEX_COORDS_1
+ graphTexCoord1 = DrawValue(invertUVs) > 0 ? vec2(vTexCoord1.x, 1.0 - vTexCoord1.y) : vTexCoord1;
+#endif
+#ifdef TANGENTS
+ graphTangent = vTangent.xyz;
+#endif
+#ifdef VERTEX_COLORS
+ graphColor = vVertexColors;
+#endif
+
+ MaterialVertexInput graphInput = CreateMaterialVertexInput(vPosition, position, normal, graphTangent, graphTexCoord, graphTexCoord1,
+ graphColor, mMatrix, globalData.time, PushConstants.materialGraphOffset);
+
+#ifdef MATERIAL_GRAPH_VERTEX_OPACITY
+ // The opacity is the same for the whole draw, moving all vertices outside the view keeps fragments free of discards
+#ifdef TRANSLUCENT_PASS
+ if (EvaluateMaterialOpacity(graphInput) <= 0.0) {
+#else
+ if (EvaluateMaterialOpacity(graphInput) < opacityCutoff) {
+#endif
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ return;
}
+#endif
+
+ WriteMaterialVaryings(graphInput);
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ // Patterns stay on the surface when it moves
+ objectPositionVS = vPosition;
+ instancePositionVS = vec3(mMatrix[3]);
+#endif
+
+#ifdef MATERIAL_GRAPH_VERTEX_OFFSET
+ normal = EvaluateMaterialVertexNormal(graphInput);
+ position += EvaluateMaterialVertexOffset(graphInput);
+
+ graphInput = CreateMaterialVertexInput(vPosition, lastPosition, graphInput.normal, graphTangent, graphTexCoord, graphTexCoord1,
+ graphColor, mMatrixLast, globalData.time - globalData.deltaTime, PushConstants.materialGraphOffset);
+ lastPosition += EvaluateMaterialVertexOffset(graphInput);
+#endif
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ objectNormalVS = normal;
+#endif
+#endif
+
+#ifdef VEGETATION
+ vec3 windPosition = vec3(mMatrix * vec4(position, 1.0));
+ vec2 windDir = GetWindDirection(mMatrix);
+ position = WindAnimation(windNoiseMap, position, windDir, DrawValue(windBendScale),
+ DrawValue(windWiggleScale), DrawValue(windTextureLod), globalData.time, windPosition);
+ lastPosition = WindAnimation(windNoiseMap, lastPosition, windDir, DrawValue(windBendScale),
+ DrawValue(windWiggleScale), DrawValue(windTextureLod),
+ globalData.time - globalData.deltaTime, windPosition);
+#endif
vec4 positionToCamera = mvMatrix * vec4(position, 1.0);
positionVS = positionToCamera.xyz;
@@ -127,18 +260,18 @@ void main() {
mat3 cofactorMatrix = mat3(cross(modelView[1], modelView[2]),
cross(modelView[2], modelView[0]), cross(modelView[0], modelView[1]));
float orientation = dot(modelView[0], cofactorMatrix[0]) < 0.0 ? -1.0 : 1.0;
- normalVS = orientation * (cofactorMatrix * vNormal.xyz);
+ normalVS = orientation * (cofactorMatrix * normal);
#if defined(NORMAL_MAP) || defined(HEIGHT_MAP)
- vec3 normal = normalize(normalVS);
- float correctionFactor = orientation * vTangent.w * (PushConstants.invertUVs > 0 ? 1.0 : -1.0);
- vec3 tangent = mat3(mvMatrix) * vTangent.xyz;
- tangent = normalize(tangent - normal * dot(tangent, normal));
+ vec3 normalView = normalize(normalVS);
+ float correctionFactor = orientation * vTangent.w * (DrawValue(invertUVs) > 0 ? 1.0 : -1.0);
+ vec3 tangentView = mat3(mvMatrix) * tangent;
+ tangentView = normalize(tangentView - normalView * dot(tangentView, normalView));
vec3 bitangent = normalize(correctionFactor *
- cross(tangent, normal));
+ cross(tangentView, normalView));
- TBN = mat3(tangent, bitangent, normal);
+ TBN = mat3(tangentView, bitangent, normalView);
#endif
#ifdef VERTEX_COLORS
diff --git a/data/shader/deferred/indirectDiffuse.csh b/data/shader/deferred/indirectDiffuse.csh
index c213b793c..f659f2efc 100644
--- a/data/shader/deferred/indirectDiffuse.csh
+++ b/data/shader/deferred/indirectDiffuse.csh
@@ -10,6 +10,9 @@
layout (local_size_x = 8, local_size_y = 8) in;
+// Needs the work group size
+#include <../common/upsample.hsh>
+
layout(set = 3, binding = 0, rgba16f) uniform image2D image;
layout(set = 3, binding = 1) uniform sampler2D giTexture;
layout(set = 3, binding = 2) uniform sampler2D lowResDepthTexture;
@@ -31,18 +34,10 @@ shared float depths[36];
shared vec3 normals[36];
shared vec4 gi[36];
-const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2);
-const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2;
-
void LoadGroupSharedData() {
- ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1);
-
- // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y
- if (gl_LocalInvocationIndex < depthDataSize) {
- ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize);
- offset += workGroupOffset;
- offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0));
+ ivec2 offset;
+ if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) {
depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r);
vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg);
@@ -57,40 +52,6 @@ void LoadGroupSharedData() {
}
-const ivec2 offsets[9] = ivec2[9](
- ivec2(-1, -1),
- ivec2(0, -1),
- ivec2(1, -1),
- ivec2(-1, 0),
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(-1, 1),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-const ivec2 pixelOffsets[4] = ivec2[4](
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-int NearestDepth(float referenceDepth, float[9] depthVec) {
-
- int idx = 0;
- float nearest = distance(referenceDepth, depthVec[0]);
- for (int i = 1; i < 9; i++) {
- float dist = distance(referenceDepth, depthVec[i]);
- if (dist < nearest) {
- nearest = dist;
- idx = i;
- }
- }
- return idx;
-
-}
-
float GetPixelEdgeWeight(int sharedMemoryOffset, float referenceDepth, vec3 referenceNormal) {
float depth = depths[sharedMemoryOffset];
@@ -163,8 +124,8 @@ void main() {
if (Uniforms.giDownsampled2x > 0 || Uniforms.reflectionDownsampled2x > 0) LoadGroupSharedData();
- if (gl_GlobalInvocationID.x > imageSize(image).x ||
- gl_GlobalInvocationID.y > imageSize(image).y)
+ if (gl_GlobalInvocationID.x >= imageSize(image).x ||
+ gl_GlobalInvocationID.y >= imageSize(image).y)
return;
ivec2 resolution = imageSize(image);
diff --git a/data/shader/deferred/indirectSpecular.csh b/data/shader/deferred/indirectSpecular.csh
index 3389a3810..5d972e5f7 100644
--- a/data/shader/deferred/indirectSpecular.csh
+++ b/data/shader/deferred/indirectSpecular.csh
@@ -2,6 +2,7 @@
#include <../brdf/brdfEval.hsh>
#include <../common/flatten.hsh>
+#include <../common/stencil.hsh>
#ifdef DDGI
#include <../ddgi/ddgi.hsh>
@@ -9,11 +10,18 @@
layout (local_size_x = 8, local_size_y = 8) in;
+// Needs the work group size
+#include <../common/upsample.hsh>
+
layout(set = 3, binding = 0, rgba16f) uniform image2D image;
layout(set = 3, binding = 1) uniform sampler2D reflectionTexture;
layout(set = 3, binding = 2) uniform sampler2D giTexture;
layout(set = 3, binding = 3) uniform sampler2D lowResDepthTexture;
layout(set = 3, binding = 4) uniform sampler2D lowResNormalTexture;
+#ifdef SEPARATE_REFLECTION
+// Where the reflections start, the ocean or a translucent surface in front of the G-buffer
+layout(set = 3, binding = 6) uniform sampler2D reflectionDepthTexture;
+#endif
layout(set = 3, binding = 5) uniform UniformBuffer {
int reflectionDownsampled2x;
@@ -33,18 +41,10 @@ shared vec3 normals[36];
shared float aos[36];
shared vec3 reflections[36];
-const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2);
-const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2;
-
void LoadGroupSharedData() {
- ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1);
-
- // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y
- if (gl_LocalInvocationIndex < depthDataSize) {
- ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize);
- offset += workGroupOffset;
- offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0));
+ ivec2 offset;
+ if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) {
depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r);
vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg);
@@ -63,40 +63,6 @@ void LoadGroupSharedData() {
}
-const ivec2 offsets[9] = ivec2[9](
- ivec2(-1, -1),
- ivec2(0, -1),
- ivec2(1, -1),
- ivec2(-1, 0),
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(-1, 1),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-const ivec2 pixelOffsets[4] = ivec2[4](
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-int NearestDepth(float referenceDepth, float[9] depthVec) {
-
- int idx = 0;
- float nearest = distance(referenceDepth, depthVec[0]);
- for (int i = 1; i < 9; i++) {
- float dist = distance(referenceDepth, depthVec[i]);
- if (dist < nearest) {
- nearest = dist;
- idx = i;
- }
- }
- return idx;
-
-}
-
float UpsampleAo2x(float referenceDepth) {
ivec2 pixel = ivec2(gl_LocalInvocationID) / 2 + ivec2(1);
@@ -128,7 +94,7 @@ float GetPixelEdgeWeight(int sharedMemoryOffset, float referenceDepth, vec3 refe
return depthWeight * normalWeight;
}
-UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float referenceRoughness, vec2 highResPixel) {
+UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, vec2 highResPixel) {
UpsampleResult result;
@@ -167,7 +133,7 @@ UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float refere
result.ao /= totalWeight;
float maxWeight = 0.0;
- int maxMemoryIdx = 0;
+ int maxMemoryIdx = Flatten2D(pixel, unflattenedDepthDataSize);
for (uint i = 0; i < 9; i++) {
int sharedMemoryOffset = Flatten2D(pixel + offsets[i], unflattenedDepthDataSize);
@@ -178,7 +144,8 @@ UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float refere
}
}
- if (totalWeight < maxWeight && referenceRoughness > 0.01) {
+ // Only fall back to the most similar neighbor when the bilinear footprint is rejected
+ if (totalWeight <= 0.05 * maxWeight) {
result.ao = aos[maxMemoryIdx];
result.reflection = reflections[maxMemoryIdx];
}
@@ -194,8 +161,8 @@ void main() {
if (Uniforms.giDownsampled2x > 0 || Uniforms.reflectionDownsampled2x > 0) LoadGroupSharedData();
- if (gl_GlobalInvocationID.x > imageSize(image).x ||
- gl_GlobalInvocationID.y > imageSize(image).y)
+ if (gl_GlobalInvocationID.x >= imageSize(image).x ||
+ gl_GlobalInvocationID.y >= imageSize(image).y)
return;
ivec2 resolution = imageSize(image);
@@ -219,7 +186,7 @@ void main() {
vec3 worldNormal = normalize(vec3(globalData.ivMatrix * vec4(surface.N, 0.0)));
vec3 geometryWorldNormal = normalize(vec3(globalData.ivMatrix * vec4(geometryNormal, 0.0)));
- upsampleResult = Upsample(depth, surface.N, surface.material.roughness, vec2(pixel));
+ upsampleResult = Upsample(depth, surface.N, vec2(pixel));
// Indirect specular BRDF
vec3 R = normalize(mat3(globalData.ivMatrix) * reflect(-surface.V, surface.N));
@@ -231,6 +198,11 @@ void main() {
#ifdef REFLECTION
vec3 indirectSpecular = Uniforms.reflectionDownsampled2x > 0 ? upsampleResult.reflection : textureLod(reflectionTexture, texCoord, 0.0).rgb;
+#ifdef SEPARATE_REFLECTION
+ // Behind the surface the reflections were traced from, the probe reflects
+ if (texelFetch(reflectionDepthTexture, pixel, 0).r < depth)
+ indirectSpecular = prefilteredSpecular;
+#endif
#else
#ifdef DDGI
vec3 indirectSpecular = IsInsideVolume(worldPosition) ? vec3(0.0) : prefilteredSpecular;
@@ -245,7 +217,7 @@ void main() {
// This normally only accounts for diffuse occlusion, we need seperate terms
// for diffuse and specular.
#ifdef SSGI
- float ao = Uniforms.giDownsampled2x > 0 ? upsampleResult.ao : texelFetch(giTexture, pixel, 0).r;
+ float ao = Uniforms.giDownsampled2x > 0 ? upsampleResult.ao : texelFetch(giTexture, pixel, 0).a;
indirect *= vec3(pow(ao, Uniforms.aoStrength));
#endif
diff --git a/data/shader/deferred/lightCulling.csh b/data/shader/deferred/lightCulling.csh
index 24193c19a..0c31c07ca 100644
--- a/data/shader/deferred/lightCulling.csh
+++ b/data/shader/deferred/lightCulling.csh
@@ -36,8 +36,13 @@ void main() {
float depth = texelFetch(depthTexture, pixel, 0).r;
float viewDepth = ConvertDepthToViewSpaceDepth(depth);
+ // Translucent surfaces are in front of the opaque ones, their tiles reach from the near plane
if (gl_LocalInvocationIndex == 0u) {
+#ifdef FROM_NEAR_PLANE
+ sharedDepthMin = floatBitsToUint(0.0);
+#else
sharedDepthMin = floatBitsToUint(depth);
+#endif
sharedDepthMax = floatBitsToUint(depth);
depthMask = 0;
}
@@ -115,10 +120,14 @@ void main() {
}
int shiftCount = 31 - endBin + startBin;
- int downShift = (0xFFFFFFFF >> shiftCount);
+ int downShift = int(0xFFFFFFFFu >> uint(shiftCount));
int lightMask = downShift << startBin;
+#ifdef FROM_NEAR_PLANE
+ if (visible) {
+#else
if (visible && (lightMask & depthMask) != 0) {
+#endif
atomicOr(sharedLightBuckets[lightBucketIdx], 1 << lightBuckedBit);
}
}
diff --git a/data/shader/deferred/sss.csh b/data/shader/deferred/sss.csh
index 081a28885..0b0a6411f 100644
--- a/data/shader/deferred/sss.csh
+++ b/data/shader/deferred/sss.csh
@@ -24,14 +24,6 @@ layout(push_constant) uniform constants {
int jitter;
} pushConstants;
-float EdgeFadeOut(vec2 screenPos, float fadeDist) {
-
- screenPos = abs(screenPos * 2.0 - 1.0);
- vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist;
- return saturate(1.0 - max(fadeOut.x, fadeOut.y));
-
-}
-
vec2 PosToUV(vec3 pos) {
vec4 clipSpace = globalData.pMatrix * vec4(pos, 1.0);
@@ -45,11 +37,17 @@ void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
ivec2 resolution = imageSize(image);
- if (pixel.x > resolution.x ||
- pixel.y > resolution.y)
+ if (pixel.x >= resolution.x ||
+ pixel.y >= resolution.y)
return;
float depth = texelFetch(depthTexture, pixel, 0).r;
+ // Sky pixels don't read the shadows
+ if (depth == 1.0) {
+ imageStore(image, pixel, vec4(1.0));
+ return;
+ }
+
vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg);
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
diff --git a/data/shader/deferred/texture.hsh b/data/shader/deferred/texture.hsh
index c225188af..54d44f9c6 100644
--- a/data/shader/deferred/texture.hsh
+++ b/data/shader/deferred/texture.hsh
@@ -1,40 +1,9 @@
#include <../globals.hsh>
-#ifndef BINDLESS_TEXTURES
-#ifdef BASE_COLOR_MAP
-layout(set = 3, binding = 0) uniform sampler2D baseColorMap;
-#endif
-#ifdef OPACITY_MAP
-layout(set = 3, binding = 1) uniform sampler2D opacityMap;
-#endif
-#ifdef NORMAL_MAP
-layout(set = 3, binding = 2) uniform sampler2D normalMap;
-#endif
-#ifdef ROUGHNESS_MAP
-layout(set = 3, binding = 3) uniform sampler2D roughnessMap;
-#endif
-#ifdef METALNESS_MAP
-layout(set = 3, binding = 4) uniform sampler2D metalnessMap;
-#endif
-#ifdef AO_MAP
-layout(set = 3, binding = 5) uniform sampler2D aoMap;
-#endif
-#ifdef HEIGHT_MAP
-layout(set = 3, binding = 6) uniform sampler2D heightMap;
-#endif
-#ifdef EMISSIVE_MAP
-layout(set = 3, binding = 7) uniform sampler2D emissiveMap;
-#endif
-#endif
-
vec3 SampleBaseColor(vec2 texCoords, uint textureID, float bias) {
#ifdef BASE_COLOR_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb;
-#else
- return texture(baseColorMap, texCoords, bias).rgb;
-#endif
#else
return vec3(1.0);
#endif
@@ -44,11 +13,7 @@ vec3 SampleBaseColor(vec2 texCoords, uint textureID, float bias) {
float SampleOpacity(vec2 texCoords, uint textureID, float bias) {
#ifdef OPACITY_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r;
-#else
- return texture(opacityMap, texCoords, bias).r;
-#endif
#else
return 1.0;
#endif
@@ -58,11 +23,7 @@ float SampleOpacity(vec2 texCoords, uint textureID, float bias) {
vec3 SampleNormal(vec2 texCoords, uint textureID, float bias) {
#ifdef NORMAL_MAP
-#ifdef BINDLESS_TEXTURES
return 2.0 * texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb - 1.0;
-#else
- return 2.0 * texture(normalMap, texCoords, bias).rgb - 1.0;
-#endif
#else
return vec3(0.0);
#endif
@@ -72,11 +33,7 @@ vec3 SampleNormal(vec2 texCoords, uint textureID, float bias) {
float SampleRoughness(vec2 texCoords, uint textureID, float bias) {
#ifdef ROUGHNESS_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r;
-#else
- return texture(roughnessMap, texCoords, bias).r;
-#endif
#else
return 1.0;
#endif
@@ -86,11 +43,7 @@ float SampleRoughness(vec2 texCoords, uint textureID, float bias) {
float SampleMetalness(vec2 texCoords, uint textureID, float bias) {
#ifdef METALNESS_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r;
-#else
- return texture(metalnessMap, texCoords, bias).r;
-#endif
#else
return 0.0;
#endif
@@ -100,11 +53,7 @@ float SampleMetalness(vec2 texCoords, uint textureID, float bias) {
float SampleAo(vec2 texCoords, uint textureID, float bias) {
#ifdef AO_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r;
-#else
- return texture(aoMap, texCoords, bias).r;
-#endif
#else
return 1.0;
#endif
@@ -114,11 +63,7 @@ float SampleAo(vec2 texCoords, uint textureID, float bias) {
float SampleHeight(vec2 texCoords, uint textureID, vec2 ddx, vec2 ddy) {
#ifdef HEIGHT_MAP
-#ifdef BINDLESS_TEXTURES
return textureGrad(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, ddx, ddy).r;
-#else
- return textureGrad(heightMap, texCoords, ddx, ddy).r;
-#endif
#else
return 0.0;
#endif
@@ -128,11 +73,7 @@ float SampleHeight(vec2 texCoords, uint textureID, vec2 ddx, vec2 ddy) {
vec3 SampleEmissive(vec2 texCoords, uint textureID, float bias) {
#ifdef EMISSIVE_MAP
-#ifdef BINDLESS_TEXTURES
return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb;
-#else
- return texture(emissiveMap, texCoords, bias).rgb;
-#endif
#else
return vec3(0.0);
#endif
diff --git a/data/shader/example/compute.csh b/data/shader/example/compute.csh
index 8d8f745a2..64bc852a7 100644
--- a/data/shader/example/compute.csh
+++ b/data/shader/example/compute.csh
@@ -14,8 +14,8 @@ const float noiseScale = 0.1;
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(image).x ||
- pixel.y > imageSize(image).y)
+ if (pixel.x >= imageSize(image).x ||
+ pixel.y >= imageSize(image).y)
return;
// Load the color from the image
diff --git a/data/shader/exposure/histogram.csh b/data/shader/exposure/histogram.csh
index a02b931d8..ad138f017 100644
--- a/data/shader/exposure/histogram.csh
+++ b/data/shader/exposure/histogram.csh
@@ -32,7 +32,7 @@ void main() {
barrier();
- ivec2 pixel = ivec2(gl_GlobalInvocationID);
+ ivec2 pixel = 2 * ivec2(gl_GlobalInvocationID);
if (pixel.x < textureSize(hdrTexture, 0).x &&
pixel.y < textureSize(hdrTexture, 0).y) {
diff --git a/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h b/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h
index 790219b44..b964ca275 100644
--- a/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h
+++ b/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h
@@ -238,7 +238,7 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp;
layout (set = 1, binding = FSR2_BIND_UAV_DILATED_MOTION_VECTORS, rg16f) writeonly uniform image2D rw_dilated_motion_vectors;
#endif
#if defined FSR2_BIND_UAV_DILATED_DEPTH
- layout (set = 1, binding = FSR2_BIND_UAV_DILATED_DEPTH, r16f) writeonly uniform image2D rw_dilatedDepth;
+ layout (set = 1, binding = FSR2_BIND_UAV_DILATED_DEPTH, r32f) writeonly uniform image2D rw_dilatedDepth;
#endif
#if defined FSR2_BIND_UAV_INTERNAL_UPSCALED
layout (set = 1, binding = FSR2_BIND_UAV_INTERNAL_UPSCALED, rgba16f) writeonly uniform image2D rw_internal_upscaled_color;
@@ -253,7 +253,7 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp;
layout(set = 1, binding = FSR2_BIND_UAV_NEW_LOCKS, r8) uniform image2D rw_new_locks;
#endif
#if defined FSR2_BIND_UAV_PREPARED_INPUT_COLOR
- layout (set = 1, binding = FSR2_BIND_UAV_PREPARED_INPUT_COLOR, rgba16) writeonly uniform image2D rw_prepared_input_color;
+ layout (set = 1, binding = FSR2_BIND_UAV_PREPARED_INPUT_COLOR, rgba16f) writeonly uniform image2D rw_prepared_input_color;
#endif
#if defined FSR2_BIND_UAV_LUMA_HISTORY
layout (set = 1, binding = FSR2_BIND_UAV_LUMA_HISTORY, rgba8) uniform image2D rw_luma_history;
@@ -281,10 +281,10 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp;
#endif
#if defined FSR2_BIND_UAV_AUTOREACTIVE
- layout(set = 1, binding = FSR2_BIND_UAV_AUTOREACTIVE, r32f) uniform image2D rw_output_autoreactive;
+ layout(set = 1, binding = FSR2_BIND_UAV_AUTOREACTIVE, r8) uniform image2D rw_output_autoreactive;
#endif
#if defined FSR2_BIND_UAV_AUTOCOMPOSITION
- layout(set = 1, binding = FSR2_BIND_UAV_AUTOCOMPOSITION, r32f) uniform image2D rw_output_autocomposition;
+ layout(set = 1, binding = FSR2_BIND_UAV_AUTOCOMPOSITION, r8) uniform image2D rw_output_autocomposition;
#endif
#if defined FSR2_BIND_UAV_PREV_PRE_ALPHA_COLOR
layout(set = 1, binding = FSR2_BIND_UAV_PREV_PRE_ALPHA_COLOR, r11f_g11f_b10f) uniform image2D rw_output_prev_color_pre_alpha;
diff --git a/data/shader/fsr2/ffx_spd.h b/data/shader/fsr2/ffx_spd.h
index 5ce24ec87..630fa0b28 100644
--- a/data/shader/fsr2/ffx_spd.h
+++ b/data/shader/fsr2/ffx_spd.h
@@ -332,6 +332,8 @@ void SpdDownsampleMip_2(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI
#else
FfxFloat32x4 v = SpdLoadIntermediate(x, y);
v = SpdReduceQuad(v);
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
// quad index 0 stores result
if (localInvocationIndex % 4 == 0)
{
@@ -367,16 +369,19 @@ void SpdDownsampleMip_3(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI
SpdStoreIntermediate(x * 4 + y, y * 4, v);
}
#else
+ FfxFloat32x4 v = FfxFloat32x4(0);
if (localInvocationIndex < 64)
{
- FfxFloat32x4 v = SpdLoadIntermediate(x * 2 + y % 2, y * 2);
- v = SpdReduceQuad(v);
- // quad index 0 stores result
- if (localInvocationIndex % 4 == 0)
- {
- SpdStore(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
- SpdStoreIntermediate(x * 2 + y / 2, y * 2, v);
- }
+ v = SpdLoadIntermediate(x * 2 + y % 2, y * 2);
+ v = SpdReduceQuad(v);
+ }
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
+ // quad index 0 stores result
+ if (localInvocationIndex < 64 && localInvocationIndex % 4 == 0)
+ {
+ SpdStore(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
+ SpdStoreIntermediate(x * 2 + y / 2, y * 2, v);
}
#endif
}
@@ -400,16 +405,19 @@ void SpdDownsampleMip_4(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI
SpdStoreIntermediate(x + y * 2, 0, v);
}
#else
+ FfxFloat32x4 v = FfxFloat32x4(0);
if (localInvocationIndex < 16)
{
- FfxFloat32x4 v = SpdLoadIntermediate(x * 4 + y, y * 4);
- v = SpdReduceQuad(v);
- // quad index 0 stores result
- if (localInvocationIndex % 4 == 0)
- {
- SpdStore(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
- SpdStoreIntermediate(x / 2 + y, 0, v);
- }
+ v = SpdLoadIntermediate(x * 4 + y, y * 4);
+ v = SpdReduceQuad(v);
+ }
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
+ // quad index 0 stores result
+ if (localInvocationIndex < 16 && localInvocationIndex % 4 == 0)
+ {
+ SpdStore(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
+ SpdStoreIntermediate(x / 2 + y, 0, v);
}
#endif
}
@@ -743,6 +751,8 @@ void SpdDownsampleMip_2H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU
#else
FfxFloat16x4 v = SpdLoadIntermediateH(x, y);
v = SpdReduceQuadH(v);
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
// quad index 0 stores result
if (localInvocationIndex % 4 == 0)
{
@@ -778,16 +788,19 @@ void SpdDownsampleMip_3H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU
SpdStoreIntermediateH(x * 4 + y, y * 4, v);
}
#else
+ FfxFloat16x4 v = FfxFloat16x4(0);
if (localInvocationIndex < 64)
{
- FfxFloat16x4 v = SpdLoadIntermediateH(x * 2 + y % 2, y * 2);
- v = SpdReduceQuadH(v);
- // quad index 0 stores result
- if (localInvocationIndex % 4 == 0)
- {
- SpdStoreH(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
- SpdStoreIntermediateH(x * 2 + y / 2, y * 2, v);
- }
+ v = SpdLoadIntermediateH(x * 2 + y % 2, y * 2);
+ v = SpdReduceQuadH(v);
+ }
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
+ // quad index 0 stores result
+ if (localInvocationIndex < 64 && localInvocationIndex % 4 == 0)
+ {
+ SpdStoreH(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
+ SpdStoreIntermediateH(x * 2 + y / 2, y * 2, v);
}
#endif
}
@@ -811,16 +824,19 @@ void SpdDownsampleMip_4H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU
SpdStoreIntermediateH(x + y * 2, 0, v);
}
#else
+ FfxFloat16x4 v = FfxFloat16x4(0);
if (localInvocationIndex < 16)
{
- FfxFloat16x4 v = SpdLoadIntermediateH(x * 4 + y, y * 4);
- v = SpdReduceQuadH(v);
- // quad index 0 stores result
- if (localInvocationIndex % 4 == 0)
- {
- SpdStoreH(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
- SpdStoreIntermediateH(x / 2 + y, 0, v);
- }
+ v = SpdLoadIntermediateH(x * 4 + y, y * 4);
+ v = SpdReduceQuadH(v);
+ }
+ // The other quads have to read their values before the results overwrite them
+ SpdWorkgroupShuffleBarrier();
+ // quad index 0 stores result
+ if (localInvocationIndex < 16 && localInvocationIndex % 4 == 0)
+ {
+ SpdStoreH(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice);
+ SpdStoreIntermediateH(x / 2 + y, 0, v);
}
#endif
}
diff --git a/data/shader/gbuffer/downsampleGBuffer2x.csh b/data/shader/gbuffer/downsampleGBuffer2x.csh
index 505fd7a09..84e29306b 100644
--- a/data/shader/gbuffer/downsampleGBuffer2x.csh
+++ b/data/shader/gbuffer/downsampleGBuffer2x.csh
@@ -13,8 +13,8 @@ layout (set = 3, binding = 4) uniform sampler2D velocityIn;
layout (set = 3, binding = 5) uniform usampler2D materialIdxIn;
layout (set = 3, binding = 6, r32f) writeonly uniform image2D depthOut;
-layout (set = 3, binding = 7, rgba16f) writeonly uniform image2D normalOut;
-layout (set = 3, binding = 8, rgba16f) writeonly uniform image2D geometryNormalOut;
+layout (set = 3, binding = 7, rg16f) writeonly uniform image2D normalOut;
+layout (set = 3, binding = 8, rg16f) writeonly uniform image2D geometryNormalOut;
layout (set = 3, binding = 9, rgba8) writeonly uniform image2D roughnessMetallicAoOut;
layout (set = 3, binding = 10, rg16f) writeonly uniform image2D velocityOut;
layout (set = 3, binding = 11, r16ui) writeonly uniform uimage2D materialIdxOut;
@@ -105,23 +105,23 @@ void main() {
imageStore(depthOut, coord, vec4(depth, 0.0, 0.0, 1.0));
#ifndef DEPTH_ONLY
- vec3 normal00 = texelFetch(normalIn, coord * 2 + ivec2(0, 0), 0).rgb;
- vec3 normal10 = texelFetch(normalIn, coord * 2 + ivec2(1, 0), 0).rgb;
- vec3 normal01 = texelFetch(normalIn, coord * 2 + ivec2(0, 1), 0).rgb;
- vec3 normal11 = texelFetch(normalIn, coord * 2 + ivec2(1, 1), 0).rgb;
+ vec2 normal00 = texelFetch(normalIn, coord * 2 + ivec2(0, 0), 0).rg;
+ vec2 normal10 = texelFetch(normalIn, coord * 2 + ivec2(1, 0), 0).rg;
+ vec2 normal01 = texelFetch(normalIn, coord * 2 + ivec2(0, 1), 0).rg;
+ vec2 normal11 = texelFetch(normalIn, coord * 2 + ivec2(1, 1), 0).rg;
- vec3 normal = depthIdx < 2 ? (depthIdx < 1 ? normal00 : normal10) :
+ vec2 normal = depthIdx < 2 ? (depthIdx < 1 ? normal00 : normal10) :
(depthIdx < 3 ? normal01 : normal11);
- imageStore(normalOut, coord, vec4(normal, 1.0));
+ imageStore(normalOut, coord, vec4(normal, 0.0, 0.0));
- vec3 geometryNormal00 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 0), 0).rgb;
- vec3 geometryNormal10 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 0), 0).rgb;
- vec3 geometryNormal01 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 1), 0).rgb;
- vec3 geometryNormal11 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 1), 0).rgb;
+ vec2 geometryNormal00 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 0), 0).rg;
+ vec2 geometryNormal10 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 0), 0).rg;
+ vec2 geometryNormal01 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 1), 0).rg;
+ vec2 geometryNormal11 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 1), 0).rg;
- vec3 geometryNormal = depthIdx < 2 ? (depthIdx < 1 ? geometryNormal00 : geometryNormal10) :
+ vec2 geometryNormal = depthIdx < 2 ? (depthIdx < 1 ? geometryNormal00 : geometryNormal10) :
(depthIdx < 3 ? geometryNormal01 : geometryNormal11);
- imageStore(geometryNormalOut, coord, vec4(geometryNormal, 1.0));
+ imageStore(geometryNormalOut, coord, vec4(geometryNormal, 0.0, 0.0));
vec3 roughnessMetallicAo00 = texelFetch(roughnessMetallicAoIn, coord * 2 + ivec2(0, 0), 0).rgb;
vec3 roughnessMetallicAo10 = texelFetch(roughnessMetallicAoIn, coord * 2 + ivec2(1, 0), 0).rgb;
diff --git a/data/shader/gbuffer/generateReactiveMask.csh b/data/shader/gbuffer/generateReactiveMask.csh
index 237539962..d7a4ddf36 100644
--- a/data/shader/gbuffer/generateReactiveMask.csh
+++ b/data/shader/gbuffer/generateReactiveMask.csh
@@ -5,6 +5,15 @@ layout (local_size_x = 8, local_size_y = 8) in;
layout (set = 3, binding = 0, r8) uniform image2D reactiveMaskImage;
layout (set = 3, binding = 1) uniform usampler2D stencilTexture;
layout (set = 3, binding = 2) uniform sampler2D roughnessMetalnessAoTexture;
+layout (set = 3, binding = 3) uniform usampler2D lastStencilTexture;
+layout (set = 3, binding = 4) uniform sampler2D velocityTexture;
+#ifdef TRANSLUCENCY
+layout (set = 3, binding = 5) uniform sampler2D translucencyTexture;
+#endif
+
+layout(push_constant) uniform constants {
+ int hasHistory;
+} pushConstants;
void main() {
@@ -22,6 +31,20 @@ void main() {
vec3 roughnessMetallicAo = texelFetch(roughnessMetalnessAoTexture, pixel, 0).rgb;
float reflectiveReactivity = min(1.0, 5.0 * roughnessMetallicAo.r);
reactivity = max(reactivity, mix(0.5, 0.0, reflectiveReactivity));
+#ifdef TRANSLUCENCY
+ // Blended surfaces don't move with the velocity of what is behind them
+ reactivity = max(reactivity, 0.9 * texelFetch(translucencyTexture, pixel, 0).r);
+#endif
+
+ bool rejectHistory = features.noTemporalAccumulation;
+ if (pushConstants.hasHistory > 0) {
+ vec2 uv = (vec2(pixel) + 0.5) / vec2(size) + texelFetch(velocityTexture, pixel, 0).rg;
+ ivec2 historyPixel = clamp(ivec2(uv * vec2(size)), ivec2(0), size - 1);
+ StencilFeatures historyFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, historyPixel, 0).r);
+ StencilFeatures previousFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, pixel, 0).r);
+ rejectHistory = rejectHistory || historyFeatures.noTemporalAccumulation || previousFeatures.noTemporalAccumulation;
+ }
+ reactivity = rejectHistory ? 1.0 : reactivity;
imageStore(reactiveMaskImage, pixel, vec4(reactivity, 0.0, 0.0, 0.0));
diff --git a/data/shader/gbuffer/hiz.csh b/data/shader/gbuffer/hiz.csh
new file mode 100644
index 000000000..4a6d3535d
--- /dev/null
+++ b/data/shader/gbuffer/hiz.csh
@@ -0,0 +1,111 @@
+// Hierarchical depth with the closest depth in r and the farthest depth plus the thickness in g.
+// Each work group reduces a 32x32 block of the input and writes up to six levels.
+
+#include <../globals.hsh>
+
+layout (local_size_x = 16, local_size_y = 16) in;
+
+layout(set = 3, binding = 0) uniform sampler2D depthIn;
+layout(set = 3, binding = 1, rg32f) readonly uniform image2D levelIn;
+
+layout(set = 3, binding = 2, rg32f) writeonly uniform image2D levelOut0;
+layout(set = 3, binding = 3, rg32f) writeonly uniform image2D levelOut1;
+layout(set = 3, binding = 4, rg32f) writeonly uniform image2D levelOut2;
+layout(set = 3, binding = 5, rg32f) writeonly uniform image2D levelOut3;
+layout(set = 3, binding = 6, rg32f) writeonly uniform image2D levelOut4;
+layout(set = 3, binding = 7, rg32f) writeonly uniform image2D levelOut5;
+
+layout(push_constant) uniform constants {
+ ivec2 inputSize;
+ int fromDepth;
+ int levelCount;
+ float distanceThickness;
+} pushConstants;
+
+shared vec2 sharedMinMax[16][16];
+
+vec2 FetchTexel(ivec2 texel) {
+
+ if (any(greaterThanEqual(texel, pushConstants.inputSize)))
+ return vec2(1.0);
+
+ if (pushConstants.fromDepth > 0) {
+ float depth = texelFetch(depthIn, texel, 0).r;
+ if (depth >= 1.0 || pushConstants.distanceThickness <= 0.0)
+ return vec2(depth);
+
+ vec2 viewSpace = (globalData.ipMatrix * vec4(0.0, 0.0, depth, 1.0)).zw;
+ float viewZ = viewSpace.x / viewSpace.y;
+ viewZ -= pushConstants.distanceThickness * min(-viewZ, 500.0);
+ vec4 clipSpace = globalData.pMatrix * vec4(0.0, 0.0, viewZ, 1.0);
+ return vec2(depth, clipSpace.z / clipSpace.w);
+ }
+
+ return imageLoad(levelIn, texel).rg;
+
+}
+
+vec2 Combine(vec2 a, vec2 b) {
+
+ return vec2(min(a.x, b.x), max(a.y, b.y));
+
+}
+
+void Store(int level, ivec2 texel, vec2 value) {
+
+ if (level >= pushConstants.levelCount)
+ return;
+
+ if (level == 0) imageStore(levelOut0, texel, vec4(value, 0.0, 0.0));
+ else if (level == 1) imageStore(levelOut1, texel, vec4(value, 0.0, 0.0));
+ else if (level == 2) imageStore(levelOut2, texel, vec4(value, 0.0, 0.0));
+ else if (level == 3) imageStore(levelOut3, texel, vec4(value, 0.0, 0.0));
+ else if (level == 4) imageStore(levelOut4, texel, vec4(value, 0.0, 0.0));
+ else if (level == 5) imageStore(levelOut5, texel, vec4(value, 0.0, 0.0));
+
+}
+
+void main() {
+
+ ivec2 pixel = ivec2(gl_LocalInvocationID);
+ ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) * 2;
+
+ // When reading the depth texture, the input is level 0
+ ivec2 coord = workGroupOffset + 2 * pixel;
+ vec2 depth00 = FetchTexel(coord);
+ vec2 depth10 = FetchTexel(coord + ivec2(1, 0));
+ vec2 depth01 = FetchTexel(coord + ivec2(0, 1));
+ vec2 depth11 = FetchTexel(coord + ivec2(1, 1));
+
+ int level = 0;
+ if (pushConstants.fromDepth > 0) {
+ Store(0, coord, depth00);
+ Store(0, coord + ivec2(1, 0), depth10);
+ Store(0, coord + ivec2(0, 1), depth01);
+ Store(0, coord + ivec2(1, 1), depth11);
+ level = 1;
+ }
+
+ vec2 value = Combine(Combine(depth00, depth10), Combine(depth01, depth11));
+ Store(level, ivec2(gl_WorkGroupID.xy) * 16 + pixel, value);
+ sharedMinMax[pixel.y][pixel.x] = value;
+
+ int size = 16;
+ for (int i = 1; i < 5; i++) {
+ barrier();
+
+ size /= 2;
+ if (all(lessThan(pixel, ivec2(size)))) {
+ ivec2 texel = 2 * pixel;
+ value = Combine(Combine(sharedMinMax[texel.y][texel.x], sharedMinMax[texel.y][texel.x + 1]),
+ Combine(sharedMinMax[texel.y + 1][texel.x], sharedMinMax[texel.y + 1][texel.x + 1]));
+ Store(level + i, ivec2(gl_WorkGroupID.xy) * size + pixel, value);
+ }
+
+ barrier();
+
+ if (all(lessThan(pixel, ivec2(size))))
+ sharedMinMax[pixel.y][pixel.x] = value;
+ }
+
+}
diff --git a/data/shader/gbuffer/patchGBuffer.csh b/data/shader/gbuffer/patchGBuffer.csh
index 86d7174d5..62a0501cd 100644
--- a/data/shader/gbuffer/patchGBuffer.csh
+++ b/data/shader/gbuffer/patchGBuffer.csh
@@ -3,7 +3,7 @@
layout (local_size_x = 8, local_size_y = 8) in;
layout (set = 3, binding = 0, rg16f) uniform image2D normalImage;
-layout (set = 3, binding = 1, rgba16f) uniform image2D roughnessMetalnessAoImage;
+layout (set = 3, binding = 1, rgba8) uniform image2D roughnessMetalnessAoImage;
layout (set = 3, binding = 2) uniform sampler2D geometryNormalTexture;
layout (set = 3, binding = 3) uniform usampler2D materialIdxTexture;
diff --git a/data/shader/globals.hsh b/data/shader/globals.hsh
index 7fab7c58c..5edd8506e 100644
--- a/data/shader/globals.hsh
+++ b/data/shader/globals.hsh
@@ -1,12 +1,7 @@
-#ifdef AE_BINDLESS
+// Has to match the counts in graphics/Common.h
#define TEXTURE_COUNT 16384
#define CUBEMAP_COUNT 1024
#define TEXTURE_ARRAY_COUNT 128
-#else
-#define TEXTURE_COUNT 1
-#define CUBEMAP_COUNT 1
-#define TEXTURE_ARRAY_COUNT 1
-#endif
layout(set = 1, binding = 31, std140) uniform GlobalBuffer {
vec4 frustumPlanes[6];
@@ -36,6 +31,13 @@ layout(set = 1, binding = 31, std140) uniform GlobalBuffer {
float mipLodBias;
float cameraNearPlane;
float cameraFarPlane;
+ // Exposure the lighting buffers are stored with, keeps strong physical lights within the limits of the GI
+ float preExposure;
+ float lastPreExposure;
+ // A loaded sky cubemap doesn't carry the pre-exposure, a generated one does
+ float skyCubemapExposure;
+ // Colors meshes by their level of detail
+ uint debugMeshLods;
} globalData;
layout(set = 0, binding = 3) uniform texture2D bindlessTextures[TEXTURE_COUNT];
diff --git a/data/shader/impostor/depthOffset.hsh b/data/shader/impostor/depthOffset.hsh
new file mode 100644
index 000000000..6db00c781
--- /dev/null
+++ b/data/shader/impostor/depthOffset.hsh
@@ -0,0 +1,7 @@
+// The bake stores the distance in front of the billboard plane plus one, texels without geometry stay zero. Filtered
+// texels at the silhouette mix both, divided by their coverage (the alpha of the base color) they are restored
+float ImpostorDepthOffset(float depth, float alpha) {
+
+ return depth / max(alpha, 1e-3) - 1.0;
+
+}
diff --git a/data/shader/impostor/generate.fsh b/data/shader/impostor/generate.fsh
index ffe7d8754..d7ebf258f 100644
--- a/data/shader/impostor/generate.fsh
+++ b/data/shader/impostor/generate.fsh
@@ -1,4 +1,5 @@
#include <../common/random.hsh>
+#include <../common/opacity.hsh>
layout (location = 0) out vec4 baseColorFS;
layout (location = 1) out vec3 normalFS;
@@ -112,7 +113,7 @@ void main() {
#ifdef OPACITY_MAP
float opacity = texture(opacityMap, texCoords).r;
- if (opacity < 0.2)
+ if (opacity < opacityCutoff)
discard;
#endif
@@ -123,21 +124,18 @@ void main() {
baseColorFS *= PushConstants.baseColor;
- vec3 geometryNormalFS = normalize(normalVS);
+ vec3 geometryNormal = normalize(normalVS);
+ // We want the normal always to face the camera for two sided materials
+ vec3 facingGeometryNormal = geometryNormal * (PushConstants.twoSided > 0 && dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0);
#ifdef NORMAL_MAP
vec3 normalColor = texture(normalMap, texCoords).rgb;
- normalFS = mix(geometryNormalFS, normalize(TBN * (2.0 * normalColor - 1.0)), PushConstants.normalScale);
- // We want the normal always to face the camera for two sided materials
- geometryNormalFS *= PushConstants.twoSided > 0 ? dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0 : 1.0;
- normalFS = 0.5 * normalFS + 0.5;
+ vec3 normal = normalize(mix(geometryNormal, normalize(TBN * (2.0 * normalColor - 1.0)), PushConstants.normalScale));
+ normal *= dot(facingGeometryNormal, normal) < 0.0 ? -1.0 : 1.0;
+ normalFS = 0.5 * normal + 0.5;
#else
- // We want the normal always to face the camera for two sided materials
- geometryNormalFS *= PushConstants.twoSided > 0 ? dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0 : 1.0;
+ normalFS = 0.5 * facingGeometryNormal + 0.5;
#endif
-
- geometryNormalFS = 0.5 * geometryNormalFS + 0.5;
- normalFS = geometryNormalFS;
float roughnessFactor = PushConstants.roughness;
float metalnessFactor = PushConstants.metalness;
diff --git a/data/shader/impostor/impostor.fsh b/data/shader/impostor/impostor.fsh
index b399840b1..fcec389e1 100644
--- a/data/shader/impostor/impostor.fsh
+++ b/data/shader/impostor/impostor.fsh
@@ -1,5 +1,6 @@
#include <../globals.hsh>
#include <../common/normalencode.hsh>
+#include
layout (location = 0) out vec4 baseColorFS;
layout (location = 1) out vec2 normalFS;
@@ -28,7 +29,7 @@ layout(location=4) flat in int indexVS;
#ifdef PIXEL_DEPTH_OFFSET
layout(location=10) in vec3 modelPositionVS;
-layout(location=11) flat in vec3 instanceScale;
+layout(location=11) in float depthScale;
#endif
layout(location=12) flat in mat3 rotationMatrix;
@@ -37,10 +38,6 @@ layout(set = 3, binding = 1) uniform sampler2DArray roughnessMetalnessAoMap;
layout(set = 3, binding = 2) uniform sampler2DArray normalMap;
layout(set = 3, binding = 3) uniform sampler2DArray depthMap;
-layout(std430, set = 1, binding = 2) buffer Matrices {
- mat4 matrices[];
-};
-
layout(set = 3, binding = 5, std140) uniform UniformBuffer{
vec4 center;
@@ -127,13 +124,14 @@ void main() {
float depth1 = texture(depthMap, vec3(texCoordVS, float(index1VS)), uniforms.mipBias + globalData.mipLodBias).r;
float depth2 = texture(depthMap, vec3(texCoordVS, float(index2VS)), uniforms.mipBias + globalData.mipLodBias).r;
- float depthOffset = weight0VS * depth0 +
- weight1VS * depth1 +
- weight2VS * depth2;
+ // Decoded together, views without the surface at this texel would push the depth back
+ float depthOffset = ImpostorDepthOffset(weight0VS * depth0 + weight1VS * depth1 + weight2VS * depth2, baseColor.a);
#else
- float depthOffset = texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias + globalData.mipLodBias).r;
+ float depthOffset = ImpostorDepthOffset(texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias + globalData.mipLodBias).r,
+ baseColor.a);
#endif
- vec3 modelPosition = modelPositionVS + depthOffset * -globalData.cameraDirection.xyz * instanceScale;
+ vec3 toCamera = normalize(globalData.cameraLocation.xyz - modelPositionVS);
+ vec3 modelPosition = modelPositionVS + depthOffset * toCamera * depthScale;
vec4 modelPositionFS = globalData.pMatrix * globalData.vMatrix * vec4(modelPosition.xyz, 1.0);
float modelDepth = modelPositionFS.z / modelPositionFS.w;
gl_FragDepth = modelDepth;
diff --git a/data/shader/impostor/impostor.vsh b/data/shader/impostor/impostor.vsh
index 6a8c1dbb9..da3971cbf 100644
--- a/data/shader/impostor/impostor.vsh
+++ b/data/shader/impostor/impostor.vsh
@@ -10,9 +10,7 @@ struct ViewPlane {
vec4 up;
};
-layout(std430, set = 1, binding = 3) readonly buffer Matrices {
- mat3x4 matrices[];
-};
+#include <../culling/instances.hsh>
layout (std430, set = 3, binding = 4) readonly buffer ViewPlanes {
ViewPlane viewPlanes[];
@@ -37,7 +35,7 @@ layout(location=4) flat out int indexVS;
#ifdef PIXEL_DEPTH_OFFSET
layout(location=10) out vec3 modelPositionVS;
-layout(location=11) flat out vec3 instanceScale;
+layout(location=11) out float depthScale;
#endif
layout(location=12) flat out mat3 rotationMatrix;
@@ -75,13 +73,12 @@ vec4 InterpolateTriangle(vec2 coord) {
void main() {
- mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex]));
+ mat4 mMatrix = GetInstanceMatrix(impostorInstanceIndices[gl_InstanceIndex]);
texCoordVS = 0.5 * vPosition + 0.5;
- vec3 translation = vec3(mMatrix[3]);
-
- vec3 pos = translation + uniforms.center.xyz;
- vec3 dir = normalize(vec3(inverse(mMatrix) * vec4(globalData.cameraLocation.xyz - pos, 0.0)));
+ mat4 inverseMatrix = inverse(mMatrix);
+ vec3 pos = vec3(mMatrix * vec4(uniforms.center.xyz, 1.0));
+ vec3 dir = normalize(vec3(inverseMatrix * vec4(globalData.cameraLocation.xyz - pos, 0.0)));
float frames = float(uniforms.views);
@@ -150,11 +147,8 @@ void main() {
rotationMatrix = mat3(mMatrix);
#ifdef PIXEL_DEPTH_OFFSET
modelPositionVS = vec3(modelPosition);
- instanceScale = vec3(
- length(mMatrix[0]),
- length(mMatrix[1]),
- length(mMatrix[2])
- );
+ // The depth is baked along the view direction in model space, this is its length in world space
+ depthScale = 1.0 / length(mat3(inverseMatrix) * normalize(globalData.cameraLocation.xyz - modelPositionVS));
#endif
gl_Position = globalData.pMatrix * vec4(positionVS, 1.0);
diff --git a/data/shader/impostor/impostorShadow.fsh b/data/shader/impostor/impostorShadow.fsh
index f9604bfdc..022f6eabc 100644
--- a/data/shader/impostor/impostorShadow.fsh
+++ b/data/shader/impostor/impostorShadow.fsh
@@ -1,4 +1,5 @@
#include <../globals.hsh>
+#include
layout(location = 0) in vec2 texCoordVS;
#ifdef INTERPOLATION
@@ -14,7 +15,7 @@ layout(location=1) flat in int indexVS;
#endif
#ifdef PIXEL_DEPTH_OFFSET
layout(location=7) in vec3 modelPositionVS;
-layout(location=8) flat in vec3 instanceScale;
+layout(location=8) in float depthScale;
#endif
layout(set = 3, binding = 0) uniform sampler2DArray baseColorMap;
@@ -22,10 +23,6 @@ layout(set = 3, binding = 0) uniform sampler2DArray baseColorMap;
layout(set = 3, binding = 1) uniform sampler2DArray depthMap;
#endif
-layout(std430, set = 1, binding = 3) buffer Matrices {
- mat4 matrices[];
-};
-
layout(set = 3, binding = 3, std140) uniform UniformBuffer{
vec4 center;
@@ -40,8 +37,6 @@ layout(push_constant) uniform constants {
mat4 lightSpaceMatrix;
vec4 lightLocation;
- vec4 lightUp;
- vec4 lightRight;
} pushConstants;
void main() {
@@ -69,13 +64,14 @@ void main() {
float depth1 = texture(depthMap, vec3(texCoordVS, float(index1VS)), uniforms.mipBias).r;
float depth2 = texture(depthMap, vec3(texCoordVS, float(index2VS)), uniforms.mipBias).r;
- float depthOffset = weight0VS * depth0 +
- weight1VS * depth1 +
- weight2VS * depth2;
+ // Decoded together, views without the surface at this texel would push the depth back
+ float depthOffset = ImpostorDepthOffset(weight0VS * depth0 + weight1VS * depth1 + weight2VS * depth2, alpha);
#else
- float depthOffset = texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias).r;
+ float depthOffset = ImpostorDepthOffset(texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias).r, alpha);
#endif
- vec3 modelPosition = modelPositionVS + depthOffset * normalize(pushConstants.lightLocation.xyz) * instanceScale;
+ // Towards a point light or along the directional light (its location lies far away against the direction)
+ vec3 toLight = normalize(pushConstants.lightLocation.xyz - modelPositionVS);
+ vec3 modelPosition = modelPositionVS + depthOffset * toLight * depthScale;
vec4 modelPositionFS = pushConstants.lightSpaceMatrix * vec4(modelPosition.xyz, 1.0);
float modelDepth = modelPositionFS.z / modelPositionFS.w;
gl_FragDepth = modelDepth;
diff --git a/data/shader/impostor/impostorShadow.vsh b/data/shader/impostor/impostorShadow.vsh
index 107edab4d..71ef62880 100644
--- a/data/shader/impostor/impostorShadow.vsh
+++ b/data/shader/impostor/impostorShadow.vsh
@@ -18,7 +18,7 @@ layout(location=1) flat out int indexVS;
#endif
#ifdef PIXEL_DEPTH_OFFSET
layout(location=7) out vec3 modelPositionVS;
-layout(location=8) flat out vec3 instanceScale;
+layout(location=8) out float depthScale;
#endif
struct ViewPlane {
@@ -26,9 +26,7 @@ struct ViewPlane {
vec4 up;
};
-layout(std430, set = 1, binding = 3) readonly buffer Matrices {
- mat3x4 matrices[];
-};
+#include <../culling/instances.hsh>
layout (std430, set = 3, binding = 2) readonly buffer ViewPlanes {
ViewPlane viewPlanes[];
@@ -48,8 +46,6 @@ layout(push_constant) uniform constants {
mat4 lightSpaceMatrix;
vec4 lightLocation;
- vec4 lightUp;
- vec4 lightRight;
} pushConstants;
vec4 InterpolateTriangle(vec2 coord) {
@@ -70,14 +66,13 @@ vec4 InterpolateTriangle(vec2 coord) {
void main() {
- mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex]));
+ mat4 mMatrix = GetInstanceMatrix(impostorInstanceIndices[gl_InstanceIndex]);
texCoordVS = 0.5 * vPosition + 0.5;
- vec3 translation = vec3(mMatrix[3]);
-
- vec3 pos = translation + uniforms.center.xyz;
- vec3 dir = normalize(vec3(inverse(mMatrix) * vec4(pushConstants.lightLocation.xyz - pos, 0.0)));
+ mat4 inverseMatrix = inverse(mMatrix);
+ vec3 pos = vec3(mMatrix * vec4(uniforms.center.xyz, 1.0));
+ vec3 dir = normalize(vec3(inverseMatrix * vec4(pushConstants.lightLocation.xyz - pos, 0.0)));
float frames = float(uniforms.views);
vec2 octahedron = UnitVectorToHemiOctahedron(normalize(dir));
@@ -135,12 +130,9 @@ void main() {
+ normalize(right.xyz) * position.x) + uniforms.center.xyz, 1.0);
#ifdef PIXEL_DEPTH_OFFSET
- instanceScale = vec3(
- length(mMatrix[0]),
- length(mMatrix[1]),
- length(mMatrix[2])
- );
modelPositionVS = vec3(modelPosition);
+ // The depth is baked along the view direction in model space, this is its length in world space
+ depthScale = 1.0 / length(mat3(inverseMatrix) * normalize(pushConstants.lightLocation.xyz - modelPositionVS));
#endif
gl_Position = pushConstants.lightSpaceMatrix * modelPosition;
diff --git a/data/shader/materialGraph/common.hsh b/data/shader/materialGraph/common.hsh
new file mode 100644
index 000000000..a88084125
--- /dev/null
+++ b/data/shader/materialGraph/common.hsh
@@ -0,0 +1,617 @@
+#extension GL_EXT_nonuniform_qualifier : require
+
+// Interface between the geometry and shadow shaders and the code generated from material graphs
+// Only shaders generated from a graph include this file, see materialgraph/Compiler
+
+#include <../globals.hsh>
+#include <../common/opacity.hsh>
+
+#if (defined(MATERIAL_GRAPH_WRITES_NORMAL) || defined(MATERIAL_GRAPH_USES_TANGENTS)) && defined(TANGENTS) && defined(TEX_COORDS) && !defined(NORMAL_MAP)
+#define NORMAL_MAP
+#endif
+
+// Parameter values and bindless texture indices of all graph materials, indexed by the offset of the material
+// Ray tracing passes use binding 9 of set 3 for other resources
+#ifdef MATERIAL_GRAPH_STAGE_HIT
+layout(std430, set = 3, binding = 24) readonly buffer MaterialGraphParameters {
+#else
+layout(std430, set = 3, binding = 9) readonly buffer MaterialGraphParameters {
+#endif
+ uint materialGraphParameters[];
+};
+
+struct MaterialVertexInput {
+ vec3 position;
+ vec3 normal;
+ vec3 tangent;
+ vec3 worldPosition;
+ vec3 worldNormal;
+ vec3 instancePosition;
+ vec3 viewDirection;
+ vec2 texCoord;
+ // Second texture coordinate set, zero for meshes without one
+ vec2 texCoord1;
+ vec4 color;
+ float time;
+ uint parameterOffset;
+ mat4 modelMatrix;
+};
+
+struct MaterialSurfaceInput {
+ vec3 position;
+ vec3 normal;
+ vec3 worldPosition;
+ vec3 worldNormal;
+ vec3 viewPosition;
+ vec3 viewNormal;
+ vec3 instancePosition;
+ vec3 viewDirection;
+ // Tangent to view space
+ mat3 tangentFrame;
+ vec2 texCoord;
+ // Only the vertex stage has the second set, evaluations and ray hits read zero
+ vec2 texCoord1;
+ vec2 screenCoord;
+ vec4 color;
+ float time;
+ float frontFacing;
+ uint parameterOffset;
+#ifdef MATERIAL_GRAPH_STAGE_EVALUATE
+ // Nodes of the vertex stage are calculated per fragment in an evaluation
+ vec3 tangent;
+ mat4 modelMatrix;
+#endif
+};
+
+struct MaterialSurfaceOutput {
+ vec3 baseColor;
+ // In tangent space
+ vec3 normal;
+ vec3 emissive;
+ float roughness;
+ float metalness;
+ float ao;
+ float opacity;
+};
+
+MaterialSurfaceOutput CreateMaterialSurfaceOutput() {
+
+ MaterialSurfaceOutput surface;
+
+ surface.baseColor = vec3(1.0);
+ surface.normal = vec3(0.0, 0.0, 1.0);
+ surface.emissive = vec3(0.0);
+ surface.roughness = 1.0;
+ surface.metalness = 0.0;
+ surface.ao = 1.0;
+ surface.opacity = 1.0;
+
+ return surface;
+
+}
+
+// The object position is the one of the mesh file, on skinned meshes it stays the same while they are animated
+MaterialVertexInput CreateMaterialVertexInput(vec3 objectPosition, vec3 position, vec3 normal, vec3 tangent, vec2 texCoord, vec2 texCoord1,
+ vec4 color, mat4 modelMatrix, float time, uint parameterOffset) {
+
+ MaterialVertexInput vertexIn;
+
+ vertexIn.position = objectPosition;
+ vertexIn.normal = normal;
+ vertexIn.tangent = tangent;
+ vertexIn.worldPosition = vec3(modelMatrix * vec4(position, 1.0));
+ vertexIn.worldNormal = normalize(mat3(modelMatrix) * normal);
+ vertexIn.instancePosition = vec3(modelMatrix[3]);
+ vertexIn.viewDirection = normalize(globalData.cameraLocation.xyz - vertexIn.worldPosition);
+ vertexIn.texCoord = texCoord;
+ vertexIn.texCoord1 = texCoord1;
+ vertexIn.color = color;
+ vertexIn.time = time;
+ vertexIn.parameterOffset = parameterOffset;
+ vertexIn.modelMatrix = modelMatrix;
+
+ return vertexIn;
+
+}
+
+// The same vertex at another position, e.g. to find the normal of the displaced surface
+MaterialVertexInput MoveMaterialVertexInput(MaterialVertexInput vertexIn, vec3 offset) {
+
+ vertexIn.position += offset;
+ vertexIn.worldPosition += mat3(vertexIn.modelMatrix) * offset;
+ vertexIn.viewDirection = normalize(globalData.cameraLocation.xyz - vertexIn.worldPosition);
+
+ return vertexIn;
+
+}
+
+MaterialSurfaceInput CreateMaterialSurfaceInput(vec3 position, vec3 normal, vec3 worldPosition, vec3 worldNormal,
+ vec3 instancePosition, mat3 tangentFrame, vec2 texCoord, vec2 screenCoord, vec4 color, float frontFacing,
+ uint parameterOffset) {
+
+ MaterialSurfaceInput surfaceIn;
+
+ surfaceIn.position = position;
+ surfaceIn.normal = normal;
+ surfaceIn.worldPosition = worldPosition;
+ surfaceIn.worldNormal = worldNormal;
+ surfaceIn.viewPosition = vec3(globalData.vMatrix * vec4(worldPosition, 1.0));
+ surfaceIn.viewNormal = mat3(globalData.vMatrix) * worldNormal;
+ surfaceIn.instancePosition = instancePosition;
+ surfaceIn.viewDirection = normalize(globalData.cameraLocation.xyz - worldPosition);
+ surfaceIn.tangentFrame = tangentFrame;
+ surfaceIn.texCoord = texCoord;
+ surfaceIn.texCoord1 = vec2(0.0);
+ surfaceIn.screenCoord = screenCoord;
+ surfaceIn.color = color;
+ surfaceIn.time = globalData.time;
+ surfaceIn.frontFacing = frontFacing;
+ surfaceIn.parameterOffset = parameterOffset;
+
+ return surfaceIn;
+
+}
+
+float MaterialGraphReadFloat(uint offset) {
+
+ return uintBitsToFloat(materialGraphParameters[offset]);
+
+}
+
+vec2 MaterialGraphReadVec2(uint offset) {
+
+ return vec2(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u));
+
+}
+
+vec3 MaterialGraphReadVec3(uint offset) {
+
+ return vec3(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u), MaterialGraphReadFloat(offset + 2u));
+
+}
+
+vec4 MaterialGraphReadVec4(uint offset) {
+
+ return vec4(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u), MaterialGraphReadFloat(offset + 2u), MaterialGraphReadFloat(offset + 3u));
+
+}
+
+#ifdef MATERIAL_GRAPH_STAGE_HIT
+// Hits have no derivatives, the level comes from the ray tracing pass
+float materialGraphHitTextureLevel = 0.0;
+#endif
+
+// The vertex stage has no derivatives, it always samples the most detailed level
+vec4 MaterialGraphSampleTexture(uint textureIdx, vec2 texCoord) {
+
+#if defined(MATERIAL_GRAPH_STAGE_HIT)
+ return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, materialGraphHitTextureLevel);
+#elif defined(MATERIAL_GRAPH_STAGE_SURFACE)
+ return texture(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, globalData.mipLodBias);
+#else
+ return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, 0.0);
+#endif
+
+}
+
+vec4 MaterialGraphSampleTextureLod(uint textureIdx, vec2 texCoord, float lod) {
+
+ return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, lod);
+
+}
+
+vec3 MaterialGraphSampleNormal(uint textureIdx, vec2 texCoord, float strength) {
+
+ vec3 normal = 2.0 * MaterialGraphSampleTexture(textureIdx, texCoord).rgb - 1.0;
+ normal.xy *= strength;
+ return normalize(normal);
+
+}
+
+vec4 MaterialGraphSampleTriplanar(uint textureIdx, vec3 position, vec3 normal, float scale, float sharpness) {
+
+ vec3 weights = pow(abs(normal), vec3(sharpness));
+ weights /= max(weights.x + weights.y + weights.z, 0.0001);
+
+ return MaterialGraphSampleTexture(textureIdx, position.zy * scale) * weights.x +
+ MaterialGraphSampleTexture(textureIdx, position.xz * scale) * weights.y +
+ MaterialGraphSampleTexture(textureIdx, position.xy * scale) * weights.z;
+
+}
+
+vec3 MaterialGraphSampleTriplanarNormal(uint textureIdx, vec3 position, vec3 normal, float scale, float sharpness, float strength) {
+
+ vec3 weights = pow(abs(normal), vec3(sharpness));
+ weights /= max(weights.x + weights.y + weights.z, 0.0001);
+
+ vec3 normalX = 2.0 * MaterialGraphSampleTexture(textureIdx, position.zy * scale).rgb - 1.0;
+ vec3 normalY = 2.0 * MaterialGraphSampleTexture(textureIdx, position.xz * scale).rgb - 1.0;
+ vec3 normalZ = 2.0 * MaterialGraphSampleTexture(textureIdx, position.xy * scale).rgb - 1.0;
+
+ normalX = vec3(normalX.xy * strength + normal.zy, abs(normalX.z) * normal.x);
+ normalY = vec3(normalY.xy * strength + normal.xz, abs(normalY.z) * normal.y);
+ normalZ = vec3(normalZ.xy * strength + normal.xy, abs(normalZ.z) * normal.z);
+
+ return normalize(normalX.zyx * weights.x + normalY.xzy * weights.y + normalZ * weights.z);
+
+}
+
+vec2 MaterialGraphTextureSize(uint textureIdx) {
+
+ return vec2(textureSize(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), 0));
+
+}
+
+vec3 MaterialGraphMod289(vec3 x) {
+
+ return x - floor(x * (1.0 / 289.0)) * 289.0;
+
+}
+
+vec4 MaterialGraphMod289(vec4 x) {
+
+ return x - floor(x * (1.0 / 289.0)) * 289.0;
+
+}
+
+vec4 MaterialGraphPermute(vec4 x) {
+
+ return MaterialGraphMod289(((x * 34.0) + 10.0) * x);
+
+}
+
+// Simplex noise in the range of -1 to 1
+float MaterialGraphSimplex(vec3 v) {
+
+ const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);
+ const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
+
+ vec3 i = floor(v + dot(v, C.yyy));
+ vec3 x0 = v - i + dot(i, C.xxx);
+
+ vec3 g = step(x0.yzx, x0.xyz);
+ vec3 l = 1.0 - g;
+ vec3 i1 = min(g.xyz, l.zxy);
+ vec3 i2 = max(g.xyz, l.zxy);
+
+ vec3 x1 = x0 - i1 + C.xxx;
+ vec3 x2 = x0 - i2 + C.yyy;
+ vec3 x3 = x0 - D.yyy;
+
+ i = MaterialGraphMod289(i);
+ vec4 p = MaterialGraphPermute(MaterialGraphPermute(MaterialGraphPermute(
+ i.z + vec4(0.0, i1.z, i2.z, 1.0)) +
+ i.y + vec4(0.0, i1.y, i2.y, 1.0)) +
+ i.x + vec4(0.0, i1.x, i2.x, 1.0));
+
+ float n_ = 0.142857142857;
+ vec3 ns = n_ * D.wyz - D.xzx;
+
+ vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
+
+ vec4 x_ = floor(j * ns.z);
+ vec4 y_ = floor(j - 7.0 * x_);
+
+ vec4 x = x_ * ns.x + ns.yyyy;
+ vec4 y = y_ * ns.x + ns.yyyy;
+ vec4 h = 1.0 - abs(x) - abs(y);
+
+ vec4 b0 = vec4(x.xy, y.xy);
+ vec4 b1 = vec4(x.zw, y.zw);
+
+ vec4 s0 = floor(b0) * 2.0 + 1.0;
+ vec4 s1 = floor(b1) * 2.0 + 1.0;
+ vec4 sh = -step(h, vec4(0.0));
+
+ vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
+ vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
+
+ vec3 p0 = vec3(a0.xy, h.x);
+ vec3 p1 = vec3(a0.zw, h.y);
+ vec3 p2 = vec3(a1.xy, h.z);
+ vec3 p3 = vec3(a1.zw, h.w);
+
+ vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3));
+ p0 *= norm.x;
+ p1 *= norm.y;
+ p2 *= norm.z;
+ p3 *= norm.w;
+
+ vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
+ m = m * m;
+ return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
+
+}
+
+float MaterialGraphFractalNoise(vec3 position, float octaves, float lacunarity, float gain) {
+
+ float value = 0.0;
+ float amplitude = 1.0;
+ float amplitudeSum = 0.0;
+
+ int count = clamp(int(octaves), 1, 8);
+ for (int i = 0; i < count; i++) {
+ value += amplitude * MaterialGraphSimplex(position);
+ amplitudeSum += amplitude;
+ amplitude *= gain;
+ position = position * lacunarity + vec3(17.3, -9.1, 4.7);
+ }
+
+ return value / amplitudeSum;
+
+}
+
+// Absolute noise folded into sharp ridges, in the range of 0 to 1
+float MaterialGraphRidgedNoise(vec3 position, float octaves, float lacunarity, float gain) {
+
+ float value = 0.0;
+ float amplitude = 1.0;
+ float amplitudeSum = 0.0;
+
+ int count = clamp(int(octaves), 1, 8);
+ for (int i = 0; i < count; i++) {
+ float ridge = 1.0 - abs(MaterialGraphSimplex(position));
+ value += amplitude * ridge * ridge;
+ amplitudeSum += amplitude;
+ amplitude *= gain;
+ position = position * lacunarity + vec3(17.3, -9.1, 4.7);
+ }
+
+ return value / amplitudeSum;
+
+}
+
+vec3 MaterialGraphHash3(vec3 p) {
+
+ p = vec3(dot(p, vec3(127.1, 311.7, 74.7)), dot(p, vec3(269.5, 183.3, 246.1)), dot(p, vec3(113.5, 271.9, 124.6)));
+ return fract(sin(p) * 43758.5453123);
+
+}
+
+// Distance to the closest feature point in x, to the second closest in y and a random value of the cell in z
+vec3 MaterialGraphVoronoi(vec3 position, float jitter) {
+
+ vec3 cell = floor(position);
+ vec3 local = fract(position);
+
+ float first = 8.0;
+ float second = 8.0;
+ float id = 0.0;
+
+ for (int z = -1; z <= 1; z++) {
+ for (int y = -1; y <= 1; y++) {
+ for (int x = -1; x <= 1; x++) {
+ vec3 offset = vec3(float(x), float(y), float(z));
+ vec3 random = MaterialGraphHash3(cell + offset);
+ vec3 delta = offset + random * jitter - local;
+ float dist = dot(delta, delta);
+ if (dist < first) {
+ second = first;
+ first = dist;
+ id = random.x;
+ }
+ else if (dist < second) {
+ second = dist;
+ }
+ }
+ }
+ }
+
+ return vec3(sqrt(first), sqrt(second), id);
+
+}
+
+float MaterialGraphChecker(vec3 position) {
+
+ vec3 cell = floor(position);
+ return mod(cell.x + cell.y + cell.z, 2.0);
+
+}
+
+vec3 MaterialGraphHueShift(vec3 color, float shift) {
+
+ const vec3 axis = vec3(0.57735);
+ float cosAngle = cos(shift);
+ return color * cosAngle + cross(axis, color) * sin(shift) + axis * dot(axis, color) * (1.0 - cosAngle);
+
+}
+
+vec3 MaterialGraphRotateAxis(vec3 position, vec3 axis, float angle) {
+
+ axis = normalize(axis);
+ float sinAngle = sin(angle);
+ float cosAngle = cos(angle);
+ return position * cosAngle + cross(axis, position) * sinAngle + axis * dot(axis, position) * (1.0 - cosAngle);
+
+}
+
+vec2 MaterialGraphRotateCoord(vec2 coord, vec2 center, float angle) {
+
+ float sinAngle = sin(angle);
+ float cosAngle = cos(angle);
+ coord -= center;
+ return vec2(coord.x * cosAngle - coord.y * sinAngle, coord.x * sinAngle + coord.y * cosAngle) + center;
+
+}
+
+vec2 MaterialGraphPolar(vec2 coord, vec2 center, float radialScale, float angleScale) {
+
+ vec2 delta = coord - center;
+ return vec2(length(delta) * radialScale, (atan(delta.y, delta.x) / 6.28318530718 + 0.5) * angleScale);
+
+}
+
+vec2 MaterialGraphFlipbook(vec2 coord, float columns, float rows, float frame) {
+
+ float index = mod(floor(frame), columns * rows);
+ return (fract(coord) + vec2(mod(index, columns), floor(index / columns))) / vec2(columns, rows);
+
+}
+
+vec2 MaterialGraphTwirl(vec2 coord, vec2 center, float strength) {
+
+ return MaterialGraphRotateCoord(coord, center, length(coord - center) * strength);
+
+}
+
+vec2 MaterialGraphDistort(vec2 coord, float scale, float strength, float seed) {
+
+ vec3 position = vec3(coord * scale, seed);
+ return coord + vec2(MaterialGraphSimplex(position), MaterialGraphSimplex(position + vec3(31.7, 11.3, 5.9))) * strength;
+
+}
+
+float MaterialGraphRemap(float value, float fromMin, float fromMax, float toMin, float toMax) {
+
+ return toMin + (value - fromMin) / (fromMax - fromMin) * (toMax - toMin);
+
+}
+
+vec3 MaterialGraphRamp(float position, vec3 color0, vec3 color1, vec3 color2, float center) {
+
+ return position < center ? mix(color0, color1, clamp(position / max(center, 0.0001), 0.0, 1.0)) :
+ mix(color1, color2, clamp((position - center) / max(1.0 - center, 0.0001), 0.0, 1.0));
+
+}
+
+vec3 MaterialGraphBlendNormals(vec3 a, vec3 b) {
+
+ return normalize(vec3(a.xy + b.xy, a.z * b.z));
+
+}
+
+vec3 MaterialGraphNormalize(vec3 value) {
+
+ float len = length(value);
+ return len > 0.0 ? value / len : value;
+
+}
+
+#if defined(MATERIAL_GRAPH_STAGE_SURFACE) && !defined(MATERIAL_GRAPH_STAGE_HIT)
+// Tangent space normal of a height, which works for procedural values without a tangent frame of the mesh
+vec3 MaterialGraphNormalFromHeight(float height, float strength, vec3 viewPosition, vec3 viewNormal, mat3 tangentFrame) {
+
+ vec3 dpdx = dFdx(viewPosition);
+ vec3 dpdy = dFdy(viewPosition);
+ float dhdx = dFdx(height) * strength;
+ float dhdy = dFdy(height) * strength;
+
+ vec3 normal = normalize(viewNormal);
+ vec3 r1 = cross(dpdy, normal);
+ vec3 r2 = cross(normal, dpdx);
+ float determinant = dot(dpdx, r1);
+
+ // Degenerate triangles, e.g. at the poles of spheres, have no direction
+ if (determinant == 0.0)
+ return vec3(0.0, 0.0, 1.0);
+
+ vec3 gradient = sign(determinant) * (dhdx * r1 + dhdy * r2);
+ vec3 perturbed = normalize(abs(determinant) * normal - gradient);
+
+ return normalize(transpose(tangentFrame) * perturbed);
+
+}
+
+// Each corner of a tile has its own offset, the mip level stays the one of the continuous coordinates
+vec4 MaterialGraphSampleWithoutTiling(uint textureIdx, vec2 coord, float blend) {
+
+ vec2 tile = floor(coord);
+ vec2 weights = smoothstep(vec2(0.5 - 0.5 * blend), vec2(0.5 + 0.5 * blend), fract(coord));
+
+ vec2 ddx = dFdx(coord);
+ vec2 ddy = dFdy(coord);
+
+ vec4 values[4];
+ for (int y = 0; y < 2; y++) {
+ for (int x = 0; x < 2; x++) {
+ vec2 offset = MaterialGraphHash3(vec3(tile + vec2(float(x), float(y)), 3.0)).xy;
+ values[y * 2 + x] = textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coord + offset, ddx, ddy);
+ }
+ }
+
+ return mix(mix(values[0], values[1], weights.x), mix(values[2], values[3], weights.x), weights.y);
+
+}
+
+vec2 MaterialGraphParallax(uint textureIdx, vec2 coord, vec3 viewDirection, float scale, float steps) {
+
+ vec2 ddx = dFdx(coord);
+ vec2 ddy = dFdy(coord);
+
+ int count = clamp(int(steps), 1, 64);
+ float layerDepth = 1.0 / float(count);
+ vec2 delta = viewDirection.xy / max(viewDirection.z, 0.05) * scale * layerDepth;
+
+ vec2 current = coord;
+ float depth = 0.0;
+ float height = 1.0 - textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), current, ddx, ddy).r;
+ float previousHeight = height;
+
+ for (int i = 0; i < count && depth < height; i++) {
+ previousHeight = height;
+ current -= delta;
+ depth += layerDepth;
+ height = 1.0 - textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), current, ddx, ddy).r;
+ }
+
+ float after = height - depth;
+ float before = previousHeight - depth + layerDepth;
+ return mix(current, current + delta, clamp(after / min(after - before, -0.0001), 0.0, 1.0));
+
+}
+
+// Tangent frame from the derivatives, for meshes without tangents
+mat3 MaterialGraphCotangentFrame(vec3 normal, vec3 viewPosition, vec2 texCoord) {
+
+ vec3 dp1 = dFdx(viewPosition);
+ vec3 dp2 = dFdy(viewPosition);
+ vec2 duv1 = dFdx(texCoord);
+ vec2 duv2 = dFdy(texCoord);
+
+ vec3 dp2perp = cross(dp2, normal);
+ vec3 dp1perp = cross(normal, dp1);
+ vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;
+ vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y;
+
+ float scale = max(dot(tangent, tangent), dot(bitangent, bitangent));
+ if (scale <= 0.0) {
+ vec3 up = abs(normal.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
+ tangent = normalize(cross(up, normal));
+ return mat3(tangent, cross(normal, tangent), normal);
+ }
+
+ float invScale = inversesqrt(scale);
+ return mat3(tangent * invScale, bitangent * invScale, normal);
+
+}
+#elif defined(MATERIAL_GRAPH_STAGE_HIT)
+// Without derivatives heights keep the surface flat
+vec3 MaterialGraphNormalFromHeight(float height, float strength, vec3 viewPosition, vec3 viewNormal, mat3 tangentFrame) {
+
+ return vec3(0.0, 0.0, 1.0);
+
+}
+
+vec4 MaterialGraphSampleWithoutTiling(uint textureIdx, vec2 coord, float blend) {
+
+ vec2 tile = floor(coord);
+ vec2 weights = smoothstep(vec2(0.5 - 0.5 * blend), vec2(0.5 + 0.5 * blend), fract(coord));
+
+ vec4 values[4];
+ for (int y = 0; y < 2; y++) {
+ for (int x = 0; x < 2; x++) {
+ vec2 offset = MaterialGraphHash3(vec3(tile + vec2(float(x), float(y)), 3.0)).xy;
+ values[y * 2 + x] = MaterialGraphSampleTexture(textureIdx, coord + offset);
+ }
+ }
+
+ return mix(mix(values[0], values[1], weights.x), mix(values[2], values[3], weights.x), weights.y);
+
+}
+
+vec2 MaterialGraphParallax(uint textureIdx, vec2 coord, vec3 viewDirection, float scale, float steps) {
+
+ return coord;
+
+}
+#endif
diff --git a/data/shader/materialGraph/evaluate.fsh b/data/shader/materialGraph/evaluate.fsh
new file mode 100644
index 000000000..4f22626f1
--- /dev/null
+++ b/data/shader/materialGraph/evaluate.fsh
@@ -0,0 +1,102 @@
+// Included by the shaders generated for evaluating a part of a graph, see materialgraph/Compiler
+
+layout(location=0) in vec3 positionVS;
+layout(location=1) in vec3 normalVS;
+layout(location=2) in vec2 texCoordVS;
+layout(location=3) in vec4 colorVS;
+layout(location=4) in vec4 tangentVS;
+#ifdef EVALUATE_IMPOSTOR
+layout(location=5) in float depthVS;
+#endif
+
+#ifdef EVALUATE_PREVIEW
+layout(location=0) out vec4 colorFS;
+#elif defined(EVALUATE_IMPOSTOR)
+// The layout of the impostor maps, see impostor/generate.fsh
+layout(location=0) out vec4 baseColorFS;
+layout(location=1) out vec3 normalFS;
+layout(location=2) out vec3 roughnessMetalnessAoFS;
+layout(location=3) out float depthFS;
+#else
+layout(location=0) out vec4 baseColorFS;
+layout(location=1) out vec4 normalFS;
+layout(location=2) out vec4 roughnessMetalnessAoFS;
+layout(location=3) out vec4 emissiveFS;
+layout(location=4) out vec4 opacityFS;
+#endif
+
+layout(push_constant) uniform constants {
+#ifdef EVALUATE_IMPOSTOR
+ mat4 vMatrix;
+#endif
+ float time;
+ uint invertUVs;
+#ifdef EVALUATE_IMPOSTOR
+ float distanceToPlaneCenter;
+ uint twoSided;
+#endif
+} PushConstants;
+
+void main() {
+
+ vec3 normal = normalize(normalVS);
+ float frontFacing = 1.0;
+#ifdef EVALUATE_IMPOSTOR
+ frontFacing = gl_FrontFacing ? 1.0 : -1.0;
+ normal *= PushConstants.twoSided > 0 ? frontFacing : 1.0;
+#endif
+
+ // The same frame the geometry pass builds
+ mat3 tangentFrame;
+ if (dot(tangentVS.xyz, tangentVS.xyz) > 0.0) {
+ vec3 tangent = normalize(tangentVS.xyz - normal * dot(tangentVS.xyz, normal));
+ float correctionFactor = tangentVS.w * (PushConstants.invertUVs > 0 ? 1.0 : -1.0);
+ tangentFrame = mat3(tangent, normalize(correctionFactor * cross(tangent, normal)), normal);
+ }
+ else {
+ tangentFrame = MaterialGraphCotangentFrame(normal, positionVS, texCoordVS);
+ }
+
+ MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(positionVS, normal, positionVS, normal, vec3(0.0),
+ tangentFrame, texCoordVS, texCoordVS, colorVS, frontFacing, 0u);
+
+ surfaceIn.time = PushConstants.time;
+#ifdef EVALUATE_IMPOSTOR
+ vec3 cameraLocation = -transpose(mat3(PushConstants.vMatrix)) * PushConstants.vMatrix[3].xyz;
+ surfaceIn.viewDirection = normalize(cameraLocation - positionVS);
+#else
+ // Maps are the same from all directions, so they are made looking straight at the surface
+ surfaceIn.viewDirection = normal;
+#endif
+ surfaceIn.tangent = tangentFrame[0];
+ surfaceIn.modelMatrix = mat4(1.0);
+
+#ifdef EVALUATE_PREVIEW
+ vec4 value = EvaluateMaterialPreview(surfaceIn);
+ colorFS = vec4(pow(clamp(value.rgb, vec3(0.0), vec3(1.0)), vec3(1.0 / 2.2)), 1.0);
+#elif defined(EVALUATE_IMPOSTOR)
+ MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn);
+ if (surface.opacity < opacityCutoff)
+ discard;
+
+ // Impostors store the normal in the space of the mesh, like the geometry pass writes it
+ vec3 surfaceNormal = normalize(tangentFrame * surface.normal);
+ surfaceNormal = any(isnan(surfaceNormal)) ? normal : surfaceNormal * (dot(normal, surfaceNormal) < 0.0 ? -1.0 : 1.0);
+
+ baseColorFS = vec4(surface.baseColor, 1.0);
+ normalFS = 0.5 * surfaceNormal + 0.5;
+ roughnessMetalnessAoFS = vec3(surface.roughness, surface.metalness, surface.ao);
+ depthFS = depthVS;
+#else
+ MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn);
+
+ // The alpha channels mark the texels the mesh covers
+ baseColorFS = vec4(surface.baseColor, 1.0);
+ // Texels of degenerate triangles have no direction
+ normalFS = vec4(any(isnan(surface.normal)) ? vec3(0.0, 0.0, 1.0) : surface.normal, 1.0);
+ roughnessMetalnessAoFS = vec4(surface.roughness, surface.metalness, surface.ao, 1.0);
+ emissiveFS = vec4(surface.emissive, 1.0);
+ opacityFS = vec4(surface.opacity, 0.0, 0.0, 1.0);
+#endif
+
+}
diff --git a/data/shader/materialGraph/evaluate.vsh b/data/shader/materialGraph/evaluate.vsh
new file mode 100644
index 000000000..4d899231a
--- /dev/null
+++ b/data/shader/materialGraph/evaluate.vsh
@@ -0,0 +1,86 @@
+// Evaluates a part of a graph outside of the regular passes, see materialgraph/Evaluator. Either on a plane for the
+// previews of nodes, on a mesh, which is laid out by its texture coordinates to fill maps of it, or on a mesh seen
+// from the views of an impostor
+
+layout(location=0) out vec3 positionVS;
+layout(location=1) out vec3 normalVS;
+layout(location=2) out vec2 texCoordVS;
+layout(location=3) out vec4 colorVS;
+layout(location=4) out vec4 tangentVS;
+#ifdef EVALUATE_IMPOSTOR
+layout(location=5) out float depthVS;
+#endif
+
+#ifdef EVALUATE_MESH
+layout(location=0) in vec3 vPosition;
+layout(location=1) in vec4 vNormal;
+#ifdef TEX_COORDS
+layout(location=2) in vec2 vTexCoord;
+#endif
+#ifdef TANGENTS
+layout(location=3) in vec4 vTangent;
+#endif
+#ifdef VERTEX_COLORS
+layout(location=4) in vec4 vVertexColors;
+#endif
+#else
+layout(location=0) in vec2 vPosition;
+#endif
+
+layout(push_constant) uniform constants {
+#ifdef EVALUATE_IMPOSTOR
+ mat4 vMatrix;
+#endif
+ float time;
+ uint invertUVs;
+#ifdef EVALUATE_IMPOSTOR
+ float distanceToPlaneCenter;
+ uint twoSided;
+#endif
+} PushConstants;
+
+#ifdef EVALUATE_IMPOSTOR
+layout(set = 3, binding = 7, std140) uniform UniformBuffer {
+ mat4 pMatrix;
+} Uniforms;
+#endif
+
+void main() {
+
+ colorVS = vec4(1.0);
+ tangentVS = vec4(0.0);
+
+#ifdef EVALUATE_MESH
+ positionVS = vPosition;
+ normalVS = vNormal.xyz;
+ texCoordVS = vec2(0.0);
+#ifdef TEX_COORDS
+ texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord;
+#endif
+
+#ifdef TANGENTS
+ tangentVS = vTangent;
+#endif
+#ifdef VERTEX_COLORS
+ colorVS = vVertexColors;
+#endif
+
+#ifdef EVALUATE_IMPOSTOR
+ vec4 positionToCamera = PushConstants.vMatrix * vec4(vPosition, 1.0);
+ depthVS = positionToCamera.z + PushConstants.distanceToPlaneCenter;
+ gl_Position = Uniforms.pMatrix * positionToCamera;
+#else
+ // The map is sampled with the coordinates the renderers use, which is what it gets filled with
+ gl_Position = vec4(2.0 * texCoordVS - 1.0, 0.0, 1.0);
+#endif
+#else
+ // A slightly bulged plane, nodes which depend on the normal show something
+ positionVS = vec3(vPosition.x, -vPosition.y, 0.0);
+ normalVS = vec3(0.7 * positionVS.xy, 1.0);
+ texCoordVS = 0.5 * vPosition + 0.5;
+ tangentVS = vec4(1.0, 0.0, 0.0, 1.0);
+
+ gl_Position = vec4(vPosition, 0.0, 1.0);
+#endif
+
+}
diff --git a/data/shader/normalreconstruction.csh b/data/shader/normalreconstruction.csh
index 6726b3412..dd8782c8d 100644
--- a/data/shader/normalreconstruction.csh
+++ b/data/shader/normalreconstruction.csh
@@ -47,8 +47,8 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(normalImage).x ||
- pixel.y > imageSize(normalImage).y)
+ if (pixel.x >= imageSize(normalImage).x ||
+ pixel.y >= imageSize(normalImage).y)
return;
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(normalImage));
diff --git a/data/shader/ocean/butterfly.csh b/data/shader/ocean/butterfly.csh
deleted file mode 100644
index cabcb3ab4..000000000
--- a/data/shader/ocean/butterfly.csh
+++ /dev/null
@@ -1,77 +0,0 @@
-#include <../common/PI.hsh>
-#include <../common/complex.hsh>
-
-layout (local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
-
-layout (set = 3, binding = 0, rg32f) readonly uniform image2D twiddleIndicesTexture;
-
-layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray pingpong0;
-layout (set = 3, binding = 2, rgba32f) writeonly uniform image2DArray pingpong1;
-
-layout(push_constant) uniform constants {
- int stage;
- int pingpong;
- int N;
- float preTwiddle;
-} PushConstants;
-
-void horizontal();
-void vertical();
-
-void main() {
-
-#ifdef HORIZONTAL
- horizontal();
-#endif
-#ifdef VERTICAL
- vertical();
-#endif
-
-}
-
-void horizontal() {
-
- int spectrumIdx = int(gl_GlobalInvocationID.z);
- ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
-
- float k = mod(float(coord.x) * PushConstants.preTwiddle, float(PushConstants.N));
- float twiddleArgument = 2.0 * PI * k / float(PushConstants.N);
- vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument));
-
- vec2 twiddle = imageLoad(twiddleIndicesTexture, ivec2(PushConstants.stage, coord.x)).rg;
-
- vec4 s1 = imageLoad(pingpong0, ivec3(twiddle.x, coord.y, spectrumIdx));
- vec4 t1 = imageLoad(pingpong0, ivec3(twiddle.y, coord.y, spectrumIdx));
-
- vec4 u1 = vec4(twiddleFactor.x, twiddleFactor.y,
- twiddleFactor.x, twiddleFactor.y);
-
- vec4 H1 = s1 + mul(u1, t1);
-
- imageStore(pingpong1, ivec3(gl_GlobalInvocationID.xyz), H1);
-
-}
-
-void vertical() {
-
- int spectrumIdx = int(gl_GlobalInvocationID.z);
- ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
-
- float k = mod(float(coord.y) * PushConstants.preTwiddle, float(PushConstants.N));
- float twiddleArgument = 2.0 * PI * k / float(PushConstants.N);
- vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument));
-
- vec2 twiddle = imageLoad(twiddleIndicesTexture, ivec2(PushConstants.stage, coord.y)).rg;
-
- vec4 s1 = imageLoad(pingpong0, ivec3(coord.x, twiddle.x, spectrumIdx));
- vec4 t1 = imageLoad(pingpong0, ivec3(coord.x, twiddle.y, spectrumIdx));
-
- vec4 u1 = vec4(twiddleFactor.x, twiddleFactor.y,
- twiddleFactor.x, twiddleFactor.y);
-
- vec4 H1 = s1 + mul(u1, t1);
-
- imageStore(pingpong1, ivec3(gl_GlobalInvocationID.xyz), H1);
-
-
-}
\ No newline at end of file
diff --git a/data/shader/ocean/caustics.csh b/data/shader/ocean/caustics.csh
index 5c813050a..b413d294c 100644
--- a/data/shader/ocean/caustics.csh
+++ b/data/shader/ocean/caustics.csh
@@ -39,8 +39,8 @@ const float fadeoutFalloff = 0.2;
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(refractionImage).x ||
- pixel.y > imageSize(refractionImage).y)
+ if (pixel.x >= imageSize(refractionImage).x ||
+ pixel.y >= imageSize(refractionImage).y)
return;
Light light = LightUniforms.light;
diff --git a/data/shader/ocean/common.hsh b/data/shader/ocean/common.hsh
index 0f62430d3..b95322ffd 100644
--- a/data/shader/ocean/common.hsh
+++ b/data/shader/ocean/common.hsh
@@ -42,24 +42,23 @@ vec3 GetOceanDisplacement(vec3 position, float dist, out float perlinScale,
vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances);
if (Uniforms.spectrumCount > 0 && fade[0] > 0.0) {
- displacement0 = textureLod(displacementMap, vec3(texCoord / tilingFactors[0], 0.0), 0.0).grb * spectrumScaling.x;
+ displacement0 = textureLod(displacementMap, vec3(texCoord / tilingFactors[0], 0.0), 0.0).rgb * spectrumScaling.x;
displacement0 *= fade[0];
}
if (Uniforms.spectrumCount > 1 && fade[1] > 0.0) {
- displacement1 = textureLod(displacementMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0), 0.0).grb * spectrumScaling.y;
+ displacement1 = textureLod(displacementMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0), 0.0).rgb * spectrumScaling.y;
displacement1 *= fade[1];
}
if (Uniforms.spectrumCount > 2 && fade[2] > 0.0) {
- displacement2 = textureLod(displacementMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0), 0.0).grb * spectrumScaling.z;
+ displacement2 = textureLod(displacementMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0), 0.0).rgb * spectrumScaling.z;
displacement2 *= fade[2];
}
if (Uniforms.spectrumCount > 3 && fade[3] > 0.0) {
- displacement3 = textureLod(displacementMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0), 0.0).grb * spectrumScaling.w;
+ displacement3 = textureLod(displacementMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0), 0.0).rgb * spectrumScaling.w;
displacement3 *= fade[3];
}
- float weightSum = dot(vec4(1.0), spectrumScaling);
- vec3 displacement = (displacement0 + displacement1 + displacement2 + displacement3) / weightSum;
+ vec3 displacement = displacement0 + displacement1 + displacement2 + displacement3;
displacement.y *= Uniforms.displacementScale * shoreScale;
displacement.x *= Uniforms.choppyScale * shoreScale;
displacement.z *= Uniforms.choppyScale * shoreScale;
@@ -81,43 +80,3 @@ vec3 GetOceanDisplacement(vec3 position, float dist, out float perlinScale,
return displacement;
}
-
-void GetOceanGradientAndFold(vec2 texCoord, float dist, out float fold, out vec2 gradient) {
-
- texCoord /= Uniforms.tiling;
-
- vec4 tilingFactors = Uniforms.spectrumTilingFactors;
- vec4 fadeoutDistances = Uniforms.spectrumFadeoutDistances;
-
- vec4 data0 = vec4(0.0), data1 = vec4(0.0), data2 = vec4(0.0), data3 = vec4(0.0);
-
- vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances);
- if (Uniforms.spectrumCount > 0 && fade[0] > 0.0) {
- data0 = texture(normalMap, vec3(texCoord / tilingFactors[0], 0.0));
- data0 *= fade[0];
- }
- if (Uniforms.spectrumCount > 1 && fade[1] > 0.0) {
- data1 = texture(normalMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0));
- data1 *= fade[1];
- }
- if (Uniforms.spectrumCount > 2 && fade[2] > 0.0) {
- data2 = texture(normalMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0));
- data2 *= fade[2];
- }
- if (Uniforms.spectrumCount > 3 && fade[3] > 0.0) {
- data3 = texture(normalMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0));
- data3 *= fade[3];
- }
-
- float perlin = textureLod(perlinNoiseMap, texCoord * 0.125 * 0.125, 0.0).r;
- float perlinScale = sqr(clamp(perlin, 0.0, 1.0));
-
- float weightSum = dot(vec4(1.0), spectrumScaling);
- fold = saturate(10.0 * ((data0.a + data1.a + data2.a + data3.a) / weightSum));
- gradient = ((data0.rg) + (data1.rg)
- + (data2.rg) + (data3.rg));
-
- //fold *= perlinScale;
- //gradient *= perlinScale;
-
-}
\ No newline at end of file
diff --git a/data/shader/ocean/depth.fsh b/data/shader/ocean/depth.fsh
index bc62a6e90..b089e3764 100644
--- a/data/shader/ocean/depth.fsh
+++ b/data/shader/ocean/depth.fsh
@@ -2,7 +2,20 @@
#include <../common/stencil.hsh>
#include <../globals.hsh>
+#include
+#include
+
+layout (location = 0) in vec3 fOriginalCoord;
+layout (location = 1) in float shoreScaling;
+#ifdef TERRAIN
+layout (location = 2) in vec3 normalShoreWave;
+#endif
+
+layout (set = 3, binding = 5) uniform sampler2D depthTexture;
+
layout (location = 0) out uint stencil;
+// Encoded view space normal, the ray origins for the reflections
+layout (location = 1) out vec2 normal;
void main() {
@@ -23,6 +36,23 @@ void main() {
features.waterPixel = true;
+ // Only the visible surface needs a normal, the depth is still needed below the scene
+ normal = vec2(0.0);
+ if (gl_FragCoord.z <= texelFetch(depthTexture, ivec2(gl_FragCoord.xy), 0).r) {
+ float fold, jacobian, slopeVariance;
+ vec2 gradient;
+ float viewDistance = distance(fOriginalCoord, globalData.cameraLocation.xyz);
+ GetOceanGradientAndFold(fOriginalCoord.xz, viewDistance, fold, gradient, jacobian, slopeVariance);
+
+ // The reflections treat the water surface as a perfect mirror
+ vec3 worldNormal = normalize(vec3(gradient.x, 1.0, gradient.y));
+#ifdef TERRAIN
+ worldNormal = mix(normalShoreWave, worldNormal, shoreScaling);
+#endif
+ worldNormal = GetOceanRippleNormal(worldNormal, fOriginalCoord.xz, shoreScaling);
+ normal = EncodeNormal(normalize(vec3(globalData.vMatrix * vec4(worldNormal, 0.0))));
+ }
+
// Remember that the ocean stencil has only 8 bits, need to be careful about the features
// and their bit order.
stencil = EncodeStencilFeatures(features);
diff --git a/data/shader/ocean/depth.vsh b/data/shader/ocean/depth.vsh
index efc2f1259..5605432e5 100644
--- a/data/shader/ocean/depth.vsh
+++ b/data/shader/ocean/depth.vsh
@@ -7,6 +7,12 @@
layout(location=0) in vec3 vPosition;
+layout(location=0) out vec3 fOriginalCoord;
+layout(location=1) out float shoreScaling;
+#ifdef TERRAIN
+layout(location=2) out vec3 normalShoreWave;
+#endif
+
vec3 stitch(vec3 position) {
// Note: This only works because our grid has a constant size
@@ -42,10 +48,13 @@ void main() {
vec3(PushConstants.nodeLocation.x, 0.0, PushConstants.nodeLocation.y)
+ Uniforms.translation.xyz;
+ fOriginalCoord = fPosition;
float distanceToCamera = distance(fPosition.xyz, globalData.cameraLocation.xyz);
- float perlinScale, shoreScaling;
+#ifndef TERRAIN
vec3 normalShoreWave;
+#endif
+ float perlinScale;
fPosition += GetOceanDisplacement(fPosition, distanceToCamera, perlinScale, shoreScaling, normalShoreWave);
vec3 position = vec3(globalData.vMatrix * vec4(fPosition, 1.0));
diff --git a/data/shader/ocean/fft.csh b/data/shader/ocean/fft.csh
new file mode 100644
index 000000000..78f4c1da4
--- /dev/null
+++ b/data/shader/ocean/fft.csh
@@ -0,0 +1,193 @@
+#include <../common/PI.hsh>
+#include <../common/complex.hsh>
+
+layout (local_size_x = FFT_SIZE / 2, local_size_y = 1, local_size_z = 1) in;
+
+#ifdef HORIZONTAL
+layout (set = 3, binding = 0, rgba32f) writeonly uniform image2DArray hTD;
+layout (set = 3, binding = 1, rg32f) readonly uniform image2DArray h0K;
+#ifdef NORMALS
+layout (set = 3, binding = 2, rgba32f) writeonly uniform image2DArray hTDSlopes;
+#endif
+#endif
+#ifdef VERTICAL
+layout (set = 3, binding = 0, rgba16f) writeonly uniform image2DArray displacementMap;
+layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray hTD;
+#ifdef NORMALS
+layout (set = 3, binding = 2, rgba16f) writeonly uniform image2DArray normalMap;
+layout (set = 3, binding = 3, rgba32f) readonly uniform image2DArray hTDSlopes;
+#endif
+#endif
+
+layout(push_constant) uniform constants {
+ vec4 L;
+ vec4 spectrumScaling;
+ float time;
+ float choppyScale;
+ float displacementScale;
+} PushConstants;
+
+const float g = 9.81;
+
+shared vec4 sharedData[FFT_SIZE];
+#ifdef NORMALS
+shared vec4 sharedSlopes[FFT_SIZE];
+#endif
+
+int ReverseBits(int idx) {
+
+ return int(bitfieldReverse(uint(idx)) >> uint(32 - findMSB(FFT_SIZE)));
+
+}
+
+#ifdef HORIZONTAL
+vec2 MulI(vec2 c) {
+
+ return vec2(-c.y, c.x);
+
+}
+
+vec4 ComputeSpectrum(ivec3 coord, out vec4 slopes) {
+
+ vec2 waveCoord = vec2(coord.xy) - float(FFT_SIZE) / 2.0;
+ vec2 waveVector = 2.0 * PI / PushConstants.L[coord.z] * waveCoord;
+
+ float k = length(waveVector);
+ float w = sqrt(g * k);
+
+ ivec2 inverseCoords = (FFT_SIZE - coord.xy) % FFT_SIZE;
+ vec2 h0_k = imageLoad(h0K, coord).rg;
+ vec2 h0_mk = imageLoad(h0K, ivec3(inverseCoords, coord.z)).rg;
+
+ float cos_wt = cos(w * PushConstants.time);
+ float sin_wt = sin(w * PushConstants.time);
+
+ // Calculate h(t)
+ vec2 ht;
+ ht.x = cos_wt * (h0_k.x + h0_mk.x) - sin_wt * (h0_k.y + h0_mk.y);
+ ht.y = sin_wt * (h0_k.x - h0_mk.x) + cos_wt * (h0_k.y - h0_mk.y);
+
+ // From h(t) calculate dx(t) and dy(t) as i * k / |k| * h(t), which moves the points towards the crests
+ float kt2 = dot(waveCoord, waveCoord);
+ vec2 nkt = vec2(0.0);
+
+ if (kt2 > 1e-12)
+ nkt = normalize(waveCoord);
+
+ vec2 dt_x = vec2(-ht.y * nkt.x, ht.x * nkt.x);
+ vec2 idt_z = vec2(-ht.x * nkt.y, -ht.y * nkt.y);
+
+#ifdef NORMALS
+ // Real results are packed in pairs: h + i * dDx/dz, dh/dx + i * dh/dz and dDx/dx + i * dDz/dz
+ vec2 slopeX = MulI(ht) * waveVector.x;
+ vec2 slopeZ = MulI(ht) * waveVector.y;
+ vec2 dxx = -ht * waveVector.x * nkt.x;
+ vec2 dzz = -ht * waveVector.y * nkt.y;
+ vec2 dxz = -ht * waveVector.x * nkt.y;
+
+ slopes = vec4(slopeX + MulI(slopeZ), dxx + MulI(dzz));
+ ht += MulI(dxz);
+#else
+ slopes = vec4(0.0);
+#endif
+
+ return vec4(ht, dt_x + idt_z);
+
+}
+#endif
+
+void FFT() {
+
+ int idx = int(gl_LocalInvocationIndex);
+
+ for (int span = 1; span < FFT_SIZE; span *= 2) {
+ int pos = idx % span;
+ int top = (idx / span) * span * 2 + pos;
+ int bottom = top + span;
+
+ float twiddleArgument = PI * float(pos) / float(span);
+ vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument));
+
+ vec4 s = sharedData[top];
+ vec4 t = mul(vec4(twiddleFactor, twiddleFactor), sharedData[bottom]);
+
+ sharedData[top] = s + t;
+ sharedData[bottom] = s - t;
+
+#ifdef NORMALS
+ s = sharedSlopes[top];
+ t = mul(vec4(twiddleFactor, twiddleFactor), sharedSlopes[bottom]);
+
+ sharedSlopes[top] = s + t;
+ sharedSlopes[bottom] = s - t;
+#endif
+
+ barrier();
+ }
+
+}
+
+void main() {
+
+ int idx = int(gl_LocalInvocationIndex);
+ int spectrumIdx = int(gl_WorkGroupID.z);
+
+#ifdef HORIZONTAL
+ int row = int(gl_WorkGroupID.y);
+
+ for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) {
+ vec4 slopes;
+ sharedData[ReverseBits(i)] = ComputeSpectrum(ivec3(i, row, spectrumIdx), slopes);
+#ifdef NORMALS
+ sharedSlopes[ReverseBits(i)] = slopes;
+#endif
+ }
+
+ barrier();
+
+ FFT();
+
+ for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) {
+ imageStore(hTD, ivec3(i, row, spectrumIdx), sharedData[i]);
+#ifdef NORMALS
+ imageStore(hTDSlopes, ivec3(i, row, spectrumIdx), sharedSlopes[i]);
+#endif
+ }
+#endif
+
+#ifdef VERTICAL
+ int column = int(gl_WorkGroupID.x);
+
+ for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) {
+ sharedData[ReverseBits(i)] = imageLoad(hTD, ivec3(column, i, spectrumIdx));
+#ifdef NORMALS
+ sharedSlopes[ReverseBits(i)] = imageLoad(hTDSlopes, ivec3(column, i, spectrumIdx));
+#endif
+ }
+
+ barrier();
+
+ FFT();
+
+ for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) {
+ vec4 data = sharedData[i];
+ float perm = bool((column + i) & 1) ? -1.0 : 1.0;
+ imageStore(displacementMap, ivec3(column, i, spectrumIdx), vec4(perm * data.bra, 1.0));
+
+#ifdef NORMALS
+ vec4 slopes = perm * sharedSlopes[i];
+ float scale = PushConstants.spectrumScaling[spectrumIdx];
+ float choppyScale = PushConstants.choppyScale * scale;
+
+ // Same as the normal shader, but without the error of finite differences
+ vec2 slope = slopes.xy * PushConstants.displacementScale * scale;
+ vec3 derivatives = vec3(slopes.zw, perm * data.g) * choppyScale;
+ float J = (1.0 + derivatives.x) * (1.0 + derivatives.y) - derivatives.z * derivatives.z;
+
+ vec2 gradient = slope / max(vec2(1.0) + derivatives.xy, vec2(0.01));
+ imageStore(normalMap, ivec3(column, i, spectrumIdx), vec4(-gradient, dot(gradient, gradient), 1.0 - J));
+#endif
+ }
+#endif
+
+}
diff --git a/data/shader/ocean/h0.csh b/data/shader/ocean/h0.csh
index 950ed6b9a..bc9dc77b9 100644
--- a/data/shader/ocean/h0.csh
+++ b/data/shader/ocean/h0.csh
@@ -10,9 +10,10 @@ layout(set = 3, binding = 4) uniform sampler2D noise2;
layout(set = 3, binding = 5) uniform sampler2D noise3;
layout(push_constant) uniform constants {
- ivec4 L;
+ vec4 L;
vec2 w;
int N;
+ int C;
float A;
float windspeed;
float windDependency;
@@ -21,13 +22,17 @@ layout(push_constant) uniform constants {
const float g = 9.81;
+// Each cascade keeps the waves between a fraction of its size and that of the next smaller cascade
+const float bandWavelengthFraction = 0.25;
+
// Box-Muller transform: https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
vec2 gaussrnd() {
- vec2 coord = vec2(gl_GlobalInvocationID.xy) / float(PushConstants.N);
-
- float U00 = clamp(texture(noise0, coord).r + 0.00001, 0.0, 1.0);
- float U01 = clamp(texture(noise1, coord).r + 0.00001, 0.0, 1.0);
+ // The cascades use the same wave vector indices, with the same random numbers they would repeat each other
+ ivec2 pixel = (ivec2(gl_GlobalInvocationID.xy) + int(gl_GlobalInvocationID.z) * ivec2(131, 241)) % PushConstants.N;
+
+ float U00 = clamp(texelFetch(noise0, pixel, 0).r + 0.00001, 0.0, 1.0);
+ float U01 = clamp(texelFetch(noise1, pixel, 0).r + 0.00001, 0.0, 1.0);
float R0 = sqrt(-2.0 * log(U00));
float T0 = 2.0 * PI * U01;
@@ -58,16 +63,30 @@ void main() {
vec2 coord = vec2(gl_GlobalInvocationID.xy) - float(PushConstants.N) / 2.0;
- vec2 waveVector = 2.0 * PI / float(PushConstants.L[spectrumIdx]) * coord;
+ vec2 waveVector = 2.0 * PI / PushConstants.L[spectrumIdx] * coord;
float l = (PushConstants.windspeed * PushConstants.windspeed) / g;
- float h0k = sqrt(phillips(waveVector, PushConstants.A, l, PushConstants.w)) / sqrt(2.0);
+ // Scaled by the frequency step, such that the wave heights don't depend on the cascade size
+ float dk = 2.0 * PI / PushConstants.L[spectrumIdx];
+ float h0k = sqrt(phillips(waveVector, PushConstants.A, l, PushConstants.w)) / sqrt(2.0) * dk;
vec2 rnd = gaussrnd();
- if (waveVector.x == 0.0 &&
- waveVector.y == 0.0) {
+ float L = PushConstants.L[spectrumIdx];
+ float smallerL = 0.0;
+ bool hasLarger = false;
+ for (int i = 0; i < PushConstants.C; i++) {
+ if (PushConstants.L[i] < L)
+ smallerL = max(smallerL, PushConstants.L[i]);
+ hasLarger = hasLarger || PushConstants.L[i] > L;
+ }
+
+ float k = length(waveVector);
+ float kMin = hasLarger ? 2.0 * PI / (bandWavelengthFraction * L) : 0.0;
+ float kMax = smallerL > 0.0 ? 2.0 * PI / (bandWavelengthFraction * smallerL) : 1e20;
+
+ if (k == 0.0 || k < kMin || k >= kMax) {
h0k = 0.0;
}
diff --git a/data/shader/ocean/ht.csh b/data/shader/ocean/ht.csh
deleted file mode 100644
index 5aa24c44f..000000000
--- a/data/shader/ocean/ht.csh
+++ /dev/null
@@ -1,52 +0,0 @@
-#include <../common/PI.hsh>
-#include <../common/complex.hsh>
-
-layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
-
-layout (set = 3, binding = 0, rgba32f) writeonly uniform image2DArray hTD;
-layout (set = 3, binding = 1, rg32f) readonly uniform image2DArray h0K;
-
-layout(push_constant) uniform constants {
- ivec4 L;
- int N;
- float time;
-} PushConstants;
-
-const float g = 9.81;
-
-void main() {
-
- int spectrumIdx = int(gl_GlobalInvocationID.z);
- vec2 coord = vec2(gl_GlobalInvocationID.xy) - float(PushConstants.N) / 2.0;
-
- vec2 waveVector = 2.0 * PI / float(PushConstants.L[spectrumIdx]) * coord;
-
- float k = length(waveVector);
- float w = sqrt(g * k);
-
- ivec2 inverseCoords = (ivec2(imageSize(h0K))) - ivec2(gl_GlobalInvocationID);
- vec2 h0_k = imageLoad(h0K, ivec3(gl_GlobalInvocationID.xy, spectrumIdx)).rg;
- vec2 h0_mk = imageLoad(h0K, ivec3(inverseCoords, spectrumIdx)).rg;
-
- float cos_wt = cos(w * PushConstants.time);
- float sin_wt = sin(w * PushConstants.time);
-
- // Calculate h(t)
- vec2 ht;
- ht.x = cos_wt * (h0_k.x + h0_mk.x) - sin_wt * (h0_k.y + h0_mk.y);
- ht.y = sin_wt * (h0_k.x - h0_mk.x) + cos_wt * (h0_k.y - h0_mk.y);
-
- // From h(t) calculate dx(t) and dy(t)
- vec2 kt = coord;
- float kt2 = dot(kt, kt);
- vec2 nkt = vec2(0.0);
-
- if (kt2 > 1e-12)
- nkt = normalize(kt);
-
- vec2 dt_x = vec2(ht.y * nkt.x, -ht.x * nkt.x);
- vec2 idt_z = vec2(ht.x * nkt.y, ht.y * nkt.y);
-
- imageStore(hTD, ivec3(gl_GlobalInvocationID.xyz), vec4(ht, dt_x + idt_z));
-
-}
\ No newline at end of file
diff --git a/data/shader/ocean/inversion.csh b/data/shader/ocean/inversion.csh
deleted file mode 100644
index 8145e4207..000000000
--- a/data/shader/ocean/inversion.csh
+++ /dev/null
@@ -1,23 +0,0 @@
-layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
-
-layout (set = 3, binding = 0, rgba16f) writeonly uniform image2DArray displacementMap;
-layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray pingpongMap;
-
-void main() {
-
- ivec3 coord = ivec3(gl_GlobalInvocationID.xyz);
-
- float perm = bool((coord.x + coord.y) & 1) ? -1.0 : 1.0;
-
- vec3 displacement;
-
- float x = imageLoad(pingpongMap, coord).b;
- float y = imageLoad(pingpongMap, coord).r;
- float z = imageLoad(pingpongMap, coord).a;
-
- displacement = perm * vec3(x, y, z);
-
- imageStore(displacementMap, coord,
- vec4(displacement, 1.0));
-
-}
\ No newline at end of file
diff --git a/data/shader/ocean/normal.csh b/data/shader/ocean/normal.csh
index da2547748..37d5d3a7b 100644
--- a/data/shader/ocean/normal.csh
+++ b/data/shader/ocean/normal.csh
@@ -7,7 +7,6 @@ layout (set = 3, binding = 1, rgba16f) writeonly uniform image2DArray normalMap;
// layout (set = 3, binding = 2, rgba16f) readonly uniform image2D historyMap;
layout(push_constant) uniform constants {
- ivec4 L;
vec4 tilingFactor;
vec4 spectrumScaling;
int N;
@@ -17,8 +16,6 @@ layout(push_constant) uniform constants {
float temporalWeight;
float temporalThreshold;
-
- float foamOffset;
} PushConstants;
vec3 AdjustScale(vec3 point) {
@@ -40,11 +37,11 @@ void main() {
float tileSize = (tilingFactor * PushConstants.tiling) / float(PushConstants.N);
float invTileSize = 1.0 / tileSize;
- vec3 center = imageLoad(displacementMap, coord).grb;
- vec3 left = imageLoad(displacementMap, ivec3(mod(fCoord.x - 1.0, fN), coord.y, coord.z)).grb;
- vec3 right = imageLoad(displacementMap, ivec3(mod(fCoord.x + 1.0, fN), coord.y, coord.z)).grb;
- vec3 top = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y + 1.0, fN), coord.z)).grb;
- vec3 bottom = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y - 1.0, fN), coord.z)).grb;
+ vec3 center = imageLoad(displacementMap, coord).rgb;
+ vec3 left = imageLoad(displacementMap, ivec3(mod(fCoord.x - 1.0, fN), coord.y, coord.z)).rgb;
+ vec3 right = imageLoad(displacementMap, ivec3(mod(fCoord.x + 1.0, fN), coord.y, coord.z)).rgb;
+ vec3 top = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y + 1.0, fN), coord.z)).rgb;
+ vec3 bottom = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y - 1.0, fN), coord.z)).rgb;
center = AdjustScale(center);
left = AdjustScale(left);
@@ -54,22 +51,19 @@ void main() {
// float history = imageLoad(historyMap, coord).a;
- // Calculate jacobian
- vec2 Dx = 2.0 * (right.xz - left.xz);
- vec2 Dy = 2.0 * (top.xz - bottom.xz);
- float J = (tileSize + Dx.x) * (tileSize + Dy.y) - Dx.y * Dy.x;
-
- float fold = max(0.0, -clamp(J, -1.0, 1.0) + PushConstants.foamOffset);
+ // Calculate jacobian, it's 1 for undisturbed water and negative where the waves fold over
+ vec2 Dx = 0.5 * invTileSize * (right.xz - left.xz);
+ vec2 Dy = 0.5 * invTileSize * (top.xz - bottom.xz);
+ float J = (1.0 + Dx.x) * (1.0 + Dy.y) - Dx.y * Dy.x;
- /*
- float blend = fold > PushConstants.temporalThreshold ? 0.0 : 0.0;
- fold = mix(fold, history, blend);
- */
+ // The cascades are combined into an approximate jacobian of the whole surface when rendering
+ float jacobianDeficit = 1.0 - J;
float width = right.x - center.x;
float height = top.z - center.z;
vec2 gradient = vec2(right.y - center.y, top.y - center.y) / max(tileSize + vec2(width, height), tileSize * 0.01);
- imageStore(normalMap, coord, vec4(-gradient, 0.0, fold));
+ // The squared slope is averaged by the mip maps, the rendering derives the roughness from it
+ imageStore(normalMap, coord, vec4(-gradient, dot(gradient, gradient), jacobianDeficit));
}
\ No newline at end of file
diff --git a/data/shader/ocean/ocean.fsh b/data/shader/ocean/ocean.fsh
index 12012460c..91b2a8d06 100644
--- a/data/shader/ocean/ocean.fsh
+++ b/data/shader/ocean/ocean.fsh
@@ -1,6 +1,7 @@
#define SHADOW_FILTER_VOGEL
#include
+#include
#include <../common/convert.hsh>
#include <../common/utility.hsh>
#include <../common/stencil.hsh>
@@ -9,8 +10,18 @@
#include <../clouds/shadow.hsh>
#include <../volumetric/volumetric.hsh>
#include <../structures.hsh>
+#include <../brdf/brdf.hsh>
#include
+#include
+
+#ifdef DDGI
+#include <../ddgi/ddgi.hsh>
+#endif
+
+// From deferred.hsh
+layout(set = 1, binding = 11) uniform samplerCube specularProbe;
+layout(set = 1, binding = 12) uniform samplerCube diffuseProbe;
// Lighting based on Island Demo (NVIDIA SDK 11)
@@ -19,12 +30,13 @@ layout (location = 1) out vec2 velocity;
layout (location = 2) out uint stencil;
layout (set = 3, binding = 2) uniform sampler2D foamTexture;
-layout (set = 3, binding = 3) uniform samplerCube skyEnvProbe;
+#ifdef REFLECTION
+layout (set = 3, binding = 3) uniform sampler2D reflectionTexture;
+#endif
layout (set = 3, binding = 4) uniform sampler2D refractionTexture;
layout (set = 3, binding = 5) uniform sampler2D depthTexture;
layout (set = 3, binding = 7) uniform sampler2D volumetricTexture;
layout (set = 3, binding = 8) uniform sampler2DArrayShadow cascadeMaps;
-layout (set = 3, binding = 10) uniform sampler2D rippleTexture;
layout(set = 3, binding = 15) uniform sampler2D cloudShadowMap;
layout(set = 3, binding = 16) uniform sampler2D volumetricCloudTexture;
layout(set = 3, binding = 20) uniform sampler2D oceanDepthTexture;
@@ -41,17 +53,18 @@ layout(location=8) in vec3 ndcLast;
layout(location=9) in vec3 normalShoreWave;
#endif
-// Control water scattering at crests
-const float scatterIntensity = 1.5;
-const float scatterCrestScale = 0.2;
-const float scatterCrestOffset = 0.0;
+// Sun light scattered through the thin wave crests, the jacobian tells how thin they are
+const float scatterIntensity = 2.5;
+const float scatterThinnessScale = 4.0;
+const float scatterCrestHeight = 1.0;
-// Specular properties
-const float specularPower = 500.0;
-const float specularIntensity = 350.0;
+// From right below, the surface stays partly transparent near the camera
+const float nearSurfaceTransmission = 0.6;
+const float nearSurfaceCameraDepth = 1.5;
+const float nearSurfaceDistance = 15.0;
// Shore softness (lower is softer)
-const float shoreSoftness = 70.5;
+const float shoreSoftness = 7.5;
const float fadeoutDistance = 100.0;
const float fadeoutFalloff = 0.2;
@@ -68,12 +81,10 @@ void main() {
Light light = LightUniforms.light;
- vec2 fTexCoord = fOriginalCoord.xz / Uniforms.tiling;
-
- float fold;
+ float fold, jacobian, slopeVariance;
vec2 gradientDisplacement;
- GetOceanGradientAndFold(fOriginalCoord.xz, distance(fOriginalCoord.xyz, globalData.cameraLocation.xyz),
- fold, gradientDisplacement);
+ float viewDistance = distance(fOriginalCoord.xyz, globalData.cameraLocation.xyz);
+ GetOceanGradientAndFold(fOriginalCoord.xz, viewDistance, fold, gradientDisplacement, jacobian, slopeVariance);
/*
// This stuff calculates the geometry normals from the depth buffer
@@ -95,10 +106,10 @@ void main() {
vec3 depthPos = ConvertDepthToViewSpace(clipDepth, ndcCoord);
//vec3 fNormal = normal;
- vec3 fNormal = normalize(vec3(gradientDisplacement.x, 2.0, gradientDisplacement.y));
+ vec3 fNormal = normalize(vec3(gradientDisplacement.x, 1.0, gradientDisplacement.y));
- float shadowFactor = max(CalculateCascadedShadow(light.shadow, cascadeMaps, fPosition,
- vec3(gl_FragCoord.xy, 0.0), fNormal, 0.0), 1.0);
+ float shadowFactor = CalculateCascadedShadow(light.shadow, cascadeMaps, fPosition,
+ vec3(gl_FragCoord.xy, 0.0), fNormal, 0.0);
#ifdef CLOUD_SHADOWS
@@ -112,58 +123,40 @@ void main() {
fNormal = mix(normalShoreWave, fNormal, shoreScaling);
#endif
- // Create TBN matrix for normal mapping
- vec3 norm = fNormal;
- vec3 tang = vec3(1.0, 0.0, 0.0);
- tang.y = -((norm.x*tang.x) / norm.y) - ((norm.z*tang.z) / norm.y);
- tang = normalize(tang);
- vec3 bitang = normalize(cross(tang, norm));
- mat3 tbn = mat3(tang, bitang, norm);
-
- // Normal mapping normal (offsets actual normal)
- vec3 rippleNormal = vec3(0.0, 1.0, 0.0);
-
-#ifdef RIPPLE_TEXTURE
- rippleNormal = normalize(2.0 * texture(rippleTexture, 20.0 * fTexCoord - vec2(globalData.time * 0.2), globalData.mipLodBias).rgb - 1.0);
- rippleNormal += normalize(2.0 * texture(rippleTexture, 20.0 * fTexCoord * 0.5 + vec2(globalData.time * 0.05), globalData.mipLodBias).rgb - 1.0);
- // Won't work with rippleNormal = vec3(0.0, 1.0, 0.0). Might be worth an investigation
- norm = normalize(tbn * rippleNormal);
-#endif
-
- // Scale ripples based on actual (not view) depth of water
- float rippleScaling = clamp(1.0 - shoreScaling, 0.05, 0.1);
- norm = normalize(mix(fNormal, norm, rippleScaling));
+ vec3 norm = GetOceanRippleNormal(fNormal, fOriginalCoord.xz, shoreScaling);
vec3 eyeDir = normalize(fModelCoord - globalData.cameraLocation.xyz);
+ vec3 lightDir = -light.direction.xyz;
- float nDotL = dot(norm, -light.direction.xyz);
+ float nDotL = dot(norm, lightDir);
float nDotE = saturate(dot(norm, -eyeDir));
// Calculate fresnel factor
- float fresnel = 0.02 + (1.0 - 0.02) * pow(1.0 - nDotE, 5.0);
-
- // Calculate reflection vector
+ float fresnel = FresnelSchlick(vec3(0.02), 1.0, nDotE).r;
+
+ // Reflections below the horizon would show the ground of the sky probe
vec3 reflectionVec = normalize(reflect(eyeDir, norm));
- //reflectionVec.y = max(0.0, reflectionVec.y);
-
+ reflectionVec.y = max(0.0, reflectionVec.y);
+ reflectionVec = normalize(reflectionVec);
+
// Calculate sun spot
- float specularFactor = shadowFactor * fresnel * pow(max(dot(normalize(reflectionVec),
- -normalize(light.direction.xyz)), 0.0), specularPower);
+ float alpha = GetOceanAlpha(slopeVariance);
+ float surfaceRoughness = sqrt(alpha);
+ // The sun is a disk, the half vectors which reflect parts of it spread by half its angular radius
+ float sunAlpha = sqrt(sqr(alpha) + sqr(tan(0.5 * Uniforms.sunAngularRadius)));
+ vec3 halfway = normalize(lightDir - eyeDir);
+ float specularFactor = shadowFactor * saturate(nDotL) * DistributionGGX(saturate(dot(norm, halfway)), sunAlpha) *
+ VisibilitySmithGGXCorrelated(saturate(nDotL), max(nDotE, 0.0001), sunAlpha) *
+ FresnelSchlick(vec3(0.02), 1.0, saturate(dot(-eyeDir, halfway))).r;
// Scattering equations
float waveHeight = fModelCoord.y - Uniforms.translation.y;
- float scatterFactor = scatterIntensity * max(0.0, waveHeight
- * scatterCrestScale + scatterCrestOffset);
-
- scatterFactor *= shadowFactor * pow(max(0.0, dot(-light.direction.xyz, eyeDir)), 8.0);
-
- scatterFactor *= pow(clamp(1.0 - nDotL, 0.0, 1.1), 16.0);
-
- /*
- scatterFactor += shadowFactor * Uniforms.waterColorIntensity.y
- * max(0.0, waveHeight) * max(0.0, nDotE) *
- max(0.0, 1.0 + eyeDir.y) * dot(-light.direction.xyz, -eyeDir);
- */
+ float crestThinness = saturate((1.0 - jacobian) * scatterThinnessScale) *
+ smoothstep(0.0, scatterCrestHeight, waveHeight);
+ // Only visible when looking towards the sun through the wave side which faces away from it
+ float scatterFactor = scatterIntensity * crestThinness * pow(saturate(dot(lightDir, eyeDir)), 4.0) *
+ pow(saturate(0.5 - 0.5 * dot(lightDir, norm)), 3.0);
+ scatterFactor *= shadowFactor * saturate(lightDir.y + 0.2);
// Calculate water depth based on the viewer (ray from camera to ground)
float waterViewDepth = max(0.0, fPosition.z - depthPos.z);
@@ -175,23 +168,47 @@ void main() {
// Retrieve colors from textures
vec3 refractionColor = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb;
- vec3 reflectionColor = textureLod(skyEnvProbe, reflectionVec, 0).rgb;
+#ifdef REFLECTION
+ // Traced and filtered from the ocean surface together with the reflections of the scene
+ vec3 reflectionColor = textureLod(reflectionTexture, ndcCoord, 0.0).rgb;
+#else
+ float reflectionMipLevel = surfaceRoughness * float(textureQueryLevels(specularProbe) - 1);
+ vec3 reflectionColor = textureLod(specularProbe, reflectionVec, reflectionMipLevel).rgb;
+#endif
- // Calculate water color
- vec3 depthFog = mix(Uniforms.deepWaterBodyColor.rgb, Uniforms.waterBodyColor.rgb, min(1.0 , exp(-waterViewDepth / 10.0)));
- float diffuseFactor = Uniforms.waterColorIntensity.x + Uniforms.waterColorIntensity.y *
- max(0.0, nDotL) * shadowFactor;
- vec3 waterColor = diffuseFactor * light.intensity * light.color.rgb * depthFog;
+ // The light which enters the water body from above, like the indirect diffuse lighting of the scene
+ vec3 indirectLight = textureLod(diffuseProbe, norm, 0.0).rgb;
+#ifdef DDGI
+#ifdef DDGI_SCROLL
+ vec4 indirectLightLocal = ddgiData.volumeEnabled > 0 ?
+ GetLocalIrradiance(fModelCoord, eyeDir, norm, norm, indirectLight) : vec4(0.0, 0.0, 0.0, 1.0);
+#else
+ vec4 indirectLightLocal = ddgiData.volumeEnabled > 0 ?
+ GetLocalIrradiance(fModelCoord, eyeDir, norm, norm) : vec4(0.0, 0.0, 0.0, 1.0);
+#endif
+ indirectLightLocal = IsInsideVolume(fModelCoord) ? indirectLightLocal : vec4(0.0, 0.0, 0.0, 1.0);
+ indirectLight = (indirectLightLocal.rgb + indirectLight * indirectLightLocal.a) * ddgiData.volumeStrength;
+#endif
+
+ // Light scattered by the water body along the refracted view ray, like seen from under water
+ vec3 extinction = GetWaterExtinction();
+ float waterRayLength = distance(fPosition, depthPos);
+ vec3 sunScattering, ambientScattering;
+ GetWaterScattering(extinction, refract(eyeDir, norm, 1.0 / waterRefractiveIndex), 0.0, waterRayLength,
+ light, indirectLight, sunScattering, ambientScattering);
+ vec3 waterColor = shadowFactor * sunScattering + ambientScattering;
// Water edges at shore sould be soft
fresnel *= min(1.0, waterViewDepth * shoreSoftness);
- // Update refraction color based on water depth (exponential falloff)
- refractionColor = mix(waterColor, refractionColor, min(1.0 , exp(-waterViewDepth / 2.0)));
+ // The ground was lit with the light above the water, it lost energy on the way down
+ vec3 groundPos = vec3(globalData.ivMatrix * vec4(depthPos, 1.0));
+ refractionColor *= GetWaterDownwellingTransmittance(light, max(Uniforms.translation.y - groundPos.y, 0.0));
+ refractionColor = refractionColor * exp(-extinction * waterRayLength) + waterColor;
vec2 shoreInteraction = vec2(0.0);
#ifdef TERRAIN
- shoreInteraction = CalculateShoreInteraction(fModelCoord);
+ shoreInteraction = CalculateShoreInteraction(fOriginalCoord);
#endif
// Calculate foam based on folding of wave and fade it out near shores
@@ -204,30 +221,66 @@ void main() {
// Mix relection and refraction and add sun spot
color = mix(refractionColor, reflectionColor, fresnel);
- color += specularIntensity * fresnel * specularFactor * light.color.rgb;
- color += Uniforms.scatterColor.rgb * scatterFactor;
+ color += specularFactor * light.intensity * light.color.rgb;
+ color += (1.0 - fresnel) * scatterFactor * light.intensity * light.color.rgb * Uniforms.scatterColor.rgb;
- vec3 foamShadowFactor = mix(vec3(0.1),
- vec3(0.5) * max(0.0, nDotL) * shadowFactor, 0.7);
+ // Foam is a bright diffuse surface lit by the sun and the sky
+ const float foamAlbedo = 0.9;
+ vec3 foamLight = max(0.0, nDotL) * shadowFactor * light.intensity * light.color.rgb * INV_PI + indirectLight;
- vec3 foamColor = vec3(1.0);
+ // Without a foam texture the foam is broken up by noise
#ifdef FOAM_TEXTURE
- foamColor = foamShadowFactor * light.intensity * light.color.rgb;
+ float foamPattern = texture(foamTexture, fOriginalCoord.xz / (2.0 * Uniforms.foamSize), globalData.mipLodBias).r;
+#else
+ float foamNoise = 0.6 * texture(perlinNoiseMap, fOriginalCoord.xz / (3.0 * Uniforms.foamSize), globalData.mipLodBias).r +
+ 0.4 * texture(perlinNoiseMap, fOriginalCoord.xz / Uniforms.foamSize, globalData.mipLodBias).r;
+ float foamPattern = saturate((foamNoise - 0.2) / 0.6);
#endif
- color = mix(color, foamColor, foam * texture(foamTexture, fOriginalCoord.xz / 8.0, globalData.mipLodBias).r);
+ // The pattern shapes the foam edges and gives the foam its structure
+ vec3 foamColor = foamAlbedo * mix(0.35, 1.0, foamPattern) * foamLight;
+ float foamEdge = max(fwidth(foamPattern), 0.1);
+ float foamCoverage = smoothstep(1.0 - foam - foamEdge, 1.0 - foam + foamEdge, foamPattern) * step(0.001, foam);
+ color = mix(color, foamColor, foamCoverage);
- vec3 breakingColor = foamShadowFactor * light.intensity * light.color.rgb;
+ vec3 breakingColor = foamAlbedo * foamLight;
color = mix(color, breakingColor, shoreInteraction.y);
StencilFeatures features = CreateStencilFeatures();
if (!gl_FrontFacing) {
- fresnel = 0.02 + (1.0 - 0.02) * pow(1.0 - saturate(dot(fNormal, eyeDir)), 5.0);
disturbance = (mat3(globalData.vMatrix) * -vec3(norm.x, 0.0, norm.z)).xz;
refractionDisturbance = vec2(disturbance.x, -disturbance.y) * 0.1;
refractionDisturbance *= min(2.0, waterViewDepth);
- color = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb * (1.0 - fresnel);
+ vec3 transmittedColor = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb;
+
+ // Light from above only gets through inside of Snell's window, outside of it the water body is reflected
+ // The waves only bend the edge of the window slightly, it stays a circle
+ vec3 windowNormal = normalize(mix(vec3(0.0, 1.0, 0.0), norm, 0.3));
+ vec3 transmittedDir = refract(eyeDir, -windowNormal, waterRefractiveIndex);
+ float windowTransmission = dot(transmittedDir, transmittedDir) > 0.0 ?
+ 1.0 - FresnelSchlick(vec3(0.02), 1.0, saturate(dot(transmittedDir, windowNormal))).r : 0.0;
+
+ // The whole sky is squeezed into the window, what isn't on screen comes from the sky probe
+ vec4 windowClip = globalData.pMatrix * globalData.vMatrix * vec4(transmittedDir, 0.0);
+ vec2 windowCoord = 0.5 * windowClip.xy / max(windowClip.w, 1e-4) + 0.5;
+ vec2 windowEdge = saturate(min(windowCoord, 1.0 - windowCoord) * 10.0);
+ float windowOnScreen = windowClip.w > 0.0 ? windowEdge.x * windowEdge.y : 0.0;
+ vec3 windowColor = mix(textureLod(specularProbe, transmittedDir, 0.0).rgb,
+ textureLod(refractionTexture, windowCoord, 0.0).rgb, windowOnScreen);
+
+ vec3 skyRadiance = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb;
+ vec3 sunScattering, ambientScattering;
+ GetWaterScattering(GetWaterExtinction(), reflect(eyeDir, -norm), 0.0, 1000.0, light, skyRadiance,
+ sunScattering, ambientScattering);
+
+ color = mix(sunScattering + ambientScattering, windowColor, windowTransmission);
+
+ // Right below the surface the outside stays visible through the waves
+ float cameraDepth = Uniforms.translation.y - globalData.cameraLocation.y;
+ float nearTransmission = nearSurfaceTransmission * (1.0 - smoothstep(0.0, nearSurfaceCameraDepth, cameraDepth)) *
+ (1.0 - smoothstep(0.0, nearSurfaceDistance, length(fPosition)));
+ color = mix(color, transmittedColor, nearTransmission * (1.0 - windowTransmission));
features.underWaterPixel = true;
}
else {
@@ -241,7 +294,7 @@ void main() {
#ifdef CLOUDS
volumetricClouds = textureLod(volumetricCloudTexture, ndcCoord, 0.0);
#endif
- color = ApplyVolumetrics(Uniforms.fog, color, volumetricFog, volumetricClouds,
+ color = ApplyVolumetrics(color, volumetricFog, volumetricClouds,
eyeDir, globalData.planetCenter.xyz, Uniforms.innerCloudRadius);
}
diff --git a/data/shader/ocean/queries.csh b/data/shader/ocean/queries.csh
new file mode 100644
index 000000000..517858559
--- /dev/null
+++ b/data/shader/ocean/queries.csh
@@ -0,0 +1,48 @@
+layout (local_size_x = 64) in;
+
+#include
+#include
+
+layout(std430, set = 3, binding = 14) readonly buffer Positions {
+ vec4 positions[];
+};
+
+layout(std430, set = 3, binding = 18) writeonly buffer Results {
+ vec4 results[];
+};
+
+layout (set = 3, binding = 17, std140) uniform QueryUniformBuffer {
+ int count;
+} QueryUniforms;
+
+vec3 GetDisplacedPosition(vec3 position) {
+
+ float perlinScale, shoreScale;
+ vec3 normalShoreWave;
+ // The physics shouldn't depend on the camera, so the waves don't fade out with the distance to it
+ return position + GetOceanDisplacement(position, 0.0, perlinScale, shoreScale, normalShoreWave);
+
+}
+
+void main() {
+
+ int idx = int(gl_GlobalInvocationID.x);
+ if (idx >= QueryUniforms.count)
+ return;
+
+ vec2 position = positions[idx].xz;
+
+ // The waves move the surface sideways as well, search the undisplaced position that ends up here
+ vec3 originalPosition = vec3(position.x, Uniforms.translation.y, position.y);
+ for (int i = 0; i < 4; i++) {
+ vec3 displacedPosition = GetDisplacedPosition(originalPosition);
+ originalPosition.xz += position - displacedPosition.xz;
+ }
+
+ vec3 displacedPosition = GetDisplacedPosition(originalPosition);
+ vec3 tangent = GetDisplacedPosition(originalPosition + vec3(0.1, 0.0, 0.0)) - displacedPosition;
+ vec3 bitangent = GetDisplacedPosition(originalPosition + vec3(0.0, 0.0, 0.1)) - displacedPosition;
+
+ results[idx] = vec4(normalize(cross(bitangent, tangent)), displacedPosition.y);
+
+}
diff --git a/data/shader/ocean/sharedUniforms.hsh b/data/shader/ocean/sharedUniforms.hsh
index f70ffedec..77fb71ddf 100644
--- a/data/shader/ocean/sharedUniforms.hsh
+++ b/data/shader/ocean/sharedUniforms.hsh
@@ -6,7 +6,6 @@ layout (set = 3, binding = 11, std140) uniform UniformBuffer {
Fog fog;
vec4 waterBodyColor;
- vec4 deepWaterBodyColor;
vec4 scatterColor;
vec4 translation;
@@ -37,6 +36,11 @@ layout (set = 3, binding = 11, std140) uniform UniformBuffer {
int N;
int spectrumCount;
float innerCloudRadius;
+
+ float foamOffset;
+ float foamScale;
+ float foamSize;
+ float sunAngularRadius;
} Uniforms;
layout (set = 3, binding = 12, std140) uniform LightUniformBuffer {
diff --git a/data/shader/ocean/shoreInteraction.hsh b/data/shader/ocean/shoreInteraction.hsh
index 95a5f1c42..81eb18de7 100644
--- a/data/shader/ocean/shoreInteraction.hsh
+++ b/data/shader/ocean/shoreInteraction.hsh
@@ -1,33 +1,63 @@
#include
#include <../common/utility.hsh>
+#include <../common/random.hsh>
layout(set = 3, binding = 9) uniform sampler2D terrainHeight;
-vec3 CalculateGerstner(vec3 position) {
+float ShoreValueNoise(vec2 position) {
+
+ ivec2 cell = ivec2(floor(position));
+ vec2 weight = fract(position);
+ weight = weight * weight * (3.0 - 2.0 * weight);
+
+ float a = floatConstruct(hash(uvec2(cell)));
+ float b = floatConstruct(hash(uvec2(cell + ivec2(1, 0))));
+ float c = floatConstruct(hash(uvec2(cell + ivec2(0, 1))));
+ float d = floatConstruct(hash(uvec2(cell + ivec2(1, 1))));
+ return mix(mix(a, b, weight.x), mix(c, d, weight.x), weight.y);
+
+}
+
+// Breaks the shore waves into irregular stretches that drift slowly, independent of the world axes
+float ShoreModulation(vec3 position) {
+
+ vec2 drift = vec2(0.031, 0.017) * globalData.time;
+ float noise = 0.65 * ShoreValueNoise(position.xz / 28.0 + drift) + 0.35 * ShoreValueNoise(position.xz / 9.0 - 1.7 * drift);
+ return smoothstep(0.45, 0.75, noise);
+
+}
+
+// Scale fades the shore wave out on the shore and in deep water
+float GetShoreWavePhase(vec3 position, out float scale, out vec2 shoreGradient) {
- vec2 terrainTex = (vec2(position.xz) - vec2(Uniforms.terrainTranslation.xz))
- / Uniforms.terrainSideLength;
+ vec2 terrainTex = (position.xz - Uniforms.terrainTranslation.xz) / Uniforms.terrainSideLength;
+ vec4 shore = textureLod(terrainHeight, terrainTex, 0.0);
- float shoreDistance = textureLod(terrainHeight, terrainTex, 0.0).g;
- vec2 shoreGradient = normalize(2.0 * textureLod(terrainHeight, terrainTex, 0.0).ba - 1.0);
+ float shoreDistance = shore.g;
+ shoreGradient = normalize(2.0 * shore.ba - 1.0);
// Avoid scaling by water depth. Resolution artifacts become obvious.
- float scale = clamp(1.0 - shoreDistance, 0.0, 1.0);
- scale *= clamp(shoreDistance * 10.0, 0.0, 1.0);
+ scale = saturate(1.0 - shoreDistance) * saturate(shoreDistance * 10.0);
- // Should be uniforms
float waveLength = Uniforms.shoreWaveLength / 100.0;
float speed = Uniforms.shoreWaveSpeed / 100.0;
+ return (shoreDistance + speed * globalData.time) / waveLength;
- float w = 1.0 / waveLength;
- float phi = speed * w;
- float rad = w * shoreDistance + phi * globalData.time;
+}
+
+vec3 CalculateGerstner(vec3 position) {
+
+ float scale;
+ vec2 shoreGradient;
+ float rad = GetShoreWavePhase(position, scale, shoreGradient);
- float modulation = saturate(sin(position.x / 20.0) + cos(position.z / 10.0));
-
float distanceScale = saturate(1.0 - (distance(globalData.cameraLocation.xyz, position)
- Uniforms.shoreWaveDistanceOffset) / Uniforms.shoreWaveDistanceScale);
+ if (scale * distanceScale <= 0.0)
+ return vec3(0.0);
+
+ float modulation = ShoreModulation(position);
float amplitude = 1.0 * Uniforms.shoreWaveAmplitude * scale * modulation * distanceScale;
float steepness = 1.0 * Uniforms.shoreWaveSteepness * scale * modulation * distanceScale;
@@ -44,22 +74,13 @@ vec3 CalculateGerstner(vec3 position) {
vec2 CalculateShoreInteraction(vec3 position) {
- vec2 terrainTex = (vec2(position.xz) - vec2(Uniforms.terrainTranslation.xz))
- / Uniforms.terrainSideLength;
- float shoreDistance = textureLod(terrainHeight, terrainTex, 0.0).g;
-
- float scale = clamp(1.0 - shoreDistance, 0.0, 1.0);
- scale *= clamp(shoreDistance * 10.0, 0.0, 1.0);
-
- // Should be uniforms
- float waveLength = Uniforms.shoreWaveLength / 100.0;
- float speed = Uniforms.shoreWaveSpeed / 100.0;
-
- float w = 1.0 / waveLength;
- float phi = speed * w;
- float rad = w * shoreDistance + phi * globalData.time;
+ float scale;
+ vec2 shoreGradient;
+ float rad = GetShoreWavePhase(position, scale, shoreGradient);
+ if (scale <= 0.3)
+ return vec2(0.0);
- float modulation = saturate(sin(position.x / 20.0) + cos(position.z / 10.0));
+ float modulation = ShoreModulation(position);
// Move these calculations to the fragment shader
float foamShoreWave = max(-cos(rad), 0.0) * 1.0 * max(scale - 0.3, 0.0) * modulation;
diff --git a/data/shader/ocean/surface.hsh b/data/shader/ocean/surface.hsh
new file mode 100644
index 000000000..08daa1092
--- /dev/null
+++ b/data/shader/ocean/surface.hsh
@@ -0,0 +1,71 @@
+// Surface detail which can only be evaluated in fragment shaders, used by the surface and the depth pass
+
+layout (set = 3, binding = 10) uniform sampler2D rippleTexture;
+
+// Roughness of the waves which are too small for the simulation, the larger ones add their slope variance
+const float roughness = 0.07;
+// Only part of the unresolved slopes is turned into roughness, which keeps some of the sparkle of the sun reflection
+const float slopeVarianceScale = 0.25;
+
+void GetOceanGradientAndFold(vec2 texCoord, float dist, out float fold, out vec2 gradient,
+ out float jacobian, out float slopeVariance) {
+
+ texCoord /= Uniforms.tiling;
+
+ vec4 tilingFactors = Uniforms.spectrumTilingFactors;
+ vec4 fadeoutDistances = Uniforms.spectrumFadeoutDistances;
+
+ vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances);
+
+ // Each cascade contains a different band of waves, so they are added up
+ gradient = vec2(0.0);
+ jacobian = 1.0;
+ slopeVariance = 0.0;
+
+ for (int i = 0; i < Uniforms.spectrumCount; i++) {
+ vec3 coord = vec3(texCoord / tilingFactors[i] + vec2(0.25 * float(i)), float(i));
+ if (fade[i] > 0.0) {
+ vec4 data = texture(normalMap, coord);
+ gradient += fade[i] * data.rg;
+ jacobian -= fade[i] * data.a;
+ // Unresolved slopes roughen the surface, under magnification the filtering only adds grid artifacts
+ float mipLevel = textureQueryLod(normalMap, coord.xy).y;
+ float filteredVariance = max(0.0, data.b - dot(data.rg, data.rg)) * saturate(mipLevel);
+ slopeVariance += filteredVariance + (1.0 - sqr(fade[i])) * dot(data.rg, data.rg);
+ }
+ else {
+ // The smallest mip level is the average squared slope of the whole cascade
+ slopeVariance += textureLod(normalMap, coord, float(textureQueryLevels(normalMap) - 1)).b;
+ }
+ }
+
+ fold = saturate((Uniforms.foamOffset - jacobian) * Uniforms.foamScale);
+
+}
+
+// Small ripples from the normal map on top of the simulated waves, they fade out at the shore
+vec3 GetOceanRippleNormal(vec3 normal, vec2 position, float shoreScaling) {
+
+#ifdef RIPPLE_TEXTURE
+ vec3 tangent = normalize(vec3(1.0, -normal.x / normal.y, 0.0));
+ vec3 bitangent = normalize(cross(tangent, normal));
+ mat3 tbn = mat3(tangent, bitangent, normal);
+
+ vec2 texCoord = 20.0 * position / Uniforms.tiling;
+ vec3 rippleNormal = normalize(2.0 * texture(rippleTexture, texCoord - vec2(globalData.time * 0.2), globalData.mipLodBias).rgb - 1.0);
+ rippleNormal += normalize(2.0 * texture(rippleTexture, texCoord * 0.5 + vec2(globalData.time * 0.05), globalData.mipLodBias).rgb - 1.0);
+
+ float rippleScaling = clamp(1.0 - shoreScaling, 0.05, 0.1);
+ return normalize(mix(normal, normalize(tbn * rippleNormal), rippleScaling));
+#else
+ return normal;
+#endif
+
+}
+
+float GetOceanAlpha(float slopeVariance) {
+
+ // The slope variance of a surface roughly is the squared alpha of its microfacet distribution
+ return sqrt(sqr(sqr(roughness)) + slopeVarianceScale * slopeVariance);
+
+}
diff --git a/data/shader/ocean/twiddleIndices.csh b/data/shader/ocean/twiddleIndices.csh
deleted file mode 100644
index a69d72378..000000000
--- a/data/shader/ocean/twiddleIndices.csh
+++ /dev/null
@@ -1,44 +0,0 @@
-#include <../common/PI.hsh>
-#include <../common/complex.hsh>
-
-layout (local_size_x = 1, local_size_y = 16) in;
-
-layout (set = 3, binding = 0, rg32f) writeonly uniform image2D twiddleIndicesTexture;
-
-// The first butterfly stage we use bit-reversed indices computed
-// on the CPU.
-layout (set = 3, binding = 1, std430) buffer indices {
- int index[];
-} bitrevIndices;
-
-// Remember that this is executed into x direction just log_2(N) times.
-void main() {
-
- vec2 coord = vec2(gl_GlobalInvocationID.xy);
-
- // Span of the butterfly operation at a given horizontal point
- float span = floor(pow(2.0, coord.x));
-
- bool topWing = mod(coord.y, pow(2.0, coord.x + 1.0)) < pow(2.0, coord.x);
-
- vec4 twiddleIndices;
-
- // For the first stage use the shader storage buffer
- if (coord.x == 0.0) {
- if (topWing)
- twiddleIndices = vec4(bitrevIndices.index[int(coord.y)],
- bitrevIndices.index[int(coord.y + 1.0)], 0.0, 0.0);
- else
- twiddleIndices = vec4(bitrevIndices.index[int(coord.y - 1.0)],
- bitrevIndices.index[int(coord.y)], 0.0, 0.0);
- }
- else {
- if (topWing)
- twiddleIndices = vec4(coord.y, coord.y + span, 0.0, 0.0);
- else
- twiddleIndices = vec4(coord.y - span, coord.y, 0.0, 0.0);
- }
-
- imageStore(twiddleIndicesTexture, ivec2(coord), twiddleIndices);
-
-}
\ No newline at end of file
diff --git a/data/shader/ocean/underwater.csh b/data/shader/ocean/underwater.csh
index c414e48cc..a963b2f77 100644
--- a/data/shader/ocean/underwater.csh
+++ b/data/shader/ocean/underwater.csh
@@ -1,6 +1,6 @@
layout (local_size_x = 8, local_size_y = 8) in;
-#define SHADOW_FILTER_VOGEL
+#define SHADOW_FILTER_1x1
#include
#include
@@ -12,6 +12,11 @@ layout (local_size_x = 8, local_size_y = 8) in;
#include <../common/utility.hsh>
#include <../common/stencil.hsh>
#include <../common/normalencode.hsh>
+#include <../common/ign.hsh>
+
+#include
+
+layout(set = 1, binding = 12) uniform samplerCube diffuseProbe;
layout (set = 3, binding = 4) uniform sampler2D refractionTexture;
layout(set = 3, binding = 16) uniform sampler2D depthTexture;
@@ -20,12 +25,61 @@ layout(set = 3, binding = 18) uniform sampler2D oceanDepthTexture;
layout(set = 3, binding = 8) uniform sampler2DArrayShadow cascadeMaps;
layout(set = 3, binding = 20, rgba16f) uniform image2D outputImage;
+const int shaftSampleCount = 8;
+const float shaftDistance = 40.0;
+
+// Caustic pattern at the surface, normalized to an average of one
+float GetShaftPattern(vec2 position) {
+
+ mat3 m = mat3(-2,-1,2, 3,-2,1, 1,2,2);
+ vec3 a = vec3(position * 0.25, globalData.time / 4.0) * m;
+ vec3 b = a * m * 0.4;
+ vec3 c = b * m * 0.3;
+ float pattern = min(min(length(0.5 - fract(a)), length(0.5 - fract(b))), length(0.5 - fract(c)));
+ return pattern * pattern * pattern / 0.06;
+
+}
+
+// Average visibility of the sun along the view ray: shadows and the light focused by the waves
+float GetShaftVisibility(Light light, vec3 rayOrigin, vec3 rayDirection, vec3 viewRayDirection, float rayLength,
+ float waterHeight, vec3 lightDirection, float extinction, float downwellingAttenuation, float noise) {
+
+ float marchLength = min(rayLength, shaftDistance);
+ float stepLength = marchLength / float(shaftSampleCount);
+
+ float visibility = 0.0;
+ float weightSum = 0.0;
+ for (int i = 0; i < shaftSampleCount; i++) {
+ float t = (float(i) + noise) * stepLength;
+ vec3 position = rayOrigin + rayDirection * t;
+ float depth = max(waterHeight - position.y, 0.0);
+
+ vec2 surfacePosition = position.xz - lightDirection.xz * depth / -lightDirection.y;
+
+ // The shadow map follows the unrefracted light, so the shadow is taken where the refracted light enters
+ vec3 surfaceViewPosition = vec3(globalData.vMatrix * vec4(surfacePosition.x, waterHeight, surfacePosition.y, 1.0));
+ float shadow = CalculateCascadedShadow(light.shadow, cascadeMaps, surfaceViewPosition,
+ vec3(0.0), vec3(0.0), 1.0);
+
+ // Shafts build up below the surface and blur out deeper down
+ float shaftStrength = saturate(depth / 3.0) * exp(-depth / 20.0);
+ float shaft = mix(1.0, GetShaftPattern(surfacePosition), shaftStrength);
+
+ // Samples which contribute more light count more
+ float weight = exp(-extinction * t - downwellingAttenuation * depth / -lightDirection.y);
+ visibility += weight * shadow * shaft;
+ weightSum += weight;
+ }
+
+ return weightSum > 0.0 ? visibility / weightSum : 1.0;
+
+}
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(outputImage).x ||
- pixel.y > imageSize(outputImage).y)
+ if (pixel.x >= imageSize(outputImage).x ||
+ pixel.y >= imageSize(outputImage).y)
return;
Light light = LightUniforms.light;
@@ -35,17 +89,10 @@ void main() {
float depth = textureLod(depthTexture, texCoord, 0.0).r;
float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r;
- if (depth == 1.0 && oceanDepth == 1.0)
- return;
-
vec3 viewSpacePos = ConvertDepthToViewSpace(depth, texCoord);
- vec3 viewSpaceOceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord);
vec3 pixelPos = vec3(globalData.ivMatrix * vec4(viewSpacePos, 1.0));
- vec3 oceanPos = vec3(globalData.ivMatrix * vec4(viewSpaceOceanPos, 1.0));
vec3 nearPos = vec3(globalData.ivMatrix * vec4(ConvertDepthToViewSpace(0.0, texCoord), 1.0));
- float distanceToCamera = length(viewSpacePos);
-
int pixelsUnderWater = 0;
int waterPixels = 0;
for (int x = -1; x <= 1; x++) {
@@ -66,41 +113,53 @@ void main() {
vec3 normalShoreWave;
vec3 displacement = GetOceanDisplacement(nearPos, 0.0, perlinScale, shoreScaling, normalShoreWave);
- vec3 viewVector = pixelPos - nearPos;
-
- float waterDepth = Uniforms.translation.y - nearPos.y + displacement.y;
- if (waterDepth < 0.0 && depth < oceanDepth && oceanDepth < 1.0 ||
+ float waterHeight = Uniforms.translation.y + displacement.y;
+ float waterDepth = waterHeight - nearPos.y;
+ // With the camera under water every pixel is seen through water, also far surface pixels voted to be seen from above
+ if (waterDepth < 0.0 && (depth == 1.0 && oceanDepth == 1.0 ||
+ depth < oceanDepth && oceanDepth < 1.0 ||
oceanDepth == 1.0 && pixelPos.y > Uniforms.translation.y ||
- (!underWaterPixel && features.waterPixel)) {
+ (!underWaterPixel && features.waterPixel))) {
return;
}
- texCoord = (texCoord + vec2(0.05)) * 0.9;
-
- texCoord.x += sin(texCoord.y * 2.0 * PI * 5.0 + 5.0 * globalData.time) * 0.001 / depth;
- texCoord.y += cos(texCoord.x * 2.0 * PI * 2.0 + 2.0 * globalData.time) * 0.001 / depth;
+ // Slight wobble of the image like seen through moving water
+ vec2 wobble = vec2(sin(texCoord.y * 2.0 * PI * 5.0 + 5.0 * globalData.time),
+ cos(texCoord.x * 2.0 * PI * 2.0 + 2.0 * globalData.time)) * 0.001;
+ texCoord = clamp(texCoord + wobble, vec2(0.0), vec2(1.0));
depth = textureLod(depthTexture, texCoord, 0.0).r;
viewSpacePos = ConvertDepthToViewSpace(depth, texCoord);
pixelPos = vec3(globalData.ivMatrix * vec4(viewSpacePos, 1.0));
- vec3 refractionColor = textureLod(refractionTexture, texCoord, 0.0).rgb;
+ vec3 surfaceColor = textureLod(refractionTexture, texCoord, 0.0).rgb;
+
+ vec3 rayOrigin = globalData.cameraLocation.xyz;
+ vec3 rayDirection = normalize(pixelPos - rayOrigin);
+ float rayLength = depth < 1.0 ? distance(pixelPos, rayOrigin) : 1000.0;
+ // The water ends at the surface
+ if (rayDirection.y > 0.0)
+ rayLength = min(rayLength, max(waterHeight - rayOrigin.y, 0.0) / rayDirection.y + 1.0);
- float NDotL = dot(-light.direction.xyz, vec3(0.0, 1.0, 0.0));
+ float cameraDepth = max(waterHeight - rayOrigin.y, 0.0);
+ float pixelDepth = max(Uniforms.translation.y - pixelPos.y, 0.0);
- viewVector = normalize(viewVector);
+ vec3 extinction = GetWaterExtinction();
+ vec3 lightDirection = GetUnderwaterLightDirection(light.direction.xyz);
- float waterOffset = max(0.0, (nearPos.y - Uniforms.translation.y) / max(viewVector.y, 0.0001));
- float waterViewDepth = distance(pixelPos, nearPos);
+ vec3 skyRadiance = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb;
+ vec3 sunScattering, ambientScattering;
+ GetWaterScattering(extinction, rayDirection, cameraDepth, rayLength, light, skyRadiance,
+ sunScattering, ambientScattering);
- // Calculate water color
- vec3 depthFog = mix(Uniforms.deepWaterBodyColor.rgb, Uniforms.waterBodyColor.rgb, min(1.0 , exp(-waterViewDepth / 20.0)));
- float diffuseFactor = Uniforms.waterColorIntensity.x + Uniforms.waterColorIntensity.y * max(0.0, NDotL);
- vec3 waterColor = diffuseFactor * light.intensity * light.color.rgb * depthFog;
+ float noise = GetInterleavedGradientNoise(vec2(pixel));
+ sunScattering *= GetShaftVisibility(light, rayOrigin, rayDirection, normalize(viewSpacePos), rayLength,
+ waterHeight, lightDirection, extinction.g, GetWaterDownwellingAttenuation().g, noise);
- // Update refraction color based on water depth (exponential falloff)
- refractionColor = mix(waterColor, refractionColor, min(1.0 , exp(-waterViewDepth / 5.0)));
+ // Surfaces were lit with the light above the water, it lost energy on the way down
+ surfaceColor *= GetWaterDownwellingTransmittance(light, pixelDepth);
+ vec3 color = surfaceColor * exp(-extinction * rayLength) + sunScattering + ambientScattering;
- imageStore(outputImage, pixel, vec4(refractionColor, 0.0));
+ imageStore(outputImage, pixel, vec4(color, 0.0));
-}
\ No newline at end of file
+}
diff --git a/data/shader/ocean/waterBody.hsh b/data/shader/ocean/waterBody.hsh
new file mode 100644
index 000000000..ae525ec4a
--- /dev/null
+++ b/data/shader/ocean/waterBody.hsh
@@ -0,0 +1,93 @@
+#include <../common/PI.hsh>
+
+// Light inside the water body, seen from above and below the surface
+// The absorption follows the water body color, red is gone after a few meters
+const float waterAbsorptionScale = 0.12;
+// Water scatters short wavelengths more
+const vec3 waterScattering = vec3(0.03, 0.05, 0.1);
+const float waterRefractiveIndex = 1.33;
+// Skylight enters from all directions and travels a longer way down than the sun light
+const float ambientDownwellingCosine = 0.75;
+const float waterPhaseG = 0.6;
+
+vec3 GetWaterAbsorption() {
+
+ return -log(clamp(Uniforms.waterBodyColor.rgb, vec3(0.01), vec3(1.0))) * waterAbsorptionScale;
+
+}
+
+vec3 GetWaterExtinction() {
+
+ return GetWaterAbsorption() + waterScattering;
+
+}
+
+// Most light is scattered forward and keeps going down, only the light scattered back is lost on the way
+vec3 GetWaterDownwellingAttenuation() {
+
+ return GetWaterAbsorption() + 0.25 * waterScattering;
+
+}
+
+// Direction of the sun light after entering the water
+vec3 GetUnderwaterLightDirection(vec3 lightDirection) {
+
+ vec3 direction = refract(normalize(lightDirection), vec3(0.0, 1.0, 0.0), 1.0 / waterRefractiveIndex);
+ return dot(direction, direction) > 0.0 ? direction : vec3(0.0, -1.0, 0.0);
+
+}
+
+float GetUnderwaterLightCosine(vec3 lightDirection) {
+
+ return max(-GetUnderwaterLightDirection(lightDirection).y, 0.05);
+
+}
+
+// Surfaces under water are lit with the light above the water, this is what is left of it at a depth
+vec3 GetWaterDownwellingTransmittance(Light light, float depth) {
+
+ return exp(-GetWaterDownwellingAttenuation() * depth / GetUnderwaterLightCosine(light.direction.xyz));
+
+}
+
+float WaterPhase(float cosTheta) {
+
+ float g = waterPhaseG;
+ float henyeyGreenstein = (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * cosTheta, 1.5));
+ return mix(1.0 / (4.0 * PI), henyeyGreenstein, 0.7);
+
+}
+
+// Integral of the light scattered towards the viewer along a ray starting at a depth below the surface,
+// where the light coming from above is attenuated by the way down with the given cosine
+vec3 IntegrateWaterScattering(vec3 extinction, float startDepth, float rayDirectionY, float lightCosine, float rayLength) {
+
+ vec3 attenuation = GetWaterDownwellingAttenuation() / lightCosine;
+ vec3 rate = extinction - attenuation * rayDirectionY;
+ vec3 integral = mix(vec3(rayLength), (1.0 - exp(-rate * rayLength)) / rate, greaterThan(abs(rate), vec3(1e-4)));
+ return exp(-attenuation * startDepth) * integral;
+
+}
+
+// Light scattered towards the viewer, without sun shadows
+void GetWaterScattering(vec3 extinction, vec3 rayDirection, float startDepth, float rayLength, Light light,
+ vec3 skyRadiance, out vec3 sunScattering, out vec3 ambientScattering) {
+
+ vec3 lightDirection = GetUnderwaterLightDirection(light.direction.xyz);
+ float lightCosine = GetUnderwaterLightCosine(light.direction.xyz);
+ // Fades out the sun below the horizon, then only the sky lights the water
+ float sunVisibility = saturate(-light.direction.y * 10.0);
+
+ // Light scattered several times, approximated for an infinite medium
+ vec3 absorption = extinction - waterScattering;
+ vec3 scattering = waterScattering / max(absorption / extinction, vec3(0.2));
+
+ vec3 sunLight = sunVisibility * light.intensity * light.color.rgb * WaterPhase(dot(rayDirection, -lightDirection));
+ sunScattering = Uniforms.waterColorIntensity.y * scattering * sunLight *
+ IntegrateWaterScattering(extinction, startDepth, rayDirection.y, lightCosine, rayLength);
+
+ // Only the upper hemisphere is lit by the sky
+ ambientScattering = Uniforms.waterColorIntensity.x * scattering * 0.5 * skyRadiance *
+ IntegrateWaterScattering(extinction, startDepth, rayDirection.y, ambientDownwellingCosine, rayLength);
+
+}
diff --git a/data/shader/pathtracer/atrous.csh b/data/shader/pathtracer/atrous.csh
new file mode 100644
index 000000000..2fe4d44cb
--- /dev/null
+++ b/data/shader/pathtracer/atrous.csh
@@ -0,0 +1,245 @@
+#include <../common/utility.hsh>
+#include <../common/convert.hsh>
+#include <../common/flatten.hsh>
+#include <../common/normalencode.hsh>
+
+#include <../common/denoiser.hsh>
+
+layout (local_size_x = 16, local_size_y = 16) in;
+
+layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage;
+layout(set = 3, binding = 1) uniform sampler2D inputTexture;
+layout(set = 3, binding = 2) uniform sampler2D depthTexture;
+layout(set = 3, binding = 3) uniform sampler2D normalTexture;
+layout(set = 3, binding = 4) uniform usampler2D materialIdxTexture;
+#ifdef REMODULATE
+layout(set = 3, binding = 5) uniform sampler2D albedoTexture;
+layout(set = 3, binding = 6) uniform sampler2D emissionTexture;
+#endif
+
+#ifdef STEP_SIZE1
+const int kernelRadius = 2;
+#endif
+#ifdef STEP_SIZE2
+const int kernelRadius = 4;
+#endif
+#ifdef STEP_SIZE4
+const int kernelRadius = 8;
+#endif
+
+const int stepSize = kernelRadius / 2;
+
+const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius);
+const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius;
+
+struct PixelData {
+ vec4 color;
+ vec3 normal;
+ uint materialIdx;
+ float depth;
+};
+
+struct PackedPixelData {
+ // Contains 16 bit color, variance and normal
+ uvec4 data;
+};
+
+// Separate arrays, a struct with them would be padded to 32 bytes and exceed 32 KB of shared memory on some devices
+shared PackedPixelData pixelData[sharedDataSize];
+shared uint pixelMaterialIdx[sharedDataSize];
+shared float pixelDepth[sharedDataSize];
+
+layout(push_constant) uniform constants {
+ float strength;
+} pushConstants;
+
+const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 };
+
+PackedPixelData PackPixelData(PixelData data) {
+ PackedPixelData compressed;
+
+ compressed.data.x = packHalf2x16(data.color.rg);
+ compressed.data.y = packHalf2x16(data.color.ba);
+ compressed.data.z = packHalf2x16(data.normal.xy);
+ compressed.data.w = packHalf2x16(vec2(data.normal.z, 0.0));
+
+ return compressed;
+}
+
+PixelData UnpackPixelData(PackedPixelData compressed) {
+ PixelData data;
+
+ data.color.rg = unpackHalf2x16(compressed.data.x);
+ data.color.ba = unpackHalf2x16(compressed.data.y);
+ data.normal.xy = unpackHalf2x16(compressed.data.z);
+ vec2 temp = unpackHalf2x16(compressed.data.w);
+ data.normal.z = temp.x;
+
+ return data;
+}
+
+void LoadGroupSharedData() {
+
+ ivec2 resolution = imageSize(outputImage);
+ ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) - ivec2(kernelRadius);
+
+ uint workGroupSize = gl_WorkGroupSize.x * gl_WorkGroupSize.y;
+ for(uint i = gl_LocalInvocationIndex; i < sharedDataSize; i += workGroupSize) {
+ ivec2 localOffset = Unflatten2D(int(i), unflattenedSharedDataSize);
+ ivec2 texel = localOffset + workGroupOffset;
+
+ texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1));
+
+ PixelData data;
+
+ data.color = texelFetch(inputTexture, texel, 0);
+
+ // Linear depth, zero marks the sky
+ float depth = texelFetch(depthTexture, texel, 0).r;
+ data.depth = depth >= 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth);
+
+ data.materialIdx = texelFetch(materialIdxTexture, texel, 0).r;
+
+ // The path tracer writes world space normals
+ data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg);
+
+ pixelData[i] = PackPixelData(data);
+ pixelMaterialIdx[i] = data.materialIdx;
+ pixelDepth[i] = data.depth;
+ }
+
+ barrier();
+
+}
+
+PixelData GetPixel(ivec2 pixelOffset) {
+
+ ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius);
+ int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize);
+ PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]);
+ data.materialIdx = pixelMaterialIdx[sharedMemoryIdx];
+ data.depth = pixelDepth[sharedMemoryIdx];
+ return data;
+
+}
+
+float GetFilteredVariance() {
+
+ float variance = 0.0;
+ const float weights[2][2] =
+ {
+ { 1.0 / 4.0, 1.0 / 8.0 },
+ { 1.0 / 8.0, 1.0 / 16.0 }
+ };
+
+ const int radius = 1;
+ for (int x = -radius; x <= radius; x++) {
+ for (int y = -radius; y <= radius; y++) {
+ PixelData samplePixelData = GetPixel(ivec2(x, y));
+
+ float weight = weights[abs(x)][abs(y)];
+ float sampleVariance = samplePixelData.color.a;
+ variance += weight * sampleVariance;
+ }
+ }
+
+ return variance;
+
+}
+
+vec4 Filter(ivec2 pixel, ivec2 resolution, PixelData centerPixelData) {
+
+ vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ vec2 texelSize = 1.0 / vec2(resolution);
+
+ vec4 centerColor = centerPixelData.color;
+ vec3 centerNormal = centerPixelData.normal;
+ uint centerMaterialIdx = centerPixelData.materialIdx;
+
+ vec3 viewRay = GetViewRay(texCoord);
+ vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay;
+ vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay;
+ vec3 centerPosition = viewRay * centerPixelData.depth;
+ vec3 centerViewNormal = normalize(mat3(globalData.vMatrix) * centerNormal);
+
+ float centerLuminance = Luma(centerColor.rgb);
+
+ vec4 outputColor = centerColor;
+ float totalWeight = 1.0;
+
+ float variance = GetFilteredVariance();
+ float stdDeviation = sqrt(max(0.0, variance));
+
+ vec3 viewDir = normalize(centerPosition);
+ float NdotV = abs(dot(viewDir, centerViewNormal));
+ float depthPhi = max(32.0, NdotV * 128.0);
+
+ // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once.
+ // The distance to the surface plane is affine in the offset since the view ray is
+ const float log2e = 1.442695;
+ float planeRay = dot(viewRay, centerViewNormal);
+ float planeRayDx = dot(viewRayDx, centerViewNormal);
+ float planeRayDy = dot(viewRayDy, centerViewNormal);
+ float planeOffset = dot(centerPosition, centerViewNormal);
+ float planeScale = depthPhi * log2e / abs(centerPosition.z);
+ float luminanceScale = log2e / (stdDeviation * pushConstants.strength + 1e-10);
+ const float normalPhi = 128.0;
+
+ const int radius = 2;
+ for (int x = -radius; x <= radius; x++) {
+ for (int y = -radius; y <= radius; y++) {
+ ivec2 offset = ivec2(x, y) * stepSize;
+ ivec2 samplePixel = pixel + offset;
+
+ if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y ||
+ samplePixel.x < 0 || samplePixel.y < 0
+ || (x == 0 && y == 0))
+ continue;
+
+ PixelData samplePixelData = GetPixel(offset);
+
+ if (samplePixelData.depth == 0.0 || samplePixelData.materialIdx != centerMaterialIdx)
+ continue;
+
+ vec4 sampleColor = samplePixelData.color;
+
+ // The distance to the surface plane stays stable at grazing angles, unlike the depth
+ float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx +
+ float(offset.y) * planeRayDy) - planeOffset;
+ float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6);
+
+ float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale +
+ abs(planeDistance) * planeScale - normalPhi * log2(normalDot);
+ float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent);
+
+ totalWeight += weight;
+ outputColor += vec4(vec3(weight), weight * weight) * sampleColor;
+ }
+ }
+
+ return outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight);
+
+}
+
+void main() {
+
+ LoadGroupSharedData();
+
+ ivec2 pixel = ivec2(gl_GlobalInvocationID);
+ ivec2 resolution = imageSize(outputImage);
+ if (pixel.x >= resolution.x || pixel.y >= resolution.y)
+ return;
+
+ PixelData centerPixelData = GetPixel(ivec2(0));
+ vec4 outputColor = centerPixelData.depth == 0.0 ? texelFetch(inputTexture, pixel, 0) :
+ Filter(pixel, resolution, centerPixelData);
+
+#ifdef REMODULATE
+ vec3 albedo = texelFetch(albedoTexture, pixel, 0).rgb;
+ vec3 emission = texelFetch(emissionTexture, pixel, 0).rgb;
+ outputColor = vec4(min(outputColor.rgb * albedo + emission, vec3(65000.0)), 1.0);
+#endif
+
+ imageStore(outputImage, pixel, outputColor);
+
+}
diff --git a/data/shader/pathtracer/rayHit.csh b/data/shader/pathtracer/rayHit.csh
index 28f182454..19ad55fd8 100644
--- a/data/shader/pathtracer/rayHit.csh
+++ b/data/shader/pathtracer/rayHit.csh
@@ -13,8 +13,11 @@
#include <../brdf/brdfSample.hsh>
#include <../brdf/importanceSample.hsh>
#include <../brdf/surface.hsh>
+#include <../clouds/shadow.hsh>
+#ifndef RAY_TRACING_PIPELINE
layout (local_size_x = 32) in;
+#endif
#ifdef REALTIME
layout (set = 3, binding = 1, r32ui) uniform uimage2DArray frameAccumImage;
@@ -23,10 +26,15 @@ layout (set = 3, binding = 6, r32f) writeonly uniform image2D depthImage;
layout (set = 3, binding = 7, rg16f) writeonly uniform image2D normalImage;
layout (set = 3, binding = 8, r16ui) writeonly uniform uimage2D materialIdxImage;
layout (set = 3, binding = 9, rgba8) writeonly uniform image2D albedoImage;
+layout (set = 3, binding = 10, rgba16f) writeonly uniform image2D emissionImage;
#else
layout (set = 3, binding = 1, rgba8) writeonly uniform image2D outputImage;
#endif
+#ifdef CLOUD_SHADOWS
+layout(set = 3, binding = 11) uniform sampler2D cloudMap;
+#endif
+
/*
Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui,
image variables must specify either memory qualifier readonly or the memory qualifier writeonly.
@@ -41,22 +49,25 @@ layout(set = 3, binding = 4) uniform UniformBuffer {
int sampleCount;
int bounceCount;
float seed;
- float exposure;
int samplesPerFrame;
float maxRadiance;
} Uniforms;
const float gamma = 1.0 / 2.2;
+const float minAlbedo = 0.02;
Surface EvaluateBounce(inout Ray ray, inout RayPayload payload);
vec3 EvaluateDirectLight(inout Surface surface);
void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayload payload);
+vec3 RefractThrough(Surface surface, vec3 direction, float raySeed, inout float seed);
float CheckVisibility(Surface surface, float lightDistance);
+vec3 GetDemodulationAlbedo(Surface surface);
void main() {
if (IsRayInvocationValid()) {
Ray ray = ReadRay();
+ TraceBufferedRay(ray);
RayPayload payload;
payload.radiance = vec3(0.0);
@@ -82,6 +93,8 @@ void main() {
vec3 position;
uint materialId;
vec3 geometryNormal;
+ vec3 albedo;
+ vec3 emission;
if (ray.hitID >= 0) {
instance = bvhInstances[nonuniformEXT(ray.hitInstanceID)];
lastMatrix = mat4(transpose(instanceLastMatrices[nonuniformEXT(ray.hitInstanceID)]));
@@ -89,6 +102,9 @@ void main() {
position = surface.P;
materialId = surface.material.ID;
geometryNormal = surface.geometryNormal;
+ albedo = GetDemodulationAlbedo(surface);
+ emission = surface.material.blendMode == blendModeMultiply ? vec3(0.0) : surface.material.emissiveColor *
+ (surface.material.blendMode == blendModeAdditive ? surface.material.opacity : 1.0);
}
else {
instance.inverseMatrix = mat3x4(1.0);
@@ -96,6 +112,8 @@ void main() {
position = ray.origin + ray.direction * 100.0;
materialId = 65535;
geometryNormal = vec3(1.0, 0.0, 0.0);
+ albedo = vec3(1.0);
+ emission = vec3(0.0);
}
// As a reminder: The current inverse matrix is also transposed
@@ -114,7 +132,9 @@ void main() {
imageStore(depthImage, pixel, vec4(ray.hitID >= 0 ? projPositionCurrent.z / projPositionCurrent.w : INF, 0.0, 0.0, 0.0));
imageStore(materialIdxImage, pixel, uvec4(materialId, 0.0, 0.0, 0.0));
- imageStore(normalImage, pixel, vec4(EncodeNormal(geometryNormal), 0.0, 0.0));
+ imageStore(normalImage, pixel, vec4(EncodeNormal(geometryNormal), 0.0, 0.0));
+ imageStore(albedoImage, pixel, vec4(albedo, 1.0));
+ imageStore(emissionImage, pixel, vec4(min(emission, vec3(65000.0)), 1.0));
}
#endif
@@ -126,7 +146,8 @@ void main() {
accumColor += vec4(payload.radiance, 1.0);
imageStore(outAccumImage, pixel, accumColor);
- vec3 color = accumColor.rgb * Uniforms.exposure / float(Uniforms.sampleCount + 1);
+ // The pre-exposure of the radiance is the exposure
+ vec3 color = accumColor.rgb / float(Uniforms.sampleCount + 1);
color = vec3(1.0) - exp(-color);
//color = color / (vec3(1.0) + color);
@@ -176,10 +197,35 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) {
int lod = int(ray.hitDistance / 30.0);
lod = 0;
- // Unpack the compressed triangle and extract surface parameters
- Instance instance = GetInstance(ray);
- Triangle tri = GetTriangle(ray, instance);
- surface = GetSurfaceParameters(instance, tri, ray, true, lod);
+ bool backfaceHit;
+ surface = GetHitSurface(ray, true, backfaceHit, lod);
+
+ // Additive surfaces add their light, multiplied ones tint the light behind them, the ray continues unchanged
+ if (surface.material.blendMode == blendModeAdditive || surface.material.blendMode == blendModeMultiply) {
+ if (surface.material.blendMode == blendModeAdditive) {
+ vec3 emission = surface.material.emissiveColor * surface.material.opacity;
+#ifdef REALTIME
+ // The primary emission is added after the denoiser
+ emission = Uniforms.bounceCount > 0 ? emission : vec3(0.0);
+#endif
+ payload.radiance += payload.throughput * (emission + EvaluateDirectLight(surface));
+ }
+ else {
+ payload.throughput *= mix(vec3(1.0), surface.material.baseColor, surface.material.opacity);
+ }
+ ray.origin = surface.P + ray.direction * EPSILON;
+ return surface;
+ }
+
+ // Alpha blended surfaces which aren't two sided cover the light behind them once like in the rasterizer, their back
+ // faces are only where the rays leave them
+ if (backfaceHit && surface.material.blendMode == blendModeAlpha) {
+ surface.material.opacity = 0.0;
+ float curSeed = Uniforms.seed;
+ ray.direction = RefractThrough(surface, ray.direction, float(ray.ID), curSeed);
+ ray.origin = surface.P + ray.direction * EPSILON;
+ return surface;
+ }
// If we hit an emissive surface we need to terminate the ray
#ifndef REALTIME
@@ -188,12 +234,13 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) {
payload.radiance += surface.material.emissiveColor;
}
#else
- payload.radiance += payload.throughput * surface.material.emissiveColor;
+ // The primary emission is added after the denoiser
+ if (Uniforms.bounceCount > 0)
+ payload.radiance += payload.throughput * surface.material.emissiveColor;
#endif
- // Evaluate direct and indirect light
- vec3 radiance = payload.throughput * saturate(surface.material.opacity)
- * EvaluateDirectLight(surface);
+ // Evaluate direct and indirect light, the direct light is weighted by the opacity
+ vec3 radiance = payload.throughput * EvaluateDirectLight(surface);
// Clamp indirect radiance
// This has to be used cautiously and might be the reason
@@ -215,13 +262,27 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) {
}
+vec3 GetDemodulationAlbedo(Surface surface) {
+
+ // Additive and multiplied surfaces only change the light behind them
+ if (surface.material.blendMode == blendModeAdditive || surface.material.blendMode == blendModeMultiply)
+ return vec3(1.0);
+
+ vec3 diffuse = (1.0 - surface.material.metalness) * surface.material.baseColor;
+ vec3 specular = EvaluateIndirectSpecularBRDF(surface);
+ vec3 albedo = mix(vec3(1.0), diffuse + specular, saturate(surface.material.opacity));
+ // Quantized like the albedo image
+ return round(max(saturate(albedo), vec3(minAlbedo)) * 255.0) / 255.0;
+
+}
+
vec3 EvaluateDirectLight(inout Surface surface) {
if (GetLightCount() == 0)
return vec3(0.0);
float curSeed = Uniforms.seed;
- float raySeed = float(gl_GlobalInvocationID.x);
+ float raySeed = float(INVOCATION_ID.x);
float lightPdf;
Light light = GetLight(surface, raySeed, curSeed, lightPdf);
@@ -232,10 +293,17 @@ vec3 EvaluateDirectLight(inout Surface surface) {
if (lightPdf <= 0.0) return vec3(0.0);
vec3 transmissionColor = GetTransmissionColor(surface.material);
- // Front side reflection, transmission is evaluated separately below
- vec3 reflectance = EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface);
- reflectance *= surface.material.opacity;
+ // Front side reflection, transmission is evaluated separately below. Alpha blended surfaces like glass reflect
+ // regardless of their opacity
+ float specularOpacity = surface.material.blendMode == blendModeAlpha ? 1.0 : surface.material.opacity;
+ vec3 reflectance = EvaluateDiffuseBRDF(surface) * surface.material.opacity +
+ EvaluateSpecularBRDF(surface) * specularOpacity;
vec3 radiance = light.radiance * solidAngle;
+#ifdef CLOUD_SHADOWS
+ if (light.type == uint(DIRECTIONAL_LIGHT))
+ radiance *= CalculateCloudShadow(vec3(globalData.vMatrix * vec4(surface.P, 1.0)), cloudShadowUniforms.cloudShadow,
+ cloudMap);
+#endif
float visibility = light.castShadow ? CheckVisibility(surface, lightDistance) : 1.0;
vec3 direct = reflectance * radiance * surface.NdotL * visibility / lightPdf;
@@ -282,7 +350,8 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa
if (rnd < specChance) {
brdfSample = SampleSpecularBRDF(surface, vec2(u0, u1));
- brdfSample.reflectance *= opacity;
+ // Alpha blended surfaces like glass reflect regardless of their opacity
+ brdfSample.reflectance *= mat.blendMode == blendModeAlpha ? 1.0 : opacity;
brdfSample.pdf *= specChance;
cosine = surface.NdotL;
}
@@ -310,7 +379,7 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa
brdfSample.pdf *= (1.0 - passThroughChance);
}
else {
- brdfSample.L = ray.direction;
+ brdfSample.L = RefractThrough(surface, ray.direction, raySeed, curSeed);
brdfSample.pdf = passThroughChance;
brdfSample.reflectance = vec3(1.0 - opacity);
transmitted = true;
@@ -332,9 +401,10 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa
payload.throughput = vec3(0.0);
return;
}
- // Offset the origin to the side the ray continues on
+ // Offset the origin to the side the ray continues on, rays passing through may also leave a surface or be reflected
+ float passedSide = dot(ray.direction, surface.geometryNormal) > 0.0 ? 1.0 : -1.0;
ray.origin = transmitted && !passedThrough ? surface.P - surface.geometryNormal * EPSILON :
- passedThrough ? surface.P - surface.N * EPSILON : surface.P + surface.V * EPSILON;
+ passedThrough ? surface.P + surface.geometryNormal * (passedSide * EPSILON) : surface.P + surface.V * EPSILON;
payload.throughput *= mat.ao;
// Russain roulette, terminate rays with a chance of one percent
@@ -359,10 +429,28 @@ float CheckVisibility(Surface surface, float lightDistance) {
ray.direction = surface.L;
// For transmitted light N is already flipped to the back side
ray.origin = surface.P + surface.N * EPSILON;
- return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON);
+ return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, lightDistance - 2.0 * EPSILON);
}
else {
return 0.0;
}
}
+
+// Refracting surfaces bend the ray where it enters and leaves them, it's reflected beyond the critical angle. Rough ones
+// refract it through a normal of their microfacets
+vec3 RefractThrough(Surface surface, vec3 direction, float raySeed, inout float seed) {
+
+ if (surface.material.refractiveIndex == 1.0)
+ return direction;
+
+ vec3 facingNormal = dot(direction, surface.N) < 0.0 ? surface.N : -surface.N;
+ if (surface.material.roughness > 0.0) {
+ vec2 u = vec2(random(raySeed, seed), random(raySeed, seed));
+ vec3 microfacetNormal = ImportanceSampleGGX(u, facingNormal, sqr(surface.material.roughness));
+ facingNormal = dot(microfacetNormal, direction) < 0.0 ? microfacetNormal : facingNormal;
+ }
+ vec3 refracted = refract(direction, facingNormal, 1.0 / surface.material.refractiveIndex);
+ return dot(refracted, refracted) > 0.0 ? refracted : reflect(direction, facingNormal);
+
+}
diff --git a/data/shader/pathtracer/rayHit.rgen b/data/shader/pathtracer/rayHit.rgen
new file mode 100644
index 000000000..6ceb692e2
--- /dev/null
+++ b/data/shader/pathtracer/rayHit.rgen
@@ -0,0 +1,7 @@
+// Traces and shades a bounce of the path tracer as the ray generation stage of a ray tracing pipeline, see bvh.hsh
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_shader_invocation_reorder : require
+
+#define RAY_TRACING_PIPELINE
+
+#include
diff --git a/data/shader/pathtracer/temporal.csh b/data/shader/pathtracer/temporal.csh
index 560f9fcc6..a7bc77b80 100644
--- a/data/shader/pathtracer/temporal.csh
+++ b/data/shader/pathtracer/temporal.csh
@@ -8,6 +8,7 @@
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
#include <../common/edgePreserving.hsh>
+#include <../common/denoiser.hsh>
layout (local_size_x = 16, local_size_y = 16) in;
@@ -20,18 +21,21 @@ layout (set = 3, binding = 4) uniform sampler2D velocityTexture;
layout (set = 3, binding = 5) uniform sampler2D depthTexture;
layout (set = 3, binding = 6) uniform sampler2D normalTexture;
layout (set = 3, binding = 7) uniform usampler2D materialIdxTexture;
+layout (set = 3, binding = 8) uniform sampler2D albedoTexture;
layout(set = 3, binding = 9) uniform sampler2D historyDepthTexture;
layout(set = 3, binding = 10) uniform sampler2D historyNormalTexture;
layout(set = 3, binding = 11) uniform usampler2D historyMaterialIdxTexture;
+layout(set = 3, binding = 12, rg32f) writeonly uniform image2D momentsImage;
+layout(set = 3, binding = 13) uniform sampler2D historyMomentsTexture;
layout(push_constant) uniform constants {
float historyClipMax;
float currentClipFactor;
float maxHistoryLength;
- float exposure;
int samplesPerFrame;
float maxRadiance;
+ int resetHistory;
} pushConstants;
vec2 invResolution = 1.0 / vec2(imageSize(outAccumImage));
@@ -63,13 +67,6 @@ const ivec2 pixelOffsets[4] = ivec2[4](
ivec2(1, 1)
);
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
vec3 FetchTexel(ivec2 texel) {
vec3 color;
@@ -90,7 +87,7 @@ vec3 FetchTexel(ivec2 texel) {
float(pushConstants.samplesPerFrame) * pushConstants.maxRadiance;
}
- return max(color, 0.0);
+ return max(color, 0.0) / texelFetch(albedoTexture, texel, 0).rgb;
}
@@ -151,26 +148,6 @@ ivec2 FindNearest3x3(ivec2 pixel) {
}
-float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) {
-
- vec3 origin = history;
- vec3 dir = current - history;
-
- // Make sure dir isn't zero
- dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x;
- dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y;
- dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z;
-
- vec3 invDir = 1.0 / dir;
-
- vec3 t0 = (boxMin - origin) * invDir;
- vec3 t1 = (boxMax - origin) * invDir;
-
- vec3 intersect = min(t0, t1);
- return max(intersect.x, max(intersect.y, intersect.z));
-
-}
-
float IsHistoryPixelValid(ivec2 pixel, float linearDepth, uint materialIdx, vec3 normal) {
float confidence = 1.0;
@@ -217,13 +194,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, vec2 velocity, out vec4 histo
if (IsHistoryPixelValid(offsetPixel, linearDepth, materialIdx, normal) > 0.0) {
totalWeight += weights[i];
history += texelFetch(inAccumImage, offsetPixel, 0) * weights[i];
- //historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i];
+ historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i];
}
}
if (totalWeight > 0.0) {
history /= totalWeight;
- //historyMoments /= totalWeight;
+ historyMoments /= totalWeight;
return true;
}
@@ -239,7 +216,7 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, vec2 velocity, out vec4 histo
if (IsHistoryPixelValid(offsetPixel, linearDepth, materialIdx, normal) > 0.0) {
totalWeight += 1.0;
history += texelFetch(inAccumImage, offsetPixel, 0);
- //historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i];
+ historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0);
}
}
@@ -369,8 +346,8 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(outAccumImage).x ||
- pixel.y > imageSize(outAccumImage).y)
+ if (pixel.x >= imageSize(outAccumImage).x ||
+ pixel.y >= imageSize(outAccumImage).y)
return;
uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r;
@@ -381,6 +358,7 @@ void main() {
ComputeVarianceMinMax(mean, std);
vec3 currentRadiance = FetchTexel(pixel);
+ float currentLuma = Luma(currentRadiance);
vec2 velocity = texelFetch(velocityTexture, pixel, 0).rg;
@@ -421,11 +399,11 @@ void main() {
currentRadiance = YCoCgToRGB(currentRadiance);
float temporalWeight = (pushConstants.maxHistoryLength - 1.0) / pushConstants.maxHistoryLength;
- float factor = mix(0.0, temporalWeight - maxVelocity, 1.0 - adjClipBlend);
+ float factor = mix(0.0, temporalWeight, 1.0 - adjClipBlend);
factor = (historyUV.x < 0.0 || historyUV.y < 0.0 || historyUV.x > 1.0
|| historyUV.y > 1.0) ? 0.0 : factor;
- if (factor < 0.1 || !valid) {
+ if (factor < 0.1 || !valid || pushConstants.resetHistory > 0) {
historyLength = 0.0;
}
@@ -444,8 +422,17 @@ void main() {
vec3 resolve = mix(currentRadiance, historyRadiance, factor);
+ vec2 momentsResolve = mix(vec2(currentLuma, sqr(currentLuma)), historyMoments.rg, factor);
+ float accumulatedFrames = GetAccumulatedFrames(factor, historyLength);
+
+ // Short histories use the variance of the neighbourhood, the resolve has the variance of the mean
+ float variance = max(momentsResolve.g - sqr(momentsResolve.r), 0.0);
+ variance = accumulatedFrames < 4.0 ? max(variance, sqr(std.x)) : variance;
+ variance /= accumulatedFrames;
+
imageStore(outAccumImage, pixel, vec4(resolve, historyLength + 1.0));
- imageStore(outputImage, pixel, vec4(resolve, 1.0));
+ imageStore(momentsImage, pixel, vec4(momentsResolve, 0.0, 0.0));
+ imageStore(outputImage, pixel, vec4(min(resolve, vec3(65000.0)), min(variance, 65000.0)));
//imageStore(outAccumImage, pixel, vec4(vec3(valid ? 1.0 : 0.0), historyLength + 1.0));
//imageStore(outAccumImage, pixel, vec4(vec3(historyLength / 10.0), historyLength + 1.0));
diff --git a/data/shader/postprocessing.fsh b/data/shader/postprocessing.fsh
index 43bf15ae6..bfe713f58 100644
--- a/data/shader/postprocessing.fsh
+++ b/data/shader/postprocessing.fsh
@@ -18,8 +18,6 @@ layout(set = 3, binding = 5) uniform sampler2D autoExposureTexture;
#endif
layout(set = 3, binding = 4) uniform UniformBuffer {
- float exposure;
- float autoExposureMipLevel;
float paperWhiteLuminance;
float maxScreenLuminance;
float saturation;
@@ -32,8 +30,10 @@ layout(set = 3, binding = 4) uniform UniformBuffer {
float vignetteOffset;
float vignettePower;
float vignetteStrength;
- float padding0;
+ float autoExposureScale;
float padding1;
+ float padding2;
+ float padding3;
vec4 vignetteColor;
vec4 tintColor;
} Uniforms;
@@ -42,13 +42,6 @@ const float gamma = 1.0 / 2.2;
float screenMaxNits = Uniforms.maxScreenLuminance;
float paperWhiteNits = Uniforms.paperWhiteLuminance;
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
vec3 ACESToneMap(vec3 hdrColor) {
float a = 2.51;
float b = 0.03;
@@ -74,33 +67,12 @@ vec3 ToneMap(vec3 hdrColor) {
}
-float ToneMap(float luminance) {
-
- return 1.0 - exp(-luminance);
-
-}
-
vec3 saturate(vec3 color, float factor) {
const vec3 luma = vec3(0.299, 0.587, 0.114);
vec3 pixelLuminance = max(vec3(dot(color, luma)), vec3(0.0));
return mix(pixelLuminance, color, factor);
}
-const mat3 RGBToYCoCgMatrix = mat3(0.25, 0.5, -0.25, 0.5, 0.0, 0.5, 0.25, -0.5, -0.25);
-const mat3 YCoCgToRGBMatrix = mat3(1.0, 1.0, 1.0, 1.0, 0.0, -1.0, -1.0, 1.0, -1.0);
-
-vec3 RGBToYCoCg(vec3 RGB) {
-
- return RGBToYCoCgMatrix * RGB;
-
-}
-
-vec3 YCoCgToRGB(vec3 YCoCg) {
-
- return YCoCgToRGBMatrix * YCoCg;
-
-}
-
void main() {
vec2 texCoord = 0.5 * positionVS + 0.5;
@@ -136,12 +108,12 @@ void main() {
bloom = Uniforms.bloomDirtStrength * textureLod(bloomDirtTexture, texCoord, 0.0).r * bloom + bloom;
#endif
- color += bloom;
+ color = color * Uniforms.tintColor.rgb + bloom;
- color *= Uniforms.exposure;
+ // The camera exposure is already applied as the pre-exposure of the lighting
#ifdef AUTO_EXPOSURE
float exposureBrightness = texelFetch(autoExposureTexture, ivec2(0.0), 0).r;
- color /= (9.6 * exposureBrightness);
+ color *= Uniforms.autoExposureScale / (9.6 * exposureBrightness);
#endif
#ifdef FILM_GRAIN
@@ -187,8 +159,6 @@ void main() {
#endif
#endif
- color = color * Uniforms.tintColor.rgb;
-
color = clamp(saturate(color, Uniforms.saturation), vec3(0.0), vec3(1.0));
color = ((color - 0.5) * max(Uniforms.contrast, 0.0)) + 0.5;
diff --git a/data/shader/raytracer/binning.csh b/data/shader/raytracer/binning.csh
deleted file mode 100644
index eb5d93bfb..000000000
--- a/data/shader/raytracer/binning.csh
+++ /dev/null
@@ -1,27 +0,0 @@
-#include
-#include
-#include
-
-layout (local_size_x = 32) in;
-
-void main() {
-
- if (IsRayInvocationValid()) {
- uint idx = (1u - rayBufferOffset) * rayBufferSize + gl_GlobalInvocationID.x;
- PackedRay packedRay = rays[idx];
- Ray ray = UnpackRay(packedRay);
-
- idx = (1u - rayPayloadBufferOffset) * rayBufferSize + gl_GlobalInvocationID.x;
- PackedRayPayload packedPayload = rayPayloads[idx];
-
- uint bin = uint(ray.hitID);
- idx = atomicAdd(rayBinCounters[bin], 1u) + rayBinOffsets[bin];
-
- uint offset = rayBufferOffset * rayBufferSize;
- rays[offset + idx] = packedRay;
-
- offset = rayPayloadBufferOffset * rayBufferSize;
- rayPayloads[offset + idx] = packedPayload;
- }
-
-}
\ No newline at end of file
diff --git a/data/shader/raytracer/binningOffset.csh b/data/shader/raytracer/binningOffset.csh
deleted file mode 100644
index 7ab63111f..000000000
--- a/data/shader/raytracer/binningOffset.csh
+++ /dev/null
@@ -1,24 +0,0 @@
-#include
-
-layout (local_size_x = 64) in;
-
-shared uint counts[64];
-
-void main() {
-
- uint idx = gl_LocalInvocationIndex;
-
- counts[idx] = rayBinCounters[idx];
-
- barrier();
-
- uint totalOffset = 0;
- for (uint i = 0; i < idx; i++) {
- totalOffset += counts[i];
- }
-
- // Also want to reset the counters
- rayBinCounters[idx] = 0;
- rayBinOffsets[idx] = totalOffset;
-
-}
\ No newline at end of file
diff --git a/data/shader/raytracer/buffers.hsh b/data/shader/raytracer/buffers.hsh
index 7ec24f9a7..2730a8027 100644
--- a/data/shader/raytracer/buffers.hsh
+++ b/data/shader/raytracer/buffers.hsh
@@ -1,10 +1,6 @@
#include
-#ifdef AE_BINDLESS
#define MESH_COUNT 8192
-#else
-#define MESH_COUNT 1
-#endif
layout(std430, set = 2, binding = 13) buffer ReadAtomic {
uint readAtomic[];
@@ -26,14 +22,6 @@ layout (std430, set = 2, binding = 7) buffer Materials {
RaytraceMaterial materials[];
};
-layout(std430, set = 2, binding = 17) buffer RayBinCounters {
- uint rayBinCounters[];
-};
-
-layout(std430, set = 2, binding = 18) buffer RayBinOffsets {
- uint rayBinOffsets[];
-};
-
layout(std430, set = 2, binding = 21) buffer Instances {
Instance bvhInstances[];
};
diff --git a/data/shader/raytracer/bvh.hsh b/data/shader/raytracer/bvh.hsh
index 3599b44a2..1e1f37fe2 100644
--- a/data/shader/raytracer/bvh.hsh
+++ b/data/shader/raytracer/bvh.hsh
@@ -3,16 +3,29 @@
#ifdef AE_HARDWARE_RAYTRACING
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_ray_query : enable
+#extension GL_EXT_ray_tracing_position_fetch : enable
layout(set = 2, binding = 23) uniform accelerationStructureEXT topLevelAS;
#endif
#include
#include
+#include <../common/opacity.hsh>
#include
#include
#include
+#ifdef AE_HARDWARE_RAYTRACING
+// Object space normal of a triangle, the hit code transforms it with the instance
+vec3 GetTriangleNormal(vec3 v0, vec3 v1, vec3 v2) {
+
+ vec3 normal = cross(v0 - v1, v0 - v2);
+ float len = length(normal);
+ return len > 0.0 ? normal / len : vec3(0.0, 1.0, 0.0);
+
+}
+#endif
+
#define STACK_SIZE 32
#define TLAS_INVALID (STACK_SIZE + 2)
@@ -36,9 +49,15 @@ BVHNode UnpackNode(PackedBVHNode compressed) {
return node;
}
-// Use local stack if there isn't much register pressure
+// Use local stack if there isn't much register pressure. Note that the local stack is dynamically
+// indexed and therefore might end up in (cached) device memory instead of registers.
+// The shared stack is laid out with the thread index as the fastest changing index, such
+// that all threads accessing the same stack depth hit different memory banks.
#ifndef LOCAL_STACK
-shared int stack[32][STACK_SIZE];
+shared int stack[STACK_SIZE][32];
+#define STACK_ENTRY(idx) stack[idx][threadID]
+#else
+#define STACK_ENTRY(idx) stack[idx]
#endif
void CheckLeafClosest(inout Ray ray, int meshPtr, int nodePtr, float tmin, float tmax) {
@@ -124,8 +143,8 @@ int nodePtr, float tmin, float tmax) {
#endif
bool intersect = IntersectTriangle(ray, v0, v1, v2, sol);
if (intersect && sol.x > tmin && sol.x < tmax && d <= 0.0 && sol.x < ray.hitDistance) {
- float opacity = tri.opacity < 0.0 ? GetOpacity(tri, sol.yz, materialOffset, 0) : tri.opacity;
- if (opacity > 0.0) {
+ // Triangles without an opacity map have a positive opacity
+ if (tri.opacity >= 0.0 || GetCutoutOpacity(tri, sol.yz, materialOffset, 0) >= opacityCutoff) {
ray.hitDistance = sol.x;
ray.hitID = triPtr;
ray.hitInstanceID = ray.currentInstanceID;
@@ -174,6 +193,10 @@ bool CheckInstance(inout Ray ray, inout uint cullMask, inout int meshPtr, inout
int instancePtr = ~nodePtr;
Instance instance = bvhInstances[instancePtr];
+ // Rejected instances must not transform the ray, the TLAS traversal continues with it
+ if ((instance.mask & cullMask) == 0)
+ return false;
+
// We don't normalize the direction in case there is a scale in the
// matrix. In that case the normalization leads to wrong scales in closest hit distance
ray.origin = vec4(ray.origin, 1.0) * instance.inverseMatrix;
@@ -184,7 +207,7 @@ bool CheckInstance(inout Ray ray, inout uint cullMask, inout int meshPtr, inout
materialOffset = instance.materialOffset;
nodePtr = 0;
- return (instance.mask & cullMask) > 0;
+ return true;
}
@@ -205,64 +228,54 @@ void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) {
return;
#ifdef LOCAL_STACK
- int stack[1][STACK_SIZE];
- threadID = 0;
+ int stack[STACK_SIZE];
#endif
uint tlasIndex = TLAS_INVALID;
+ // TLAS and BLAS nodes share one code path, only the node fetch differs. Lanes of a SIMD group
+ // are often in different levels, separate paths would then be executed one after another.
while (stackPtr != 0u) {
- if (stackPtr < tlasIndex) {
+ bool isTlas = stackPtr < tlasIndex;
+ if (isTlas && tlasIndex != TLAS_INVALID) {
ray.origin = originalRayOrigin;
ray.direction = originalRayDirection;
tlasIndex = TLAS_INVALID;
- if (nodePtr < 0) {
+ }
+
+ if (nodePtr < 0) {
+ if (isTlas) {
if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr))
tlasIndex = stackPtr;
else
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
else {
- BVHNode node = UnpackNode(tlasNodes[nodePtr]);
-
- float hitL = 0.0, hitR = 0.0;
- bool intersectL = IntersectAABB(ray,
- node.leftAABB, tMin, ray.hitDistance, hitL);
- bool intersectR = IntersectAABB(ray,
- node.rightAABB, tMin, ray.hitDistance, hitR);
-
- bool noIntersection = !intersectL && !intersectR;
- nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
- nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr;
-
- if (intersectR && intersectL) {
- int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
- stack[threadID][stackPtr++] = stackIdx;
- }
+ CheckLeafClosest(ray, meshPtr, nodePtr, tMin, ray.hitDistance);
+ nodePtr = STACK_ENTRY(--stackPtr);
}
}
else {
- if(nodePtr < 0) {
- CheckLeafClosest(ray, meshPtr, nodePtr, tMin, ray.hitDistance);
- nodePtr = stack[threadID][--stackPtr];
- }
- else {
- BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]);
-
- float hitL = 0.0, hitR = 0.0;
- bool intersectL = IntersectAABB(ray,
+ PackedBVHNode packedNode;
+ if (isTlas)
+ packedNode = tlasNodes[nodePtr];
+ else
+ packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr];
+ BVHNode node = UnpackNode(packedNode);
+
+ float hitL = 0.0, hitR = 0.0;
+ bool intersectL = IntersectAABB(ray,
node.leftAABB, tMin, ray.hitDistance, hitL);
- bool intersectR = IntersectAABB(ray,
+ bool intersectR = IntersectAABB(ray,
node.rightAABB, tMin, ray.hitDistance, hitR);
- bool noIntersection = !intersectL && !intersectR;
- nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
- nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr;
+ bool noIntersection = !intersectL && !intersectR;
+ nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
+ nodePtr = noIntersection ? STACK_ENTRY(--stackPtr) : nodePtr;
- if (intersectR && intersectL) {
- int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
- stack[threadID][stackPtr++] = stackIdx;
- }
+ if (intersectR && intersectL) {
+ int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
+ STACK_ENTRY(stackPtr++) = stackIdx;
}
}
}
@@ -289,64 +302,53 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax
return;
#ifdef LOCAL_STACK
- int stack[1][STACK_SIZE];
- threadID = 0;
+ int stack[STACK_SIZE];
#endif
uint tlasIndex = TLAS_INVALID;
+ // See HitClosest for why TLAS and BLAS nodes share one code path
while (stackPtr != 0u) {
- if (stackPtr < tlasIndex) {
+ bool isTlas = stackPtr < tlasIndex;
+ if (isTlas && tlasIndex != TLAS_INVALID) {
ray.origin = originalRayOrigin;
ray.direction = originalRayDirection;
tlasIndex = TLAS_INVALID;
- if (nodePtr < 0) {
+ }
+
+ if (nodePtr < 0) {
+ if (isTlas) {
if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr))
tlasIndex = stackPtr;
else
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
else {
- BVHNode node = UnpackNode(tlasNodes[nodePtr]);
-
- float hitL = 0.0, hitR = 0.0;
- bool intersectL = IntersectAABB(ray,
- node.leftAABB, tMin, ray.hitDistance, hitL);
- bool intersectR = IntersectAABB(ray,
- node.rightAABB, tMin, ray.hitDistance, hitR);
-
- bool noIntersection = !intersectL && !intersectR;
- nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
- nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr;
-
- if (intersectR && intersectL) {
- int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
- stack[threadID][stackPtr++] = stackIdx;
- }
+ CheckLeafClosestTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, ray.hitDistance);
+ nodePtr = STACK_ENTRY(--stackPtr);
}
}
else {
- if(nodePtr < 0) {
- CheckLeafClosestTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, ray.hitDistance);
- nodePtr = stack[threadID][--stackPtr];
- }
- else {
- BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]);
-
- float hitL = 0.0, hitR = 0.0;
- bool intersectL = IntersectAABB(ray,
+ PackedBVHNode packedNode;
+ if (isTlas)
+ packedNode = tlasNodes[nodePtr];
+ else
+ packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr];
+ BVHNode node = UnpackNode(packedNode);
+
+ float hitL = 0.0, hitR = 0.0;
+ bool intersectL = IntersectAABB(ray,
node.leftAABB, tMin, ray.hitDistance, hitL);
- bool intersectR = IntersectAABB(ray,
+ bool intersectR = IntersectAABB(ray,
node.rightAABB, tMin, ray.hitDistance, hitR);
- bool noIntersection = !intersectL && !intersectR;
- nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
- nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr;
+ bool noIntersection = !intersectL && !intersectR;
+ nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr;
+ nodePtr = noIntersection ? STACK_ENTRY(--stackPtr) : nodePtr;
- if (intersectR && intersectL) {
- int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
- stack[threadID][stackPtr++] = stackIdx;
- }
+ if (intersectR && intersectL) {
+ int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr;
+ STACK_ENTRY(stackPtr++) = stackIdx;
}
}
}
@@ -373,62 +375,52 @@ bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) {
vec3 originalRayDirection = ray.direction;
#ifdef LOCAL_STACK
- int stack[1][STACK_SIZE];
- threadID = 0;
+ int stack[STACK_SIZE];
#endif
uint tlasIndex = TLAS_INVALID;
+ // See HitClosest for why TLAS and BLAS nodes share one code path
while (stackPtr != 0u && !hit) {
- if (stackPtr < tlasIndex) {
- if (tlasIndex != TLAS_INVALID) {
- ray.origin = originalRayOrigin;
- ray.direction = originalRayDirection;
- }
+ bool isTlas = stackPtr < tlasIndex;
+ if (isTlas && tlasIndex != TLAS_INVALID) {
+ ray.origin = originalRayOrigin;
+ ray.direction = originalRayDirection;
tlasIndex = TLAS_INVALID;
- if (nodePtr < 0) {
+ }
+
+ if (nodePtr < 0) {
+ if (isTlas) {
if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr))
tlasIndex = stackPtr;
else
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
else {
- BVHNode node = UnpackNode(tlasNodes[nodePtr]);
-
- bool intersectL = IntersectAABB(ray,
- node.leftAABB, tMin, tMax);
- bool intersectR = IntersectAABB(ray,
- node.rightAABB, tMin, tMax);
-
- nodePtr = intersectL ? node.leftPtr : node.rightPtr;
- nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr;
-
- if (intersectR && intersectL) {
- stack[threadID][stackPtr++] = node.rightPtr;
- }
- }
- }
- else {
- if(nodePtr < 0) {
if (CheckLeaf(ray, meshPtr, nodePtr, tMin, tMax)) {
hit = true;
}
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
- else {
- BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]);
-
- bool intersectL = IntersectAABB(ray,
+ }
+ else {
+ PackedBVHNode packedNode;
+ if (isTlas)
+ packedNode = tlasNodes[nodePtr];
+ else
+ packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr];
+ BVHNode node = UnpackNode(packedNode);
+
+ bool intersectL = IntersectAABB(ray,
node.leftAABB, tMin, tMax);
- bool intersectR = IntersectAABB(ray,
+ bool intersectR = IntersectAABB(ray,
node.rightAABB, tMin, tMax);
- nodePtr = intersectL ? node.leftPtr : node.rightPtr;
- nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr;
+ nodePtr = intersectL ? node.leftPtr : node.rightPtr;
+ nodePtr = !intersectR && !intersectL ? STACK_ENTRY(--stackPtr) : nodePtr;
- if (intersectR && intersectL) {
- stack[threadID][stackPtr++] = node.rightPtr;
- }
+ if (intersectR && intersectL) {
+ STACK_ENTRY(stackPtr++) = node.rightPtr;
}
}
}
@@ -457,61 +449,53 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
vec3 originalRayDirection = ray.direction;
#ifdef LOCAL_STACK
- int stack[1][STACK_SIZE];
- threadID = 0;
+ int stack[STACK_SIZE];
#endif
uint tlasIndex = TLAS_INVALID;
+ // See HitClosest for why TLAS and BLAS nodes share one code path
while (stackPtr != 0u && transparency > 0.0) {
- if (stackPtr < tlasIndex) {
+ bool isTlas = stackPtr < tlasIndex;
+ if (isTlas && tlasIndex != TLAS_INVALID) {
ray.origin = originalRayOrigin;
ray.direction = originalRayDirection;
tlasIndex = TLAS_INVALID;
- if (nodePtr < 0) {
+ }
+
+ if (nodePtr < 0) {
+ if (isTlas) {
if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr))
tlasIndex = stackPtr;
else
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
else {
- BVHNode node = UnpackNode(tlasNodes[nodePtr]);
-
- bool intersectL = IntersectAABB(ray,
- node.leftAABB, tMin, tMax);
- bool intersectR = IntersectAABB(ray,
- node.rightAABB, tMin, tMax);
-
- nodePtr = intersectL ? node.leftPtr : node.rightPtr;
- nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr;
-
- if (intersectR && intersectL) {
- stack[threadID][stackPtr++] = node.rightPtr;
- }
- }
- }
- else {
- if(nodePtr < 0) {
- transparency *= CheckLeafTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, tMax, transparency);
+ transparency = CheckLeafTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, tMax, transparency);
if (transparency < 0.000001) {
transparency = 0.0;
}
- nodePtr = stack[threadID][--stackPtr];
+ nodePtr = STACK_ENTRY(--stackPtr);
}
- else {
- BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]);
-
- bool intersectL = IntersectAABB(ray,
+ }
+ else {
+ PackedBVHNode packedNode;
+ if (isTlas)
+ packedNode = tlasNodes[nodePtr];
+ else
+ packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr];
+ BVHNode node = UnpackNode(packedNode);
+
+ bool intersectL = IntersectAABB(ray,
node.leftAABB, tMin, tMax);
- bool intersectR = IntersectAABB(ray,
+ bool intersectR = IntersectAABB(ray,
node.rightAABB, tMin, tMax);
- nodePtr = intersectL ? node.leftPtr : node.rightPtr;
- nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr;
+ nodePtr = intersectL ? node.leftPtr : node.rightPtr;
+ nodePtr = !intersectR && !intersectL ? STACK_ENTRY(--stackPtr) : nodePtr;
- if (intersectR && intersectL) {
- stack[threadID][stackPtr++] = node.rightPtr;
- }
+ if (intersectR && intersectL) {
+ STACK_ENTRY(stackPtr++) = node.rightPtr;
}
}
}
@@ -525,12 +509,78 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
#else
+#ifdef RAY_TRACING_PIPELINE
+// The hit object only identifies the hit, the ray generation stage shades it after the threads are reordered
+layout(location = 0) rayPayloadEXT uvec2 unusedPayload;
+layout(location = 0) hitObjectAttributeEXT vec2 hitObjectBarycentrics;
+
+void TraceClosest(inout Ray ray, uint rayFlags, uint cullMask, float tMin, float tMax) {
+
+ ray.hitDistance = tMax;
+
+ // One hit record per geometry, the records of meshes with material graphs select their hit groups
+ // (RayTracingWorld::hitRecords), reordering groups the threads by hit group first
+ hitObjectTraceRayEXT(closestHitObject, topLevelAS, rayFlags, cullMask, 0, 1, 0,
+ ray.origin, tMin, ray.direction, tMax, 0);
+
+#ifdef SHADER_EXECUTION_REORDER
+ // Hits on the same mesh share materials and textures, misses all sample the sky
+ uint coherenceHint = hitObjectIsHitEXT(closestHitObject) ? uint(hitObjectGetInstanceCustomIndexEXT(closestHitObject)) + 1u : 0u;
+ reorderThreadEXT(closestHitObject, coherenceHint, 16);
+#endif
+
+ if (hitObjectIsHitEXT(closestHitObject)) {
+ hitObjectGetAttributesEXT(closestHitObject, 0);
+ ray.hitBarycentrics = hitObjectBarycentrics;
+#ifdef AE_POSITION_FETCH
+ vec3 positions[3];
+ hitObjectGetIntersectionTriangleVertexPositionsEXT(closestHitObject, positions);
+ ray.hitGeometryNormal = GetTriangleNormal(positions[0], positions[1], positions[2]);
+#endif
+
+ ray.hitDistance = hitObjectGetRayTMaxEXT(closestHitObject);
+ ray.hitInstanceID = hitObjectGetInstanceIdEXT(closestHitObject);
+
+ int geometryOffset = hitObjectGetGeometryIndexEXT(closestHitObject);
+ int meshIdx = hitObjectGetInstanceCustomIndexEXT(closestHitObject);
+
+ int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]);
+ ray.hitID = hitObjectGetPrimitiveIndexEXT(closestHitObject) + triangleOffset;
+ }
+
+}
+
+void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) {
+
+ TraceClosest(ray, gl_RayFlagsOpaqueEXT, cullMask, tMin, tMax);
+
+}
+
+// Transparent geometry is resolved by the any hit stage
+void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
+
+ TraceClosest(ray, gl_RayFlagsNoneEXT, cullMask, tMin, tMax);
+
+}
+#else
+void SetCommittedHitGeometry(inout Ray ray, rayQueryEXT rayQuery) {
+
+ ray.hitBarycentrics = rayQueryGetIntersectionBarycentricsEXT(rayQuery, true);
+#ifdef AE_POSITION_FETCH
+ vec3 positions[3];
+ rayQueryGetIntersectionTriangleVertexPositionsEXT(rayQuery, true, positions);
+ ray.hitGeometryNormal = GetTriangleNormal(positions[0], positions[1], positions[2]);
+#endif
+
+}
+
void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) {
ray.hitDistance = tMax;
rayQueryEXT rayQuery;
- rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsNoneEXT, cullMask,
+ // Every candidate would be confirmed anyway, opaque rays keep the traversal in hardware
+ rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsOpaqueEXT, cullMask,
ray.origin, tMin, ray.direction, tMax);
// Start traversal: return false if traversal is complete
@@ -545,20 +595,24 @@ void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) {
ray.hitDistance = rayQueryGetIntersectionTEXT(rayQuery, true);
ray.hitInstanceID = rayQueryGetIntersectionInstanceIdEXT(rayQuery, true);
- int geometryOffset = rayQueryGetIntersectionGeometryIndexEXT(rayQuery, false);
- int meshIdx = rayQueryGetIntersectionInstanceCustomIndexEXT(rayQuery, false);
+ int geometryOffset = rayQueryGetIntersectionGeometryIndexEXT(rayQuery, true);
+ int meshIdx = rayQueryGetIntersectionInstanceCustomIndexEXT(rayQuery, true);
int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]);
ray.hitID = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, true) + triangleOffset;
+
+ SetCommittedHitGeometry(ray, rayQuery);
}
}
+#endif
+
bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) {
ray.hitDistance = tMax;
rayQueryEXT rayQuery;
- rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsTerminateOnFirstHitEXT, cullMask,
+ rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsTerminateOnFirstHitEXT | gl_RayFlagsOpaqueEXT, cullMask,
ray.origin, tMin, ray.direction, tMax);
// Start traversal: return false if traversal is complete
@@ -577,6 +631,7 @@ bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) {
}
+#ifndef RAY_TRACING_PIPELINE
void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
ray.hitDistance = tMax;
@@ -603,7 +658,7 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax
Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]);
- if (GetOpacity(tri, barrycentric, materialOffset, 0) > 0.001) {
+ if (GetCutoutOpacity(tri, barrycentric, materialOffset, 0) >= opacityCutoff) {
rayQueryConfirmIntersectionEXT(rayQuery);
}
@@ -620,10 +675,14 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax
int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]);
ray.hitID = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, true) + triangleOffset;
+
+ SetCommittedHitGeometry(ray, rayQuery);
}
}
+#endif
+
float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
float transparency = 1.0;
@@ -667,4 +726,27 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) {
return transparency;
}
-#endif
\ No newline at end of file
+#endif
+
+// Non-opaque geometry is alpha tested with OPACITY_CHECK
+void HitClosestOpacityCheck(inout Ray ray, uint cullMask, float tMin, float tMax) {
+
+#ifdef OPACITY_CHECK
+ HitClosestTransparency(ray, cullMask, tMin, tMax);
+#else
+ HitClosest(ray, cullMask, tMin, tMax);
+#endif
+
+}
+
+// Rays of the ray buffer are traced in a separate pass by compute pipelines, ray tracing pipelines trace them here
+void TraceBufferedRay(inout Ray ray) {
+
+#ifdef RAY_TRACING_PIPELINE
+ ray.hitID = -1;
+ ray.hitDistance = 0.0;
+ if (ray.ID >= 0)
+ HitClosestOpacityCheck(ray, INSTANCE_MASK_CLOSEST, 0.0, INF);
+#endif
+
+}
diff --git a/data/shader/raytracer/common.hsh b/data/shader/raytracer/common.hsh
index 3cfdb5b6e..faa9765fa 100644
--- a/data/shader/raytracer/common.hsh
+++ b/data/shader/raytracer/common.hsh
@@ -1,4 +1,5 @@
#include
+#include <../globals.hsh>
#include <../common/random.hsh>
#include <../common/PI.hsh>
#include <../common/packing.hsh>
@@ -15,6 +16,17 @@
#define INSTANCE_MASK_ALL (1 << 7)
#define INSTANCE_MASK_SHADOW (1 << 6)
+// Meshes with only translucent materials, rays without TRANSLUCENT_HITS would see them as opaque without an opacity check
+#define INSTANCE_MASK_TRANSLUCENT (1 << 5)
+#define INSTANCE_MASK_TRANSLUCENT_SHADOW (1 << 4)
+
+// The instances of closest hits, and of shadow rays which pass translucent surfaces by their opacity
+#ifdef TRANSLUCENT_HITS
+#define INSTANCE_MASK_CLOSEST (INSTANCE_MASK_ALL | INSTANCE_MASK_TRANSLUCENT)
+#else
+#define INSTANCE_MASK_CLOSEST INSTANCE_MASK_ALL
+#endif
+#define INSTANCE_MASK_SHADOW_TRANSPARENCY (INSTANCE_MASK_SHADOW | INSTANCE_MASK_TRANSLUCENT_SHADOW)
Triangle UnpackTriangle(PackedTriangle triangle) {
Triangle tri;
@@ -56,6 +68,9 @@ Ray UnpackRay(PackedRay compressed) {
ray.hitDistance = compressed.hit.x;
ray.hitInstanceID = floatBitsToInt(compressed.hit.z);
+ ray.hitBarycentrics = unpackUnorm2x16(floatBitsToUint(compressed.direction.w));
+ ray.hitGeometryNormal = unpackUnitVector(floatBitsToInt(compressed.hit.w)).xyz;
+
return ray;
}
@@ -70,6 +85,9 @@ PackedRay PackRay(Ray ray) {
compressed.hit.y = intBitsToFloat(ray.hitID);
compressed.hit.z = intBitsToFloat(ray.hitInstanceID);
+ compressed.direction.w = uintBitsToFloat(packUnorm2x16(ray.hitBarycentrics));
+ compressed.hit.w = intBitsToFloat(packUnitVector(ray.hitGeometryNormal));
+
return compressed;
}
@@ -106,7 +124,8 @@ Light UnpackLight(PackedLight compressed) {
light.P = compressed.P.xyz;
light.N = normalize(compressed.N.xyz);
- light.radiance = compressed.color.rgb;
+ // The lights of ray tracing are built once, the pre-exposure follows the camera
+ light.radiance = compressed.color.rgb * globalData.preExposure;
uint data0 = floatBitsToUint(compressed.data.x);
uint data1 = floatBitsToUint(compressed.P.w);
diff --git a/data/shader/raytracer/deferredShadow.hsh b/data/shader/raytracer/deferredShadow.hsh
new file mode 100644
index 000000000..c7de03bd5
--- /dev/null
+++ b/data/shader/raytracer/deferredShadow.hsh
@@ -0,0 +1,32 @@
+// The radiance of each sample is clamped, so the result can only be put together after the shadow rays are traced
+
+struct DeferredSample {
+ // w: 1.0 if the sample is valid, -1.0 in the first sample of a pixel which isn't ray traced
+ vec4 radiance;
+ // w: radiance limit
+ vec4 lobeWeight;
+};
+
+struct DeferredShadowRay {
+ // xyz: origin, w: maximum distance
+ vec4 origin;
+ // w: index of the light
+ vec4 direction;
+};
+
+layout(std430, set = 3, binding = 12) buffer DeferredSamples {
+ DeferredSample deferredSamples[];
+};
+
+// rgb: direct light, w: transparency along the shadow ray
+layout(std430, set = 3, binding = 13) buffer DeferredLights {
+ vec4 deferredLights[];
+};
+
+layout(std430, set = 3, binding = 14) buffer DeferredShadowRays {
+ DeferredShadowRay deferredShadowRays[];
+};
+
+layout(std430, set = 3, binding = 15) buffer DeferredShadowRayCount {
+ uint deferredShadowRayCount;
+};
diff --git a/data/shader/raytracer/deform.csh b/data/shader/raytracer/deform.csh
new file mode 100644
index 000000000..942b05c1b
--- /dev/null
+++ b/data/shader/raytracer/deform.csh
@@ -0,0 +1,167 @@
+// Deforms vertices for hardware ray tracing like deferred/geometry.vsh (skinning, graph vertex offset, wind) into the
+// positions of the instance BLAS and the normals the hits read. Material graphs include it after their vertex functions
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+#include <../globals.hsh>
+#include <../wind.hsh>
+#include <../common/packing.hsh>
+#include <../common/rotation.hsh>
+#include <../common/texCoord.hsh>
+
+// Has to match the group size of the deformation pass in RayTracingWorld
+layout (local_size_x = 64) in;
+
+// Has to match GPUDeformVertex in RTStructures.h
+struct DeformVertex {
+ // Position and the packed normal in w
+ vec4 position;
+ // Packed tangent with the handedness in w
+ uint tangent;
+ uint texCoord;
+ uint color;
+ uint weights;
+ uint joints01;
+ uint joints23;
+ uint texCoord1;
+ uint padding0;
+};
+
+// One deformed vertex range of an instance, has to match GPUDeformJob in RTStructures.h
+struct DeformJob {
+ mat3x4 matrix;
+ uvec2 sourceVertices;
+ uvec2 positions;
+ uvec2 normals;
+ uint firstGroup;
+ uint vertexOffset;
+ uint vertexCount;
+ uint deformOffset;
+ float windBendScale;
+ float windWiggleScale;
+ float windTextureLod;
+ uint materialGraphOffset;
+ uint invertUVs;
+ float uvTiling;
+ vec2 uvAnimation;
+ uint hasTexCoords1;
+ uint padding0;
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer DeformVertexBuffer {
+ DeformVertex vertices[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer PositionBuffer {
+ float positions[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 8) writeonly buffer NormalBuffer {
+ uvec2 normals[];
+};
+
+layout(std430, set = 3, binding = 0) readonly buffer DeformJobs {
+ DeformJob deformJobs[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer JointMatrices {
+ mat3x4 jointMatrices[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer GroupJobs {
+ uint groupJobs[];
+};
+
+#ifdef WIND
+layout(set = 3, binding = 3) uniform sampler2D windNoiseMap;
+#endif
+
+#ifdef SOFT_BODY
+// Positions with the packed normal in w
+layout(std430, set = 3, binding = 4) readonly buffer SoftBodyVertices {
+ vec4 softBodyVertices[];
+};
+#endif
+
+layout(push_constant) uniform constants {
+ uint groupOffset;
+ uint groupCount;
+} PushConstants;
+
+void main() {
+
+ uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
+ if (group >= PushConstants.groupCount)
+ return;
+
+ DeformJob job = deformJobs[groupJobs[PushConstants.groupOffset + group]];
+ uint idx = (group - job.firstGroup) * gl_WorkGroupSize.x + gl_LocalInvocationIndex;
+ if (idx >= job.vertexCount)
+ return;
+
+ uint vertexIdx = job.vertexOffset + idx;
+ DeformVertex vertex = DeformVertexBuffer(job.sourceVertices).vertices[vertexIdx];
+
+ vec3 position = vertex.position.xyz;
+ vec3 normal = unpackUnitVector(floatBitsToInt(vertex.position.w)).xyz;
+ vec4 tangent = unpackUnitVector(int(vertex.tangent));
+
+ mat4 mMatrix = mat4(transpose(job.matrix));
+
+#ifdef SKINNED
+ uvec4 joints = uvec4(vertex.joints01 & 0xFFFFu, vertex.joints01 >> 16u, vertex.joints23 & 0xFFFFu, vertex.joints23 >> 16u);
+ vec4 weights = unpackUnorm4x8(vertex.weights);
+ weights /= dot(weights, vec4(1.0));
+
+ mat3x4 skinMatrix = weights.x * jointMatrices[job.deformOffset + joints.x] +
+ weights.y * jointMatrices[job.deformOffset + joints.y] +
+ weights.z * jointMatrices[job.deformOffset + joints.z] +
+ weights.w * jointMatrices[job.deformOffset + joints.w];
+
+ position = vec4(position, 1.0) * skinMatrix;
+ normal = vec4(normal, 0.0) * skinMatrix;
+ tangent.xyz = vec4(tangent.xyz, 0.0) * skinMatrix;
+#endif
+
+#ifdef SOFT_BODY
+ // The vertices of the body start at the joint offset
+ vec4 softBodyVertex = softBodyVertices[job.deformOffset + vertexIdx];
+ vec3 restNormal = normal;
+ position = softBodyVertex.xyz;
+ normal = unpackUnitVector(floatBitsToInt(softBodyVertex.w)).xyz;
+ tangent.xyz = RotateLike(tangent.xyz, normalize(restNormal), normal);
+#endif
+
+#ifdef MATERIAL_GRAPH_VERTEX_OFFSET
+ vec2 texCoord = unpackHalf2x16(vertex.texCoord);
+ texCoord = TransformTexCoord(texCoord, job.invertUVs > 0u, job.uvAnimation, job.uvTiling);
+
+ // Meshes without tangents use the same default as the rasterizer
+ vec3 graphTangent = dot(tangent.xyz, tangent.xyz) > 0.01 ? tangent.xyz : vec3(1.0, 0.0, 0.0);
+
+ // Zero without a second set, like the rasterizer
+ vec2 texCoord1 = unpackHalf2x16(vertex.texCoord1);
+ texCoord1 = job.invertUVs > 0u && job.hasTexCoords1 > 0u ? vec2(texCoord1.x, 1.0 - texCoord1.y) : texCoord1;
+
+ MaterialVertexInput graphInput = CreateMaterialVertexInput(vertex.position.xyz, position, normal, graphTangent,
+ texCoord, texCoord1, unpackUnorm4x8(vertex.color), mMatrix, globalData.time, job.materialGraphOffset);
+ normal = EvaluateMaterialVertexNormal(graphInput);
+ position += EvaluateMaterialVertexOffset(graphInput);
+#endif
+
+#ifdef WIND
+ vec3 windPosition = vec3(mMatrix * vec4(position, 1.0));
+ position = WindAnimation(windNoiseMap, position, GetWindDirection(mMatrix), job.windBendScale,
+ job.windWiggleScale, job.windTextureLod, globalData.time, windPosition);
+#endif
+
+ PositionBuffer positions = PositionBuffer(job.positions);
+ positions.positions[vertexIdx * 3u + 0u] = position.x;
+ positions.positions[vertexIdx * 3u + 1u] = position.y;
+ positions.positions[vertexIdx * 3u + 2u] = position.z;
+
+ float tangentLength = length(tangent.xyz);
+ tangent.xyz = tangentLength > 0.0 ? tangent.xyz / tangentLength : vec3(0.0);
+ NormalBuffer(job.normals).normals[vertexIdx] = uvec2(packUnitVector(normalize(normal)), packUnitVector(tangent));
+
+}
diff --git a/data/shader/raytracer/deformTriangles.csh b/data/shader/raytracer/deformTriangles.csh
new file mode 100644
index 000000000..729142443
--- /dev/null
+++ b/data/shader/raytracer/deformTriangles.csh
@@ -0,0 +1,113 @@
+// Gathers the vertices deformed by deform.csh into the triangles of a software BLAS, hardware ray tracing builds
+// its BLAS from the deformed positions directly
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+#include
+#include <../common/packing.hsh>
+
+// Has to match the group size of the triangle pass in RayTracingWorld
+layout (local_size_x = 64) in;
+
+// Has to match GPUDeformTriangleJob in RTStructures.h
+struct DeformTriangleJob {
+ uvec2 triangleVertices;
+ uvec2 positions;
+ uvec2 normals;
+ uvec2 triangles;
+ uvec2 bvhTriangles;
+ uint firstGroup;
+ uint triangleCount;
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer TriangleVertexBuffer {
+ uvec4 triangleVertices[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer PositionBuffer {
+ float positions[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 8) readonly buffer NormalBuffer {
+ uvec2 normals[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 16) buffer TriangleBuffer {
+ PackedTriangle triangles[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 16) buffer BVHTriangleBuffer {
+ PackedBVHTriangle bvhTriangles[];
+};
+
+layout(std430, set = 3, binding = 0) readonly buffer TriangleJobs {
+ DeformTriangleJob triangleJobs[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer GroupJobs {
+ uint groupJobs[];
+};
+
+layout(push_constant) uniform constants {
+ uint groupOffset;
+ uint groupCount;
+} PushConstants;
+
+void main() {
+
+ uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
+ if (group >= PushConstants.groupCount)
+ return;
+
+ DeformTriangleJob job = triangleJobs[groupJobs[PushConstants.groupOffset + group]];
+ uint idx = (group - job.firstGroup) * gl_WorkGroupSize.x + gl_LocalInvocationIndex;
+ if (idx >= job.triangleCount)
+ return;
+
+ PositionBuffer deformedPositions = PositionBuffer(job.positions);
+ NormalBuffer deformedNormals = NormalBuffer(job.normals);
+ uvec4 vertexIndices = TriangleVertexBuffer(job.triangleVertices).triangleVertices[idx];
+
+ vec3 positions[3];
+ vec3 normals[3];
+ for (int i = 0; i < 3; i++) {
+ uint vertexIdx = vertexIndices[i];
+ positions[i] = vec3(deformedPositions.positions[vertexIdx * 3u], deformedPositions.positions[vertexIdx * 3u + 1u],
+ deformedPositions.positions[vertexIdx * 3u + 2u]);
+ normals[i] = unpackUnitVector(int(deformedNormals.normals[vertexIdx].x)).xyz;
+ }
+
+ TriangleBuffer triangles = TriangleBuffer(job.triangles);
+ vec4 texCoords = triangles.triangles[idx].d0;
+ vec2 uv0 = unpackHalf2x16(floatBitsToUint(texCoords.x));
+ vec2 uv1 = unpackHalf2x16(floatBitsToUint(texCoords.y));
+ vec2 uv2 = unpackHalf2x16(floatBitsToUint(texCoords.z));
+
+ // Same tangent frame as the triangles built on the CPU
+ vec3 v0v1 = positions[1] - positions[0];
+ vec3 v0v2 = positions[2] - positions[0];
+ vec2 uv0uv1 = uv1 - uv0;
+ vec2 uv0uv2 = uv2 - uv0;
+
+ float r = 1.0 / (uv0uv1.x * uv0uv2.y - uv0uv2.x * uv0uv1.y);
+
+ vec3 s = (uv0uv2.y * v0v1 - uv0uv1.y * v0v2) * r;
+ vec3 t = (uv0uv1.x * v0v2 - uv0uv2.x * v0v1) * r;
+
+ vec3 normal = normalize(normals[0] + normals[1] + normals[2]);
+
+ vec3 tangent = normalize(s - normal * dot(normal, s));
+ float handedness = dot(cross(tangent, normal), t) < 0.0 ? 1.0 : -1.0;
+ vec3 bitangent = handedness * normalize(cross(tangent, normal));
+
+ triangles.triangles[idx].v0 = vec4(positions[0], intBitsToFloat(packUnitVector(normals[0])));
+ triangles.triangles[idx].v1 = vec4(positions[1], intBitsToFloat(packUnitVector(normals[1])));
+ triangles.triangles[idx].v2 = vec4(positions[2], intBitsToFloat(packUnitVector(normals[2])));
+ triangles.triangles[idx].d1.xy = vec2(intBitsToFloat(packUnitVector(tangent)), intBitsToFloat(packUnitVector(bitangent)));
+
+ BVHTriangleBuffer bvhTriangles = BVHTriangleBuffer(job.bvhTriangles);
+ bvhTriangles.bvhTriangles[idx].v0.xyz = positions[0];
+ bvhTriangles.bvhTriangles[idx].v1.xyz = positions[1];
+ bvhTriangles.bvhTriangles[idx].v2.xyz = positions[2];
+
+}
diff --git a/data/shader/raytracer/direct.hsh b/data/shader/raytracer/direct.hsh
index 22d190681..3fb5eee54 100644
--- a/data/shader/raytracer/direct.hsh
+++ b/data/shader/raytracer/direct.hsh
@@ -4,6 +4,7 @@
#include
#include
#include <../common/random.hsh>
+#include <../common/light.hsh>
int GetLightCount() {
return PushConstants.lightCount;
@@ -33,21 +34,18 @@ Light GetLight(Surface surface, float seed0, float seed1, out float lightPdf) {
weight = light.brightness;
}
else if (light.type == uint(POINT_LIGHT)) {
- vec3 pointToLight = light.P - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- float lightDistance = sqrt(sqrDistance);
+ float lightDistance = distance(light.P, surface.P);
- weight = light.brightness * light.radius / sqrDistance;
+ weight = light.brightness * GetDistanceAttenuation(lightDistance, light.radius);
}
else if (light.type == uint(SPOT_LIGHT)) {
vec3 pointToLight = light.P - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- float lightDistance = sqrt(sqrDistance);
+ float lightDistance = length(pointToLight);
vec3 L = pointToLight / lightDistance;
- float NdotL = max(dot(light.N, -L), 0.0);
+ float angleAttenuation = saturate(dot(light.N, -L) * light.angleScale + light.angleOffset);
- weight = light.brightness * NdotL / sqrDistance;
+ weight = light.brightness * sqr(angleAttenuation) * GetDistanceAttenuation(lightDistance, light.radius);
}
weight = clamp(weight, 0.0000001, 1000000000000.0);
@@ -103,24 +101,21 @@ void SampleLight(Light light, inout Surface surface, float seed0, float seed1,
}
else if (light.type == uint(POINT_LIGHT)) {
vec3 pointToLight = light.P - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- dist = sqrt(sqrDistance);
+ dist = length(pointToLight);
- float attenuation = saturate(1.0 - pow(dist / light.radius, 4.0));
- solidAngle = attenuation / sqrDistance;
+ solidAngle = GetDistanceAttenuation(dist, light.radius);
surface.L = pointToLight / dist;
UpdateSurface(surface);
}
else if (light.type == uint(SPOT_LIGHT)) {
vec3 pointToLight = light.P - surface.P;
- float sqrDistance = dot(pointToLight, pointToLight);
- dist = sqrt(sqrDistance);
+ dist = length(pointToLight);
surface.L = pointToLight / dist;
float strength = dot(surface.L, -light.N);
- float attenuation = saturate(strength * light.angleScale + light.angleOffset);
- solidAngle = sqr(attenuation) / sqrDistance;
+ float angleAttenuation = saturate(strength * light.angleScale + light.angleOffset);
+ solidAngle = sqr(angleAttenuation) * GetDistanceAttenuation(dist, light.radius);
UpdateSurface(surface);
}
diff --git a/data/shader/raytracer/graphHit.hsh b/data/shader/raytracer/graphHit.hsh
new file mode 100644
index 000000000..44eea2b6b
--- /dev/null
+++ b/data/shader/raytracer/graphHit.hsh
@@ -0,0 +1,20 @@
+// Data exchanged between the surface of hits and the hit shader of a material graph, see graphHit.rchit
+
+struct MaterialGraphHit {
+ // Tangent, bitangent and normal in world space, the hit shader gets positions and transforms from the hit object
+ mat3 tangentFrame;
+ // Vertex color packed as unorm 4x8
+ uint color;
+ vec2 texCoord;
+ float frontFacing;
+ float textureLevel;
+ uint parameterOffset;
+
+ vec3 baseColor;
+ // In tangent space
+ vec3 normal;
+ vec3 emissive;
+ float roughness;
+ float metalness;
+ float ao;
+};
diff --git a/data/shader/raytracer/graphHit.rchit b/data/shader/raytracer/graphHit.rchit
new file mode 100644
index 000000000..21dc28433
--- /dev/null
+++ b/data/shader/raytracer/graphHit.rchit
@@ -0,0 +1,39 @@
+// Evaluates the surface of a material graph for a hit of a ray tracing pipeline, the ray generation stage executes it
+// with the hit object of the ray. The shaders generated from graphs include this file after their surface function,
+// see materialgraph/Compiler
+#extension GL_EXT_ray_tracing : require
+
+#include
+
+layout(location = 1) rayPayloadInEXT MaterialGraphHit graphHit;
+
+void main() {
+
+ materialGraphHitTextureLevel = graphHit.textureLevel;
+
+ mat4 modelMatrix = mat4(gl_ObjectToWorldEXT);
+ mat3 tangentFrame = graphHit.tangentFrame;
+
+ vec3 worldPosition = gl_WorldRayOriginEXT + gl_HitTEXT * gl_WorldRayDirectionEXT;
+ vec3 objectPosition = gl_ObjectRayOriginEXT + gl_HitTEXT * gl_ObjectRayDirectionEXT;
+ vec3 objectNormal = normalize(tangentFrame[2] * mat3(modelMatrix));
+
+ MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(objectPosition, objectNormal, worldPosition,
+ tangentFrame[2], vec3(modelMatrix[3]), mat3(globalData.vMatrix) * tangentFrame, graphHit.texCoord, vec2(0.5),
+ unpackUnorm4x8(graphHit.color), graphHit.frontFacing, graphHit.parameterOffset);
+
+ // Rays see the surface from their origin, not from the camera
+ surfaceIn.viewDirection = -gl_WorldRayDirectionEXT;
+ surfaceIn.tangent = normalize(transpose(mat3(modelMatrix)) * tangentFrame[0]);
+ surfaceIn.modelMatrix = modelMatrix;
+
+ MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn);
+
+ graphHit.baseColor = surface.baseColor;
+ graphHit.normal = surface.normal;
+ graphHit.emissive = surface.emissive;
+ graphHit.roughness = surface.roughness;
+ graphHit.metalness = surface.metalness;
+ graphHit.ao = surface.ao;
+
+}
diff --git a/data/shader/raytracer/graphOpacity.rahit b/data/shader/raytracer/graphOpacity.rahit
new file mode 100644
index 000000000..2f524089c
--- /dev/null
+++ b/data/shader/raytracer/graphOpacity.rahit
@@ -0,0 +1,67 @@
+// Alpha tests the candidate hits of a material graph with an opacity like opacity.rahit does for other materials. The
+// shaders generated from graphs include this file after their surface function, see materialgraph/Compiler
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_nonuniform_qualifier : require
+
+#include
+#include <../common/random.hsh>
+
+hitAttributeEXT vec2 barycentrics;
+
+void main() {
+
+ int meshIdx = gl_InstanceCustomIndexEXT;
+ int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(gl_GeometryIndexEXT)]);
+ int hitID = gl_PrimitiveID + triangleOffset;
+
+ Instance instance = bvhInstances[nonuniformEXT(gl_InstanceID)];
+ Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]);
+ RaytraceMaterial rayMat = materials[nonuniformEXT(tri.materialIndex + instance.materialOffset)];
+#ifndef TRANSLUCENT_HITS
+ // Rays pass through translucent surfaces
+ if (rayMat.blendMode != blendModeNone)
+ ignoreIntersectionEXT;
+#endif
+
+ float s = barycentrics.x;
+ float t = barycentrics.y;
+ float r = 1.0 - s - t;
+
+ vec2 texCoord = r * tri.uv0 + s * tri.uv1 + t * tri.uv2;
+ texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling);
+ vec4 color = r * tri.color0 + s * tri.color1 + t * tri.color2;
+
+ mat4 modelMatrix = mat4(gl_ObjectToWorldEXT);
+ vec3 objectNormal = normalize(r * tri.n0 + s * tri.n1 + t * tri.n2);
+ vec3 worldNormal = normalize(transpose(mat3(gl_WorldToObjectEXT)) * objectNormal);
+ vec3 worldPosition = gl_WorldRayOriginEXT + gl_HitTEXT * gl_WorldRayDirectionEXT;
+ vec3 objectPosition = gl_ObjectRayOriginEXT + gl_HitTEXT * gl_ObjectRayDirectionEXT;
+
+ vec3 bitangent = rayMat.invertUVs > 0 ? tri.bt : -tri.bt;
+ mat3 tangentFrame = mat3(normalize(mat3(modelMatrix) * tri.t), normalize(mat3(modelMatrix) * bitangent), worldNormal);
+ float frontFacing = gl_HitKindEXT == gl_HitKindFrontFacingTriangleEXT ? 1.0 : -1.0;
+
+ materialGraphHitTextureLevel = 0.0;
+ MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(objectPosition, objectNormal, worldPosition, worldNormal,
+ vec3(modelMatrix[3]), mat3(globalData.vMatrix) * tangentFrame, texCoord, vec2(0.5), color, frontFacing,
+ rayMat.graphParameterOffset);
+
+ // Rays see the surface from their origin, not from the camera
+ surfaceIn.viewDirection = -gl_WorldRayDirectionEXT;
+ surfaceIn.tangent = normalize(tri.t);
+ surfaceIn.modelMatrix = modelMatrix;
+
+ float opacity = EvaluateMaterialSurface(surfaceIn).opacity;
+#ifdef TRANSLUCENT_HITS
+ // The path tracer blends the opacity of translucent materials itself, the one of the graph decides which hits it sees
+ if (rayMat.blendMode != blendModeNone) {
+ uint seed = hash(uvec4(gl_LaunchIDEXT.xy, floatBitsToUint(gl_HitTEXT), uint(globalData.frameCount)));
+ if (opacity <= floatConstruct(seed))
+ ignoreIntersectionEXT;
+ return;
+ }
+#endif
+ if (opacity < opacityCutoff)
+ ignoreIntersectionEXT;
+
+}
diff --git a/data/shader/raytracer/lighting.hsh b/data/shader/raytracer/lighting.hsh
new file mode 100644
index 000000000..a2c4dca78
--- /dev/null
+++ b/data/shader/raytracer/lighting.hsh
@@ -0,0 +1,96 @@
+// Direct light at the hits of RTGI and reflections. With DEFERRED_SHADOW_RAYS the shadow rays are written out and
+// traced in a separate pass. Needs the cloud map with CLOUD_SHADOWS
+#ifdef DEFERRED_SHADOW_RAYS
+#include
+
+bool hasDeferredShadowRay = false;
+DeferredShadowRay deferredShadowRay;
+int deferredLightBase = 0;
+#endif
+
+float CheckVisibility(Surface surface, float lightDistance) {
+
+ if (surface.NdotL > 0.0) {
+ Ray ray;
+ ray.direction = surface.L;
+ float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0;
+ ray.origin = surface.P + surface.geometryNormal * (side * EPSILON);
+#ifdef DEFERRED_SHADOW_RAYS
+ hasDeferredShadowRay = true;
+ deferredShadowRay.origin = vec4(ray.origin, lightDistance - 2.0 * EPSILON);
+ deferredShadowRay.direction = vec4(ray.direction, 0.0);
+ return 1.0;
+#else
+ return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, lightDistance - 2.0 * EPSILON);
+#endif
+ }
+ else {
+ return 0.0;
+ }
+
+}
+
+vec3 EvaluateDirectLight(inout Surface surface, float raySeed, float seed) {
+
+ if (GetLightCount() == 0)
+ return vec3(0.0);
+
+ float lightPdf;
+ Light light = GetLight(surface, raySeed, seed, lightPdf);
+
+ float solidAngle, lightDistance;
+ SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance);
+
+ bool transmittedLight = IsTransmittedLight(surface);
+ Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface;
+
+ // Evaluate the BRDF
+ vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) :
+ EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface);
+ reflectance *= surface.material.opacity;
+ vec3 radiance = light.radiance * solidAngle;
+
+ // The visibility is needed to estimate the solid angle of the light from the surface
+ if (light.castShadow)
+ radiance *= CheckVisibility(lightSurface, lightDistance);
+
+#ifdef CLOUD_SHADOWS
+ if (light.type == uint(DIRECTIONAL_LIGHT)) {
+ vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0));
+ float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap);
+
+ radiance *= cloudShadowFactor;
+ }
+#endif
+
+ return reflectance * radiance * lightSurface.NdotL / lightPdf;
+
+}
+
+// The average of several light samples, deferred shadow rays store their sample instead
+vec3 EvaluateDirectLights(inout Surface surface, float raySeed, float seed, int lightSampleCount) {
+
+ vec3 radiance = vec3(0.0);
+ for (int i = 0; i < lightSampleCount; i++) {
+#ifdef DEFERRED_SHADOW_RAYS
+ hasDeferredShadowRay = false;
+ vec3 direct = EvaluateDirectLight(surface, raySeed, seed) / float(lightSampleCount);
+ if (hasDeferredShadowRay) {
+ uint lightIdx = uint(deferredLightBase + i);
+ deferredLights[lightIdx] = vec4(direct, 1.0);
+ uint shadowRayIdx = atomicAdd(deferredShadowRayCount, 1u);
+ deferredShadowRays[shadowRayIdx].origin = deferredShadowRay.origin;
+ deferredShadowRays[shadowRayIdx].direction = vec4(deferredShadowRay.direction.xyz, uintBitsToFloat(lightIdx));
+ }
+ else {
+ radiance += direct;
+ }
+#else
+ radiance += EvaluateDirectLight(surface, raySeed, seed) / float(lightSampleCount);
+#endif
+ seed += 1.0 / float(lightSampleCount);
+ }
+
+ return radiance;
+
+}
diff --git a/data/shader/raytracer/miss.rmiss b/data/shader/raytracer/miss.rmiss
new file mode 100644
index 000000000..869c9cd53
--- /dev/null
+++ b/data/shader/raytracer/miss.rmiss
@@ -0,0 +1,8 @@
+// Hit objects don't invoke miss shaders, the pipeline just needs one
+#extension GL_EXT_ray_tracing : require
+
+layout(location = 0) rayPayloadInEXT uvec2 unusedPayload;
+
+void main() {
+
+}
diff --git a/data/shader/raytracer/opacity.rahit b/data/shader/raytracer/opacity.rahit
new file mode 100644
index 000000000..d9721fc4b
--- /dev/null
+++ b/data/shader/raytracer/opacity.rahit
@@ -0,0 +1,22 @@
+// Alpha tests the candidate hits of non-opaque geometry like HitClosestTransparency in bvh.hsh
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_nonuniform_qualifier : require
+
+#include
+#include <../common/opacity.hsh>
+
+hitAttributeEXT vec2 barycentrics;
+
+void main() {
+
+ int meshIdx = gl_InstanceCustomIndexEXT;
+ int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(gl_GeometryIndexEXT)]);
+ int hitID = gl_PrimitiveID + triangleOffset;
+
+ int materialOffset = bvhInstances[nonuniformEXT(gl_InstanceID)].materialOffset;
+ Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]);
+
+ if (GetCutoutOpacity(tri, barycentrics, materialOffset, 0) < opacityCutoff)
+ ignoreIntersectionEXT;
+
+}
diff --git a/data/shader/raytracer/refitBVH.csh b/data/shader/raytracer/refitBVH.csh
new file mode 100644
index 000000000..4632126d4
--- /dev/null
+++ b/data/shader/raytracer/refitBVH.csh
@@ -0,0 +1,78 @@
+#include
+
+// Updates the bounds of a BVH with a fixed topology. Each dispatch updates the nodes of one tree level,
+// starting with the deepest level, such that the bounds of the child nodes are always up to date.
+
+layout (local_size_x = 64) in;
+
+layout(std430, set = 3, binding = 0) buffer Nodes {
+ PackedBVHNode nodes[];
+};
+
+layout(std430, set = 3, binding = 1) readonly buffer BVHTriangles {
+ PackedBVHTriangle bvhTriangles[];
+};
+
+layout(std430, set = 3, binding = 2) readonly buffer LevelNodes {
+ int levelNodes[];
+};
+
+// Bounds of each node (min, max) for its parent
+layout(std430, set = 3, binding = 3) buffer NodeBounds {
+ vec4 nodeBounds[];
+};
+
+layout(push_constant) uniform constants {
+ uint nodeOffset;
+ uint nodeCount;
+} PushConstants;
+
+void GetChildBounds(int nodePtr, out vec3 boundsMin, out vec3 boundsMax) {
+
+ if (nodePtr >= 0) {
+ boundsMin = nodeBounds[2 * nodePtr].xyz;
+ boundsMax = nodeBounds[2 * nodePtr + 1].xyz;
+ return;
+ }
+
+ boundsMin = vec3(1e30);
+ boundsMax = vec3(-1e30);
+
+ int triPtr = ~nodePtr;
+ bool endOfNode = false;
+ while (!endOfNode) {
+ vec3 v0 = bvhTriangles[triPtr].v0.xyz;
+ vec3 v1 = bvhTriangles[triPtr].v1.xyz;
+ vec3 v2 = bvhTriangles[triPtr].v2.xyz;
+ endOfNode = bvhTriangles[triPtr].v0.w > 0.0;
+
+ boundsMin = min(boundsMin, min(v0, min(v1, v2)));
+ boundsMax = max(boundsMax, max(v0, max(v1, v2)));
+ triPtr++;
+ }
+
+}
+
+void main() {
+
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= PushConstants.nodeCount)
+ return;
+
+ int nodeIdx = levelNodes[PushConstants.nodeOffset + idx];
+
+ int leftPtr = floatBitsToInt(nodes[nodeIdx].data3.x);
+ int rightPtr = floatBitsToInt(nodes[nodeIdx].data3.y);
+
+ vec3 leftMin, leftMax, rightMin, rightMax;
+ GetChildBounds(leftPtr, leftMin, leftMax);
+ GetChildBounds(rightPtr, rightMin, rightMax);
+
+ nodes[nodeIdx].data0 = vec4(leftMin, leftMax.x);
+ nodes[nodeIdx].data1 = vec4(leftMax.yz, rightMin.xy);
+ nodes[nodeIdx].data2 = vec4(rightMin.z, rightMax);
+
+ nodeBounds[2 * nodeIdx] = vec4(min(leftMin, rightMin), 0.0);
+ nodeBounds[2 * nodeIdx + 1] = vec4(max(leftMax, rightMax), 0.0);
+
+}
diff --git a/data/shader/raytracer/structures.hsh b/data/shader/raytracer/structures.hsh
index 01ee80a09..4f9789cd5 100644
--- a/data/shader/raytracer/structures.hsh
+++ b/data/shader/raytracer/structures.hsh
@@ -27,6 +27,10 @@ struct Ray {
int hitInstanceID;
int currentInstanceID;
+
+ // Hardware ray tracing returns the hit point on the triangle and its object space normal
+ vec2 hitBarycentrics;
+ vec3 hitGeometryNormal;
};
struct RayPayload {
@@ -142,6 +146,21 @@ struct RaytraceMaterial {
uint transmissionColor;
+ // Hit group of a material graph in ray tracing pipelines, 0 without one
+ uint graphHitGroup;
+ uint graphParameterOffset;
+ float uvAnimationX;
+ float uvAnimationY;
+
+ // A blend mode of common/material.hsh, rays pass through translucent surfaces except with TRANSLUCENT_HITS, shadow
+ // rays are dimmed by their opacity
+ uint blendMode;
+ // Of the inside of refracting surfaces, 1 for the others
+ float refractiveIndex;
+
+ uint padding0;
+ uint padding1;
+
};
struct PackedLight {
@@ -186,6 +205,10 @@ struct Instance {
int nextInstance;
int mask;
+
+ // Device addresses of the normals of a deformed instance and the indices of its mesh, see GetTriangle
+ uvec2 deformedVertices;
+ uvec2 meshIndices;
};
struct PackedBVHNode {
@@ -207,14 +230,3 @@ struct PackedBVHTriangle {
vec4 v1;
vec4 v2;
};
-
-layout(push_constant) uniform constants {
- int lightCount;
- uint rayBufferOffset;
- uint rayPayloadBufferOffset;
- uint rayBufferSize;
- int useRayBinning;
- int padding0;
- int padding1;
- int padding2;
-} PushConstants;
diff --git a/data/shader/raytracer/surface.hsh b/data/shader/raytracer/surface.hsh
index 0db76aec2..81f18af30 100644
--- a/data/shader/raytracer/surface.hsh
+++ b/data/shader/raytracer/surface.hsh
@@ -1,4 +1,8 @@
#extension GL_EXT_nonuniform_qualifier : require
+#ifdef AE_HARDWARE_RAYTRACING
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#endif
#include
#include
@@ -6,6 +10,20 @@
#include
#include <../brdf/surface.hsh>
+#include <../common/texCoord.hsh>
+#include <../common/opacity.hsh>
+
+#ifdef RAY_TRACING_PIPELINE
+// The hit of the last ray of TraceClosest, hit objects can't be assigned or passed as out parameters
+hitObjectEXT closestHitObject;
+#endif
+
+#if defined(MATERIAL_GRAPH_HITS) && defined(RAY_TRACING_PIPELINE)
+#include
+
+// The hit groups of material graphs are executed with the hit object of the ray
+layout(location = 1) rayPayloadEXT MaterialGraphHit graphHit;
+#endif
Instance GetInstance(Ray ray) {
@@ -13,9 +31,60 @@ Instance GetInstance(Ray ray) {
}
+#ifdef AE_HARDWARE_RAYTRACING
+// Packed normal and tangent per vertex, written by the deformation pass
+layout(buffer_reference, std430, buffer_reference_align = 8) readonly buffer DeformedVertexBuffer {
+ uvec2 data[];
+};
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer MeshIndexBuffer {
+ uint data[];
+};
+
+uint GetMeshIndex(uvec2 address, uint position) {
+
+ // The lowest bit of the address marks 16 bit indices
+ MeshIndexBuffer indices = MeshIndexBuffer(uvec2(address.x & ~1u, address.y));
+ if ((address.x & 1u) == 0u)
+ return indices.data[position];
+
+ uint word = indices.data[position >> 1u];
+ return (position & 1u) > 0u ? word >> 16u : word & 0xFFFFu;
+
+}
+#endif
+
+// The triangle of the mesh with the normals of a deformed instance, hardware ray tracing gets the hit positions from
+// the acceleration structure
Triangle GetTriangle(Ray ray, Instance instance) {
- return UnpackTriangle(triangles[nonuniformEXT(instance.meshOffset)].data[nonuniformEXT(ray.hitID)]);
+ Triangle tri = UnpackTriangle(triangles[nonuniformEXT(instance.meshOffset)].data[nonuniformEXT(ray.hitID)]);
+
+#ifdef AE_HARDWARE_RAYTRACING
+ if (instance.deformedVertices != uvec2(0u)) {
+ DeformedVertexBuffer vertices = DeformedVertexBuffer(instance.deformedVertices);
+ uint firstIndex = uint(ray.hitID) * 3u;
+ uvec2 v0 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex)];
+ uvec2 v1 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex + 1u)];
+ uvec2 v2 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex + 2u)];
+
+ // The bitangent keeps the handedness of the undeformed triangle
+ float handedness = dot(cross(tri.n0 + tri.n1 + tri.n2, tri.t), tri.bt) < 0.0 ? -1.0 : 1.0;
+
+ tri.n0 = unpackUnitVector(int(v0.x)).xyz;
+ tri.n1 = unpackUnitVector(int(v1.x)).xyz;
+ tri.n2 = unpackUnitVector(int(v2.x)).xyz;
+
+ vec3 tangent = unpackUnitVector(int(v0.y)).xyz + unpackUnitVector(int(v1.y)).xyz + unpackUnitVector(int(v2.y)).xyz;
+ // Meshes without tangents have zero tangents, which unpack to almost zero
+ if (dot(tangent, tangent) > 0.01) {
+ tri.t = normalize(tangent);
+ tri.bt = handedness * normalize(cross(tri.n0 + tri.n1 + tri.n2, tri.t));
+ }
+ }
+#endif
+
+ return tri;
}
@@ -26,7 +95,7 @@ Material GetTriangleMaterial(Triangle tri, int materialOffset, out RaytraceMater
mat.ID = rayMat.ID;
mat.baseColor = vec3(rayMat.baseR, rayMat.baseG, rayMat.baseB);
- mat.emissiveColor = vec3(rayMat.emissR, rayMat.emissG, rayMat.emissB);
+ mat.emissiveColor = vec3(rayMat.emissR, rayMat.emissG, rayMat.emissB) * globalData.preExposure;
mat.transmissiveColor = unpackColorVector(int(rayMat.transmissionColor)).rgb;
mat.transmissive = any(greaterThan(mat.transmissiveColor, vec3(0.0)));
@@ -41,6 +110,9 @@ Material GetTriangleMaterial(Triangle tri, int materialOffset, out RaytraceMater
mat.normalScale = rayMat.normalScale;
mat.displacementScale = 0.0;
+ mat.blendMode = rayMat.blendMode;
+ mat.refractiveIndex = rayMat.refractiveIndex;
+
return mat;
}
@@ -48,9 +120,11 @@ void TransformTriangle(inout Triangle tri, Instance instance) {
mat4 matrix = inverse(mat4(transpose(instance.inverseMatrix)));
+#ifndef AE_HARDWARE_RAYTRACING
tri.v0 = vec3(matrix * vec4(tri.v0, 1.0));
tri.v1 = vec3(matrix * vec4(tri.v1, 1.0));
tri.v2 = vec3(matrix * vec4(tri.v2, 1.0));
+#endif
mat3 normalMatrix = transpose(mat3(transpose(instance.inverseMatrix)));
tri.n0 = normalize(normalMatrix * tri.n0);
@@ -71,13 +145,17 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray,
RaytraceMaterial rayMat;
Material mat = GetTriangleMaterial(tri, instance.materialOffset, rayMat);
- // The ray doesn't provide us with the barrycentric coordinates
- // so we intersect again.
+#ifdef AE_HARDWARE_RAYTRACING
+ float dist = ray.hitDistance;
+ vec2 barrycentric = ray.hitBarycentrics;
+#else
+ // The software traversal doesn't provide the barycentric coordinates, so we intersect again
vec3 sol;
IntersectTriangle(ray, tri.v0, tri.v1, tri.v2, sol);
float dist = sol.x;
vec2 barrycentric = sol.yz;
+#endif
float s = barrycentric.x;
float t = barrycentric.y;
@@ -89,16 +167,29 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray,
vec3 normal = normalize(r * tri.n0 + s * tri.n1 + t * tri.n2);
vec4 vertexColor = r * tri.color0 + s * tri.color1 + t * tri.color2;
+#ifdef AE_HARDWARE_RAYTRACING
+ // The normal matrix keeps the front face of transforms with reversed winding
+ mat3 normalMatrix = transpose(mat3(transpose(instance.inverseMatrix)));
+#ifdef AE_POSITION_FETCH
+ vec3 triangleNormal = normalize(normalMatrix * ray.hitGeometryNormal);
+#else
+ // The undeformed triangle of the mesh, deformed instances only use it to find the front face
+ vec3 triangleNormal = normalize(normalMatrix * cross(tri.v0 - tri.v1, tri.v0 - tri.v2));
+#endif
+#else
// Produces some problems in the bottom left corner of the Sponza scene,
// but fixes the cube. Should work in theory.
vec3 triangleNormal = normalize(cross(tri.v0 - tri.v1, tri.v0 - tri.v2));
// Transforms with reversed winding need the same front-face correction as in the rasterizer
float orientation = determinant(mat3(transpose(instance.inverseMatrix))) < 0.0 ? -1.0 : 1.0;
triangleNormal *= orientation;
+#endif
bool flipNormal = dot(triangleNormal, ray.direction) > 0.0;
bool twoSided = rayMat.twoSided > 0 || mat.transmissive;
backfaceHit = twoSided || rayMat.cullBackFaces == 0 ? false : flipNormal;
triangleNormal *= flipNormal && twoSided ? -1.0 : 1.0;
+ // Rays leave refracting surfaces through their back faces
+ mat.refractiveIndex = flipNormal ? 1.0 / mat.refractiveIndex : mat.refractiveIndex;
vec3 geometryNormal = triangleNormal;
@@ -109,33 +200,59 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray,
normal = normalize(2.0 * SampleTerrainNormalBilinear(rayMat.terrainNormalTexture, 0.0, terrainTexCoord) - 1.0);
}
- texCoord = rayMat.invertUVs > 0 ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord;
- texCoord *= rayMat.tiling;
+ texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling);
int level = textureLevel;
- //mat.opacity *= vertexColor.a;
- mat.baseColor *= rayMat.useVertexColors > 0 ? vertexColor.rgb : vec3(1.0);
- mat.baseColor *= SampleBaseColorBilinear(rayMat.baseColorTexture, float(level), texCoord);
- mat.opacity *= SampleOpacityBilinear(rayMat.opacityTexture, float(level), texCoord);
-
- mat.roughness *= SampleRoughnessBilinear(rayMat.roughnessTexture, float(level), texCoord);
- mat.metalness *= SampleMetalnessBilinear(rayMat.metalnessTexture, float(level), texCoord);
- mat.ao *= SampleAoBilinear(rayMat.aoTexture, float(level), texCoord);
- // Need to have the texture level to go to near zero, otherwise we will have light leaks
- mat.emissiveColor *= SampleEmissiveBilinear(rayMat.emissiveTexture, max(0.0, float(level - 3.0)), texCoord);
// Account for changing texture coord direction
vec3 bitangent = rayMat.invertUVs > 0 ? tri.bt : -tri.bt;
mat3 TBN = mat3(tri.t, bitangent, normal);
- // Sample normal map
- if (rayMat.normalTexture >= 0 && useNormalMaps) {
- vec3 texNormal = 2.0 * SampleNormalBilinear(rayMat.normalTexture, float(level), texCoord) - 1.0;
- texNormal = TBN * texNormal;
- // Make sure we don't divide by zero
- // The normalize function crashes the program in case of vec3(0.0)
- texNormal /= max(length(texNormal), 0.00001);
- normal = mix(normal, texNormal, saturate(mat.normalScale));
+#if defined(MATERIAL_GRAPH_HITS) && defined(RAY_TRACING_PIPELINE)
+ if (rayMat.graphHitGroup > 0u) {
+ graphHit.tangentFrame = TBN;
+ graphHit.color = packUnorm4x8(vertexColor);
+ graphHit.texCoord = texCoord;
+ graphHit.frontFacing = flipNormal ? -1.0 : 1.0;
+ graphHit.textureLevel = float(level);
+ graphHit.parameterOffset = rayMat.graphParameterOffset;
+
+ hitObjectExecuteShaderEXT(closestHitObject, 1);
+
+ // The G-buffer limits these values, an albedo above one would amplify itself in the bounces of the DDGI
+ mat.baseColor = saturate(graphHit.baseColor);
+ mat.roughness = saturate(graphHit.roughness);
+ mat.metalness = saturate(graphHit.metalness);
+ mat.ao = saturate(graphHit.ao);
+ mat.emissiveColor = graphHit.emissive * globalData.preExposure;
+
+ vec3 graphNormal = TBN * graphHit.normal;
+ if (useNormalMaps && dot(graphNormal, graphNormal) > 0.0)
+ normal = normalize(graphNormal);
+ }
+ else
+#endif
+ {
+ //mat.opacity *= vertexColor.a;
+ mat.baseColor *= rayMat.useVertexColors > 0 ? vertexColor.rgb : vec3(1.0);
+ mat.baseColor *= SampleBaseColorBilinear(rayMat.baseColorTexture, float(level), texCoord);
+ mat.opacity *= SampleOpacityBilinear(rayMat.opacityTexture, float(level), texCoord);
+
+ mat.roughness *= SampleRoughnessBilinear(rayMat.roughnessTexture, float(level), texCoord);
+ mat.metalness *= SampleMetalnessBilinear(rayMat.metalnessTexture, float(level), texCoord);
+ mat.ao *= SampleAoBilinear(rayMat.aoTexture, float(level), texCoord);
+ // Need to have the texture level to go to near zero, otherwise we will have light leaks
+ mat.emissiveColor *= SampleEmissiveBilinear(rayMat.emissiveTexture, max(0.0, float(level - 3.0)), texCoord);
+
+ // Sample normal map
+ if (rayMat.normalTexture >= 0 && useNormalMaps) {
+ vec3 texNormal = 2.0 * SampleNormalBilinear(rayMat.normalTexture, float(level), texCoord) - 1.0;
+ texNormal = TBN * texNormal;
+ // Make sure we don't divide by zero
+ // The normalize function crashes the program in case of vec3(0.0)
+ texNormal /= max(length(texNormal), 0.00001);
+ normal = mix(normal, texNormal, saturate(mat.normalScale));
+ }
}
normal = dot(normal, triangleNormal) < 0.0 && rayMat.twoSided > 0 ? -normal : normal;
@@ -161,22 +278,49 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray,
}
+// The surface of the closest hit of a ray
+Surface GetHitSurface(Ray ray, bool useNormalMaps, out bool backfaceHit, int textureLevel) {
+
+ Instance instance = GetInstance(ray);
+ Triangle tri = GetTriangle(ray, instance);
+ return GetSurfaceParameters(instance, tri, ray, useNormalMaps, backfaceHit, textureLevel);
+
+}
+
Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, bool useNormalMaps, int textureLevel) {
bool normalFlipped;
return GetSurfaceParameters(instance, tri, ray, useNormalMaps, normalFlipped, textureLevel);
}
-float GetOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) {
+float SampleMaterialOpacity(RaytraceMaterial rayMat, Triangle tri, vec2 barrycentric, int textureLevel) {
float s = barrycentric.x;
float t = barrycentric.y;
float r = 1.0 - s - t;
- RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset];
-
- float vertexAlpha = r * tri.color0.a + s * tri.color1.a + t * tri.color2.a;
vec2 texCoord = r * tri.uv0 + s * tri.uv1 + t * tri.uv2;
- texCoord = rayMat.invertUVs > 0 ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord;
+ texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling);
- return SampleOpacityBilinear(rayMat.opacityTexture, float(textureLevel), texCoord * rayMat.tiling)
- * rayMat.opacity;
+ return SampleOpacityBilinear(rayMat.opacityTexture, float(textureLevel), texCoord);
+}
+
+// Surfaces are cut out by their opacity map only, like in the raster passes. Rays pass through translucent ones,
+// the path tracer blends them itself (TRANSLUCENT_HITS)
+float GetCutoutOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) {
+ RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset];
+#ifdef TRANSLUCENT_HITS
+ if (rayMat.blendMode != blendModeNone)
+ return 1.0;
+#else
+ if (rayMat.blendMode != blendModeNone)
+ return 0.0;
+#endif
+ return SampleMaterialOpacity(rayMat, tri, barrycentric, textureLevel);
+}
+
+// The share of the light a surface blocks, translucent ones block it by their opacity, additive ones not at all
+float GetOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) {
+ RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset];
+ if (rayMat.blendMode == blendModeAdditive)
+ return 0.0;
+ return SampleMaterialOpacity(rayMat, tri, barrycentric, textureLevel) * rayMat.opacity;
}
diff --git a/data/shader/raytracer/texture.hsh b/data/shader/raytracer/texture.hsh
index 591c858ea..85953151c 100644
--- a/data/shader/raytracer/texture.hsh
+++ b/data/shader/raytracer/texture.hsh
@@ -81,12 +81,12 @@ vec3 SampleTerrainNormalBilinear(int textureId, float mip, vec2 texCoord) {
vec4 SampleEnvironmentMap(vec3 v) {
- return textureLod(environmentMap, v, 0);
+ return textureLod(environmentMap, v, 0) * globalData.skyCubemapExposure;
}
vec4 SampleEnvironmentMap(vec3 v, float lod) {
- return textureLod(environmentMap, v, lod);
+ return textureLod(environmentMap, v, lod) * globalData.skyCubemapExposure;
}
\ No newline at end of file
diff --git a/data/shader/raytracer/traceClosest.csh b/data/shader/raytracer/traceClosest.csh
index d1d00cc2a..aa1827c2c 100644
--- a/data/shader/raytracer/traceClosest.csh
+++ b/data/shader/raytracer/traceClosest.csh
@@ -22,12 +22,7 @@ void main() {
ray.hitID = -1;
ray.hitDistance = 0.0;
if (ray.ID >= 0) {
- // Find any triangle in the BVH
-#ifdef OPACITY_CHECK
- HitClosestTransparency(ray, INSTANCE_MASK_ALL, offset, INF);
-#else
- HitClosest(ray, INSTANCE_MASK_ALL, offset, INF);
-#endif
+ HitClosestOpacityCheck(ray, INSTANCE_MASK_CLOSEST, offset, INF);
}
uint writeOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize;
diff --git a/data/shader/raytracer/traceDispatch.csh b/data/shader/raytracer/traceDispatch.csh
index 142de4a8f..7c94bfc71 100644
--- a/data/shader/raytracer/traceDispatch.csh
+++ b/data/shader/raytracer/traceDispatch.csh
@@ -22,6 +22,14 @@ void main() {
dispatch.numGroupsZ = uint(1);
indirectCommands[0] = dispatch;
+
+ // Ray generation stages of ray tracing pipelines are launched per ray
+ DispatchIndirectCommand traceRays;
+ traceRays.numGroupsX = max(rayCount, uint(1));
+ traceRays.numGroupsY = uint(1);
+ traceRays.numGroupsZ = uint(1);
+
+ indirectCommands[1] = traceRays;
writeAtomic[0] = uint(0);
diff --git a/data/shader/raytracer/traceShadow.csh b/data/shader/raytracer/traceShadow.csh
new file mode 100644
index 000000000..00795aad1
--- /dev/null
+++ b/data/shader/raytracer/traceShadow.csh
@@ -0,0 +1,21 @@
+#define LOCAL_STACK
+
+#include
+#include
+
+layout (local_size_x = 32) in;
+
+void main() {
+
+ uint idx = gl_GlobalInvocationID.x;
+ if (idx >= deferredShadowRayCount)
+ return;
+
+ Ray ray;
+ ray.origin = deferredShadowRays[idx].origin.xyz;
+ ray.direction = deferredShadowRays[idx].direction.xyz;
+
+ uint lightIdx = floatBitsToUint(deferredShadowRays[idx].direction.w);
+ deferredLights[lightIdx].w = HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, deferredShadowRays[idx].origin.w);
+
+}
diff --git a/data/shader/raytracer/tracing.hsh b/data/shader/raytracer/tracing.hsh
index 708a7d240..bfd49b2c7 100644
--- a/data/shader/raytracer/tracing.hsh
+++ b/data/shader/raytracer/tracing.hsh
@@ -1,3 +1,10 @@
+// Ray generation stages of ray tracing pipelines launch one invocation per element like a compute dispatch
+#ifdef RAY_TRACING_PIPELINE
+#define INVOCATION_ID gl_LaunchIDEXT
+#else
+#define INVOCATION_ID gl_GlobalInvocationID
+#endif
+
#include
#include
#include
@@ -9,31 +16,25 @@
#include <../common/octahedron.hsh>
#include <../common/flatten.hsh>
+layout(push_constant) uniform constants {
+ int lightCount;
+ uint rayBufferOffset;
+ uint rayPayloadBufferOffset;
+ uint rayBufferSize;
+} PushConstants;
+
// We use double buffering for the ray and payload buffers,
// which means the buffer has an actual size of rayBufferSize * 2
// Also note that the payload offset is different from the ray offset
// as rays are written two times per bounce or execution, while payloads
// are just written by the shader of the user
-uint DetermineRayBin(Ray ray) {
- ivec2 coord = ivec2(UnitVectorToOctahedron(ray.direction) * 8.0);
- return Flatten2D(coord, ivec2(8));
-}
-
-Ray AddRayToBin(Ray ray) {
- if (PushConstants.useRayBinning == 0) return ray;
- uint bin = DetermineRayBin(ray);
- atomicAdd(rayBinCounters[bin], 1u);
- ray.hitID = int(bin);
- return ray;
-}
-
bool IsRayInvocationValid() {
- return gl_GlobalInvocationID.x < readAtomic[0];
+ return INVOCATION_ID.x < readAtomic[0];
}
uint GetRayInvocation() {
- return gl_GlobalInvocationID.x;
+ return INVOCATION_ID.x;
}
bool IsRayIndexValid(uint idx) {
@@ -41,12 +42,12 @@ bool IsRayIndexValid(uint idx) {
}
Ray ReadRay() {
- uint idx = (1u - PushConstants.rayBufferOffset) * PushConstants.rayBufferSize + gl_GlobalInvocationID.x;
+ uint idx = (1u - PushConstants.rayBufferOffset) * PushConstants.rayBufferSize + INVOCATION_ID.x;
return UnpackRay(rays[idx]);
}
RayPayload ReadRayPayload() {
- uint idx = (1u - PushConstants.rayPayloadBufferOffset) * PushConstants.rayBufferSize + gl_GlobalInvocationID.x;
+ uint idx = (1u - PushConstants.rayPayloadBufferOffset) * PushConstants.rayBufferSize + INVOCATION_ID.x;
return UnpackRayPayload(rayPayloads[idx]);
}
@@ -61,14 +62,12 @@ RayPayload ReadRayPayload(uint idx) {
}
void WriteRay(Ray ray) {
- ray = AddRayToBin(ray);
uint offset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize;
uint idx = atomicAdd(writeAtomic[0], uint(1)) + offset;
rays[idx] = PackRay(ray);
}
void WriteRay(Ray ray, RayPayload payload) {
- ray = AddRayToBin(ray);
uint rayOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize;
uint payloadOffset = PushConstants.rayPayloadBufferOffset * PushConstants.rayBufferSize;
uint idx = atomicAdd(writeAtomic[0], uint(1));
@@ -77,14 +76,12 @@ void WriteRay(Ray ray, RayPayload payload) {
}
void WriteRay(Ray ray, uint idx) {
- ray = AddRayToBin(ray);
idx += PushConstants.rayBufferOffset * PushConstants.rayBufferSize;
atomicAdd(writeAtomic[0], uint(1));
rays[idx] = PackRay(ray);
}
void WriteRay(Ray ray, RayPayload payload, uint idx) {
- ray = AddRayToBin(ray);
uint rayOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize;
uint payloadOffset = PushConstants.rayPayloadBufferOffset * PushConstants.rayBufferSize;
atomicAdd(writeAtomic[0], uint(1));
diff --git a/data/shader/reflection/atrous.csh b/data/shader/reflection/atrous.csh
index dfc7d130b..5261ce28c 100644
--- a/data/shader/reflection/atrous.csh
+++ b/data/shader/reflection/atrous.csh
@@ -7,6 +7,8 @@
#include <../common/material.hsh>
#include <../common/normalencode.hsh>
+#include <../common/denoiser.hsh>
+
layout (local_size_x = 16, local_size_y = 16) in;
layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage;
@@ -15,6 +17,7 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture;
layout(set = 3, binding = 3) uniform sampler2D normalTexture;
layout(set = 3, binding = 4) uniform sampler2D roughnessTexture;
layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture;
+layout(set = 3, binding = 6) uniform sampler2D historyLengthTexture;
#ifdef STEP_SIZE1
const int kernelRadius = 2;
@@ -26,6 +29,8 @@ const int kernelRadius = 4;
const int kernelRadius = 8;
#endif
+const int stepSize = kernelRadius / 2;
+
const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius);
const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius;
@@ -44,19 +49,24 @@ struct PackedPixelData {
#else
uvec4 data;
#endif
- float depth;
};
+// Separate arrays, a struct with the depth would be padded to 32 bytes and exceed 32 KB of shared memory on some devices
shared PackedPixelData pixelData[sharedDataSize];
+shared float pixelDepth[sharedDataSize];
+shared uint groupFilters;
layout(push_constant) uniform constants {
- int stepSize;
float strength;
float roughnessCutoff;
} pushConstants;
const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 };
+// In pixels, the three passes together reach 14 pixels
+const float maxBlurRadius = 16.0;
+const float minBlurRadius = 1.5;
+
PackedPixelData PackPixelData(PixelData data) {
PackedPixelData compressed;
@@ -71,8 +81,6 @@ PackedPixelData PackPixelData(PixelData data) {
compressed.data.w = packHalf2x16(vec2(data.normal.z, data.roughness));
#endif
- compressed.depth = data.depth;
-
return compressed;
}
@@ -91,7 +99,6 @@ PixelData UnpackPixelData(PackedPixelData compressed) {
data.normal.z = temp.x;
data.roughness = temp.y;
#endif
- data.depth = compressed.depth;
return data;
}
@@ -112,12 +119,15 @@ void LoadGroupSharedData() {
data.color = texelFetch(inputTexture, texel, 0);
- data.depth = texelFetch(depthTexture, texel, 0).r;
+ // Linear depth, zero marks the sky
+ float depth = texelFetch(depthTexture, texel, 0).r;
+ data.depth = depth == 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth);
data.roughness = texelFetch(roughnessTexture, texel, 0).r;
data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg);
pixelData[i] = PackPixelData(data);
+ pixelDepth[i] = data.depth;
}
barrier();
@@ -128,39 +138,9 @@ PixelData GetPixel(ivec2 pixelOffset) {
ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius);
int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize);
- return UnpackPixelData(pixelData[sharedMemoryIdx]);
-
-}
-
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
-float ComputeEdgeStoppingWeight(float centerLuminance, float sampleLuminance,
- vec3 centerNormal, vec3 sampleNormal,
- float centerDepth, float sampleDepth,
- float centerRoughness, float sampleRoughness,
- float luminancePhi, float normalPhi,
- float depthPhi, float roughnessPhi) {
-
- const float epsilon = 1e-10;
-
- float luminanceDiff = abs(centerLuminance - sampleLuminance);
- float luminanceWeight = min(exp(-luminanceDiff / (luminancePhi + epsilon)), 1.0);
-
- float normalDiff = saturate(dot(centerNormal, sampleNormal));
- float normalWeight = min(pow(normalDiff, normalPhi), 1.0);
-
- float depthDiff = abs(centerDepth - sampleDepth);
- float depthWeight = min(exp(-depthDiff * depthPhi), 1.0);
-
- float roughnessDiff = abs(centerRoughness - sampleRoughness);
- float roughnessWeight = min(exp(-roughnessDiff / (roughnessPhi + epsilon)), 1.0);
-
- return luminanceWeight * normalWeight * depthWeight * roughnessWeight;
+ PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]);
+ data.depth = pixelDepth[sharedMemoryIdx];
+ return data;
}
@@ -190,82 +170,117 @@ float GetFilteredVariance(ivec2 pixel) {
void main() {
- LoadGroupSharedData();
-
ivec2 pixel = ivec2(gl_GlobalInvocationID);
ivec2 resolution = imageSize(outputImage);
+ bool insideImage = pixel.x < resolution.x && pixel.y < resolution.y;
+
+ float depth = insideImage ? texelFetch(depthTexture, pixel, 0).r : 1.0;
+ float roughness = insideImage ? texelFetch(roughnessTexture, pixel, 0).r : 1.0;
+ vec4 moments = insideImage ? texelFetch(historyLengthTexture, pixel, 0) : vec4(0.0);
+ float historyLength = moments.b;
- if (pixel.x >= resolution.x || pixel.y >= resolution.y)
+ // The projection flips y, its scale is negative
+ float pixelWorldSize = 2.0 * abs(ConvertDepthToViewSpaceDepth(depth)) / (abs(globalData.pMatrix[1][1]) * float(resolution.y));
+ // The blur radius follows the reflection lobe (roughness squared times hit distance), short histories get more
+ float lobeRadius = sqr(roughness) * DecodeHitDistance(moments.a) / pixelWorldSize;
+ lobeRadius = max(lobeRadius, maxBlurRadius / max(historyLength, 1.0));
+
+ float blurRadius = clamp(lobeRadius, minBlurRadius, maxBlurRadius);
+
+ // Below half the step size the taps of this pass have no weight left
+ bool filterPixel = insideImage && depth < 1.0 && roughness < pushConstants.roughnessCutoff &&
+ blurRadius >= 0.5 * float(stepSize);
+
+ if (gl_LocalInvocationIndex == 0)
+ groupFilters = 0u;
+ barrier();
+ if (filterPixel)
+ atomicOr(groupFilters, 1u);
+ barrier();
+
+ if (groupFilters != 0u)
+ LoadGroupSharedData();
+
+ if (!insideImage || depth == 1.0)
return;
+ if (!filterPixel) {
+ imageStore(outputImage, pixel, texelFetch(inputTexture, pixel, 0));
+ return;
+ }
+
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ vec2 texelSize = 1.0 / vec2(resolution);
+
+ vec3 viewRay = GetViewRay(texCoord);
+ vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay;
+ vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay;
PixelData centerPixelData = GetPixel(ivec2(0));
-
+
vec4 centerColor = centerPixelData.color;
- float centerDepth = centerPixelData.depth;
vec3 centerNormal = centerPixelData.normal;
float centerRoughness = centerPixelData.roughness;
- if (centerDepth == 1.0)
- return;
-
float centerLuminance = Luma(centerColor.rgb);
- float centerLinearDepth = ConvertDepthToViewSpaceDepth(centerDepth);
-
+ vec3 centerPosition = viewRay * centerPixelData.depth;
+
vec4 outputColor = centerColor;
float totalWeight = 1.0;
float variance = GetFilteredVariance(pixel);
float stdDeviation = sqrt(max(0.0, variance));
- vec3 viewDir = normalize(ConvertDepthToViewSpace(centerDepth, texCoord));
- float NdotV = abs(dot(viewDir, centerNormal));
- float depthPhi = max(32.0, NdotV * 256.0 / max(1.0, abs(centerLinearDepth)));
-
- if (centerRoughness < pushConstants.roughnessCutoff) {
- const int radius = 2;
- for (int x = -radius; x <= radius; x++) {
- for (int y = -radius; y <= radius; y++) {
- ivec2 samplePixel = pixel + ivec2(x, y) * pushConstants.stepSize;
-
- if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y
- || (x == 0 && y == 0))
- continue;
+ // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once.
+ // The distance to the surface plane is affine in the offset since the view ray is
+ const float log2e = 1.442695;
+ const float normalPhi = 256.0;
+ const float depthPhi = 128.0;
+ const float roughnessPhi = 0.05;
+ float planeRay = dot(viewRay, centerNormal);
+ float planeRayDx = dot(viewRayDx, centerNormal);
+ float planeRayDy = dot(viewRayDy, centerNormal);
+ float planeOffset = dot(centerPosition, centerNormal);
+ float planeScale = depthPhi * log2e / abs(centerPosition.z);
+ float luminanceScale = log2e / (stdDeviation * pushConstants.strength + 1e-10);
+ float roughnessScale = log2e / roughnessPhi;
+ float distanceScale = log2e * float(stepSize * stepSize) / sqr(blurRadius);
+
+ const int radius = 2;
+ for (int x = -radius; x <= radius; x++) {
+ for (int y = -radius; y <= radius; y++) {
+ ivec2 offset = ivec2(x, y) * stepSize;
+ ivec2 samplePixel = pixel + offset;
- PixelData samplePixelData = GetPixel(ivec2(x, y) * pushConstants.stepSize);
+ if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y ||
+ samplePixel.x < 0 || samplePixel.y < 0
+ || (x == 0 && y == 0))
+ continue;
- if (samplePixelData.depth == 1.0)
- continue;
+ PixelData samplePixelData = GetPixel(offset);
- vec4 sampleColor = samplePixelData.color;
- vec3 sampleNormal = samplePixelData.normal;
+ if (samplePixelData.depth == 0.0)
+ continue;
- float sampleDepth = samplePixelData.depth;
- float sampleLuminance = Luma(sampleColor.rgb);
+ vec4 sampleColor = samplePixelData.color;
- float sampleRoughness = samplePixelData.roughness;
+ // The distance to the surface plane stays stable at grazing angles, unlike the depth
+ float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx +
+ float(offset.y) * planeRayDy) - planeOffset;
+ float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6);
- float kernelWeight = kernelWeights[abs(x)] * kernelWeights[abs(y)];
- float edgeStoppingWeight = ComputeEdgeStoppingWeight(
- centerLuminance, sampleLuminance,
- centerNormal, sampleNormal,
- centerDepth, sampleDepth,
- centerRoughness, sampleRoughness,
- stdDeviation * pushConstants.strength,
- 256.0, 128.0, 0.05);
+ float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale +
+ abs(planeDistance) * planeScale + abs(centerRoughness - samplePixelData.roughness) * roughnessScale +
+ float(x * x + y * y) * distanceScale - normalPhi * log2(normalDot);
+ float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent);
- float weight = kernelWeight * edgeStoppingWeight;
-
- totalWeight += weight;
- outputColor += vec4(vec3(weight), weight * weight) * sampleColor;
- }
+ totalWeight += weight;
+ outputColor += vec4(vec3(weight), weight * weight) * sampleColor;
}
-
- outputColor = outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight);
}
+ outputColor = outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight);
+
imageStore(outputImage, pixel, outputColor);
- //imageStore(outputImage, pixel, vec4(centerColor.a));
}
\ No newline at end of file
diff --git a/data/shader/reflection/reflectionData.csh b/data/shader/reflection/reflectionData.csh
new file mode 100644
index 000000000..eb5d9cf55
--- /dev/null
+++ b/data/shader/reflection/reflectionData.csh
@@ -0,0 +1,128 @@
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+#include <../common/stencil.hsh>
+
+// The G-buffer, but the reflections start on the closest surface: the visible ocean (OCEAN) or the closest alpha blended
+// surface (FRONT_LAYER) if they are in front of it
+
+layout (local_size_x = 8, local_size_y = 8) in;
+
+layout (set = 3, binding = 0) uniform sampler2D depthIn;
+layout (set = 3, binding = 1) uniform sampler2D normalIn;
+layout (set = 3, binding = 2) uniform sampler2D geometryNormalIn;
+layout (set = 3, binding = 3) uniform sampler2D roughnessMetallicAoIn;
+layout (set = 3, binding = 4) uniform sampler2D velocityIn;
+layout (set = 3, binding = 5) uniform usampler2D materialIdxIn;
+
+#ifdef OCEAN
+layout (set = 3, binding = 6) uniform sampler2D oceanDepthIn;
+layout (set = 3, binding = 7) uniform sampler2D oceanNormalIn;
+layout (set = 3, binding = 8) uniform usampler2D oceanStencilIn;
+#endif
+#ifdef FRONT_LAYER
+layout (set = 3, binding = 22) uniform sampler2D frontLayerDepthIn;
+layout (set = 3, binding = 23) uniform sampler2D frontLayerNormalIn;
+layout (set = 3, binding = 24) uniform sampler2D frontLayerGeometryNormalIn;
+layout (set = 3, binding = 25) uniform sampler2D frontLayerRoughnessMetallicAoIn;
+layout (set = 3, binding = 26) uniform sampler2D frontLayerVelocityIn;
+layout (set = 3, binding = 27) uniform usampler2D frontLayerMaterialIdxIn;
+#endif
+
+layout (set = 3, binding = 9, r32f) writeonly uniform image2D depthOut;
+layout (set = 3, binding = 10, rg16f) writeonly uniform image2D normalOut;
+layout (set = 3, binding = 11, rg16f) writeonly uniform image2D geometryNormalOut;
+layout (set = 3, binding = 12, rgba8) writeonly uniform image2D roughnessMetallicAoOut;
+layout (set = 3, binding = 13, rg16f) writeonly uniform image2D velocityOut;
+layout (set = 3, binding = 14, r16ui) writeonly uniform uimage2D materialIdxOut;
+
+// Like the G-buffer downscale, the half resolution data is the top left pixel of each 2x2 block
+layout (set = 3, binding = 15, r32f) writeonly uniform image2D halfResDepthOut;
+layout (set = 3, binding = 16, rg16f) writeonly uniform image2D halfResNormalOut;
+layout (set = 3, binding = 17, rg16f) writeonly uniform image2D halfResGeometryNormalOut;
+layout (set = 3, binding = 18, rgba8) writeonly uniform image2D halfResRoughnessMetallicAoOut;
+layout (set = 3, binding = 19, rg16f) writeonly uniform image2D halfResVelocityOut;
+layout (set = 3, binding = 20, r16ui) writeonly uniform uimage2D halfResMaterialIdxOut;
+layout (set = 3, binding = 21, r8i) writeonly uniform iimage2D halfResOffsetOut;
+
+layout(push_constant) uniform constants {
+ uint oceanMaterialIdx;
+} PushConstants;
+
+void Store(ivec2 pixel, float depth, vec2 normal, vec2 geometryNormal, vec4 roughnessMetallicAo,
+ vec2 velocity, uint materialIdx) {
+
+ imageStore(depthOut, pixel, vec4(depth));
+ imageStore(normalOut, pixel, vec4(normal, 0.0, 0.0));
+ imageStore(geometryNormalOut, pixel, vec4(geometryNormal, 0.0, 0.0));
+ imageStore(roughnessMetallicAoOut, pixel, roughnessMetallicAo);
+ imageStore(velocityOut, pixel, vec4(velocity, 0.0, 0.0));
+ imageStore(materialIdxOut, pixel, uvec4(materialIdx));
+
+ ivec2 halfResPixel = pixel / 2;
+ if (pixel.x % 2 != 0 || pixel.y % 2 != 0 || any(greaterThanEqual(halfResPixel, imageSize(halfResDepthOut))))
+ return;
+
+ imageStore(halfResDepthOut, halfResPixel, vec4(depth));
+ imageStore(halfResNormalOut, halfResPixel, vec4(normal, 0.0, 0.0));
+ imageStore(halfResGeometryNormalOut, halfResPixel, vec4(geometryNormal, 0.0, 0.0));
+ imageStore(halfResRoughnessMetallicAoOut, halfResPixel, roughnessMetallicAo);
+ imageStore(halfResVelocityOut, halfResPixel, vec4(velocity, 0.0, 0.0));
+ imageStore(halfResMaterialIdxOut, halfResPixel, uvec4(materialIdx));
+ imageStore(halfResOffsetOut, halfResPixel, ivec4(0));
+
+}
+
+void main() {
+
+ ivec2 resolution = imageSize(depthOut);
+ ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ if (pixel.x >= resolution.x || pixel.y >= resolution.y)
+ return;
+
+ float depth = texelFetch(depthIn, pixel, 0).r;
+
+#ifdef FRONT_LAYER
+ // Starts out as a copy of the depth, the surfaces only write where they are in front
+ float frontLayerDepth = texelFetch(frontLayerDepthIn, pixel, 0).r;
+#else
+ float frontLayerDepth = 1.0;
+#endif
+
+#ifdef OCEAN
+ float oceanDepth = texelFetch(oceanDepthIn, pixel, 0).r;
+ StencilFeatures features = DecodeStencilFeatures(texelFetch(oceanStencilIn, pixel, 0).r);
+ bool oceanVisible = oceanDepth < 1.0 && oceanDepth <= depth && !features.underWaterPixel;
+
+ if (oceanVisible && oceanDepth <= frontLayerDepth) {
+ vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ vec3 viewPos = ConvertDepthToViewSpace(oceanDepth, texCoord);
+ vec3 worldPos = vec3(globalData.ivMatrix * vec4(viewPos, 1.0));
+
+ vec2 normal = texelFetch(oceanNormalIn, pixel, 0).rg;
+
+ // Same velocity as the ocean surface pass, which only accounts for the camera movement
+ vec4 last = globalData.pvMatrixLast * vec4(worldPos, 1.0);
+ vec4 current = globalData.pMatrix * vec4(viewPos, 1.0);
+ vec2 ndcLast = last.xy / last.w - globalData.jitterLast;
+ vec2 ndcCurrent = current.xy / current.w - globalData.jitterCurrent;
+
+ Store(pixel, oceanDepth, normal, normal, vec4(0.0, 0.0, 1.0, 0.0), (ndcLast - ndcCurrent) * 0.5,
+ PushConstants.oceanMaterialIdx);
+ return;
+ }
+#endif
+
+#ifdef FRONT_LAYER
+ if (frontLayerDepth < depth) {
+ Store(pixel, frontLayerDepth, texelFetch(frontLayerNormalIn, pixel, 0).rg,
+ texelFetch(frontLayerGeometryNormalIn, pixel, 0).rg, texelFetch(frontLayerRoughnessMetallicAoIn, pixel, 0),
+ texelFetch(frontLayerVelocityIn, pixel, 0).rg, texelFetch(frontLayerMaterialIdxIn, pixel, 0).r);
+ return;
+ }
+#endif
+
+ Store(pixel, depth, texelFetch(normalIn, pixel, 0).rg, texelFetch(geometryNormalIn, pixel, 0).rg,
+ texelFetch(roughnessMetallicAoIn, pixel, 0), texelFetch(velocityIn, pixel, 0).rg,
+ texelFetch(materialIdxIn, pixel, 0).r);
+
+}
diff --git a/data/shader/reflection/rtreflection.csh b/data/shader/reflection/rtreflection.csh
index a32159c58..182c59578 100644
--- a/data/shader/reflection/rtreflection.csh
+++ b/data/shader/reflection/rtreflection.csh
@@ -1,5 +1,3 @@
-#define SHADOW_FILTER_1x1
-
#include <../globals.hsh>
#include <../raytracer/lights.hsh>
#include <../raytracer/tracing.hsh>
@@ -21,10 +19,13 @@
#include <../ddgi/ddgi.hsh>
#include <../ddgi/transmission.hsh>
-#include <../shadow.hsh>
#include <../clouds/shadow.hsh>
+#include <../common/denoiser.hsh>
+
+#ifndef RAY_TRACING_PIPELINE
layout (local_size_x = 8, local_size_y = 4) in;
+#endif
layout (set = 3, binding = 0, rgba16f) uniform image2D rtrImage;
@@ -33,7 +34,6 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture;
layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture;
layout(set = 3, binding = 4) uniform isampler2D offsetTexture;
layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture;
-layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps;
layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture;
layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture;
@@ -80,29 +80,34 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer {
ivec2 resolution;
uint frameCount;
int padding1;
- Shadow shadow;
} uniforms;
+#include <../raytracer/lighting.hsh>
+
vec3 EvaluateHit(inout Ray ray, float rand);
-vec3 EvaluateDirectLight(inout Surface surface, inout float seed);
-float CheckVisibility(Surface surface, float lightDistance);
void main() {
ivec2 resolution = uniforms.resolution;
- if (int(gl_GlobalInvocationID.x) < resolution.x &&
- int(gl_GlobalInvocationID.y) < resolution.y) {
+ if (int(INVOCATION_ID.x) < resolution.x &&
+ int(INVOCATION_ID.y) < resolution.y) {
- ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ ivec2 pixel = ivec2(INVOCATION_ID.xy);
#ifdef SSR
vec4 reflection = imageLoad(rtrImage, pixel);
+ // Pixels SSR resolved keep its result, the resolve skips them by the marker
+ if (reflection.a != 0.0) {
+#ifdef DEFERRED_SHADOW_RAYS
+ deferredSamples[(pixel.y * resolution.x + pixel.x) * uniforms.sampleCount].radiance.w = -1.0;
+#endif
+ return;
+ }
#else
vec4 reflection = vec4(0.0);
#endif
- // No need, there is no offset right now
int offsetIdx = texelFetch(offsetTexture, pixel, 0).r;
#ifdef UPSCALE
ivec2 offset = pixelOffsets[globalData.frameCount % 4];
@@ -117,7 +122,8 @@ void main() {
recontructTexCoord = (2.0 * (vec2(pixel)) + offset + 0.5) / (2.0 * vec2(resolution));
highResPixel = 2 * pixel + offset;
#else
- recontructTexCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ // The downsampled data belongs to one pixel of the 2x2 block
+ recontructTexCoord = (2.0 * vec2(pixel) + pixelOffsets[offsetIdx] + 0.5) / (2.0 * vec2(resolution));
highResPixel = pixel;
#endif
}
@@ -140,7 +146,13 @@ void main() {
float roughness = texelFetch(roughnessMetallicAoTexture, highResPixel, 0).r;
material.roughness *= material.roughnessMap || material.terrain ? roughness : 1.0;
- float hitDistance = reflection.a;
+#ifdef DEFERRED_SHADOW_RAYS
+ int pixelIdx = pixel.y * resolution.x + pixel.x;
+#endif
+
+ // Mean of the encoded hit distances, misses and probe samples count as one
+ float hitDistanceSum = 0.0;
+ int hitDistanceCount = 0;
if (material.roughness <= 1.0 && depth < 1.0 && reflection.a == 0.0) {
@@ -153,11 +165,28 @@ void main() {
const int sampleCount = uniforms.sampleCount;
+ // Values per pixel are computed once before the loop
+ float roughness = material.roughness;
+ float alpha = sqr(max(0.0, roughness));
+ float viewOffset = max(1.0, 2.0 * length(viewPos));
+#ifdef AUTO_EXPOSURE
+ float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure;
+#else
+ float radianceLimit = uniforms.radianceLimit;
+#endif
+
for (int i = 0; i < sampleCount; i++) {
#ifdef UPSCALE
int sampleIdx = int(uniforms.frameSeed / 4) * sampleCount + i;
#else
int sampleIdx = int(uniforms.frameSeed) * sampleCount + i;
+#endif
+#ifdef DEFERRED_SHADOW_RAYS
+ int deferredSampleIdx = pixelIdx * sampleCount + i;
+ deferredSamples[deferredSampleIdx].radiance.w = 0.0;
+ deferredLightBase = deferredSampleIdx * uniforms.lightSampleCount;
+ for (int j = 0; j < uniforms.lightSampleCount; j++)
+ deferredLights[deferredLightBase + j] = vec4(0.0, 0.0, 0.0, 1.0);
#endif
vec3 blueNoiseVec = vec3(
SampleBlueNoise(highResPixel, sampleIdx, 0, scramblingRankingTexture, sobolSequenceTexture),
@@ -165,15 +194,13 @@ void main() {
SampleBlueNoise(highResPixel, sampleIdx, 2, scramblingRankingTexture, sobolSequenceTexture)
);
- float alpha = sqr(max(0.0, material.roughness));
-
Ray ray;
ray.ID = i;
blueNoiseVec.y *= (1.0 - uniforms.bias);
float pdf = 1.0;
BRDFSample brdfSample;
- if (material.roughness >= 0.0) {
+ if (roughness >= 0.0) {
ImportanceSampleGGXVNDF(blueNoiseVec.xy, N, V, alpha,
ray.direction, pdf);
}
@@ -181,28 +208,22 @@ void main() {
ray.direction = R;
}
- Surface surface = CreateSurface(V, N, ray.direction, material);
-
bool isRayValid = !isnan3(ray.direction) && !isinf3(ray.direction) &&
dot(N, ray.direction) >= 0.0;
if (isRayValid) {
// Scale offset by depth since the depth buffer inaccuracies increase at a distance and might not match the ray traced geometry anymore
- float viewOffset = max(1.0, 2.0 * length(viewPos));
ray.origin = worldPos + ray.direction * EPSILON * viewOffset + worldNorm * EPSILON * viewOffset;
ray.hitID = -1;
ray.hitDistance = 0.0;
vec3 radiance = vec3(0.0);
+ float encodedHitDistance = 1.0;
- if (material.roughness <= uniforms.roughnessCutoff) {
-#ifdef OPACITY_CHECK
- HitClosestTransparency(ray, INSTANCE_MASK_ALL, 0.0, INF);
-#else
- HitClosest(ray, INSTANCE_MASK_ALL, 0.0, INF);
-#endif
- hitDistance = ray.hitDistance;
+ if (roughness <= uniforms.roughnessCutoff) {
+ HitClosestOpacityCheck(ray, INSTANCE_MASK_ALL, 0.0, INF);
+ encodedHitDistance = ray.hitID != -1 ? EncodeHitDistance(ray.hitDistance) : 1.0;
radiance = EvaluateHit(ray, blueNoiseVec.z);
}
else {
@@ -214,13 +235,15 @@ void main() {
#elif defined(IRRADIANCE_VOLUME)
radiance = IsInsideVolume(worldPos) ? probeIrradiance.rgb : vec3(0.0);
#endif
- hitDistance = 1.0;
}
-#ifdef AUTO_EXPOSURE
- float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r;
-#else
- float radianceLimit = uniforms.radianceLimit;
+ hitDistanceSum += encodedHitDistance;
+ hitDistanceCount++;
+
+#ifdef DEFERRED_SHADOW_RAYS
+ deferredSamples[deferredSampleIdx].radiance = vec4(radiance, 1.0);
+ deferredSamples[deferredSampleIdx].lobeWeight = vec4(1.0, 1.0, 1.0, radianceLimit);
+ continue;
#endif
float radianceMax = max(max(max(radiance.r,
@@ -229,10 +252,20 @@ void main() {
}
}
+#ifndef DEFERRED_SHADOW_RAYS
reflection.rgb /= float(sampleCount);
+#endif
}
+#ifdef DEFERRED_SHADOW_RAYS
+ else {
+ deferredSamples[pixelIdx * uniforms.sampleCount].radiance.w = -1.0;
+ }
+#endif
+ // Misses store zero, an infinite distance breaks the virtual reprojection of the temporal pass
+ float meanHitDistance = hitDistanceCount > 0 ? hitDistanceSum / float(hitDistanceCount) : 1.0;
+ float hitDistance = meanHitDistance < 1.0 ? DecodeHitDistance(meanHitDistance) : 0.0;
imageStore(rtrImage, pixel, vec4(reflection.rgb, hitDistance));
}
@@ -248,12 +281,8 @@ vec3 EvaluateHit(inout Ray ray, float rand) {
return SampleEnvironmentMap(ray.direction).rgb;
}
- // Unpack the compressed triangle and extract surface parameters
- Instance instance = GetInstance(ray);
- Triangle tri = GetTriangle(ray, instance);
-
bool backfaceHit;
- Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, uniforms.textureLevel);
+ Surface surface = GetHitSurface(ray, false, backfaceHit, uniforms.textureLevel);
// Evaluate indirect lighting
#ifdef IRRADIANCE_VOLUME
@@ -275,73 +304,9 @@ vec3 EvaluateHit(inout Ray ray, float rand) {
radiance += surface.material.emissiveColor;
float curSeed = float(uniforms.frameSeed) / 255.0 + float(ray.ID) * float(uniforms.sampleCount);
- // Evaluate direct light
- for (int i = 0; i < uniforms.lightSampleCount; i++) {
- radiance += (EvaluateDirectLight(surface, curSeed) / float(uniforms.lightSampleCount));
- curSeed += 1.0 / float(uniforms.lightSampleCount);
- }
+ float raySeed = float(INVOCATION_ID.x * uniforms.resolution.y + INVOCATION_ID.y);
+ radiance += EvaluateDirectLights(surface, raySeed, curSeed, uniforms.lightSampleCount);
return radiance;
}
-
-vec3 EvaluateDirectLight(inout Surface surface, inout float seed) {
-
- if (GetLightCount() == 0)
- return vec3(0.0);
-
- float raySeed = float(gl_GlobalInvocationID.x * uniforms.resolution.y + gl_GlobalInvocationID.y);
-
- float lightPdf;
- Light light = GetLight(surface, raySeed, seed, lightPdf);
-
- float solidAngle, lightDistance;
- SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance);
-
- bool transmittedLight = IsTransmittedLight(surface);
- Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface;
-
- // Evaluate the BRDF
- vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) :
- EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface);
- reflectance *= surface.material.opacity;
- vec3 radiance = light.radiance * solidAngle;
-
- // Check for visibilty. This is important to get an
- // estimate of the solid angle of the light from point P
- // on the surface.
-#ifdef USE_SHADOW_MAP
- radiance *= CalculateShadowWorldSpace(uniforms.shadow, cascadeMaps, surface.P,
- lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal)));
-#else
- if (light.castShadow)
- radiance *= CheckVisibility(lightSurface, lightDistance);
-#endif
-
-#ifdef CLOUD_SHADOWS
- if (light.type == uint(DIRECTIONAL_LIGHT)) {
- vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0));
- float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap);
-
- radiance *= cloudShadowFactor;
- }
-#endif
-
- return reflectance * radiance * lightSurface.NdotL / lightPdf;
-
-}
-
-float CheckVisibility(Surface surface, float lightDistance) {
-
- if (surface.NdotL > 0.0) {
- Ray ray;
- ray.direction = surface.L;
- float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0;
- ray.origin = surface.P + surface.geometryNormal * (side * EPSILON);
- return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON);
- }
- else {
- return 0.0;
- }
-
-}
diff --git a/data/shader/reflection/rtreflection.rgen b/data/shader/reflection/rtreflection.rgen
new file mode 100644
index 000000000..11c17c85c
--- /dev/null
+++ b/data/shader/reflection/rtreflection.rgen
@@ -0,0 +1,7 @@
+// Ray traced reflections as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_shader_invocation_reorder : require
+
+#define RAY_TRACING_PIPELINE
+
+#include
diff --git a/data/shader/reflection/rtreflectionResolve.csh b/data/shader/reflection/rtreflectionResolve.csh
new file mode 100644
index 000000000..9358f0094
--- /dev/null
+++ b/data/shader/reflection/rtreflectionResolve.csh
@@ -0,0 +1,47 @@
+#include <../raytracer/deferredShadow.hsh>
+
+layout (local_size_x = 8, local_size_y = 4) in;
+
+layout (set = 3, binding = 0, rgba16f) uniform image2D rtrImage;
+
+layout(push_constant) uniform constants {
+ ivec2 resolution;
+ int sampleCount;
+ int lightSampleCount;
+} pushConstants;
+
+void main() {
+
+ ivec2 resolution = pushConstants.resolution;
+ if (int(gl_GlobalInvocationID.x) >= resolution.x || int(gl_GlobalInvocationID.y) >= resolution.y)
+ return;
+
+ ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ int pixelIdx = pixel.y * resolution.x + pixel.x;
+
+ // Pixels which weren't ray traced, e.g. because of an SSR hit, keep their reflection
+ if (deferredSamples[pixelIdx * pushConstants.sampleCount].radiance.w < 0.0)
+ return;
+
+ vec4 reflection = imageLoad(rtrImage, pixel);
+ for (int i = 0; i < pushConstants.sampleCount; i++) {
+ int sampleIdx = pixelIdx * pushConstants.sampleCount + i;
+ if (deferredSamples[sampleIdx].radiance.w == 0.0)
+ continue;
+
+ vec3 radiance = deferredSamples[sampleIdx].radiance.rgb;
+ for (int j = 0; j < pushConstants.lightSampleCount; j++) {
+ vec4 light = deferredLights[sampleIdx * pushConstants.lightSampleCount + j];
+ radiance += light.rgb * light.w;
+ }
+
+ float radianceLimit = deferredSamples[sampleIdx].lobeWeight.w;
+ float radianceMax = max(max(max(radiance.r,
+ max(radiance.g, radiance.b)), radianceLimit), 1e-12);
+ reflection.rgb += radiance * (radianceLimit / radianceMax);
+ }
+
+ reflection.rgb /= float(pushConstants.sampleCount);
+ imageStore(rtrImage, pixel, reflection);
+
+}
diff --git a/data/shader/reflection/ssr.csh b/data/shader/reflection/ssr.csh
index 5e15dfc84..0c9e8c8d4 100644
--- a/data/shader/reflection/ssr.csh
+++ b/data/shader/reflection/ssr.csh
@@ -17,7 +17,6 @@
#include <../brdf/surface.hsh>
#include <../ddgi/ddgi.hsh>
-#include <../shadow.hsh>
layout (local_size_x = 8, local_size_y = 4) in;
@@ -28,12 +27,14 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture;
layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture;
layout(set = 3, binding = 4) uniform isampler2D offsetTexture;
layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture;
-layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps;
layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture;
layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture;
layout(set = 3, binding = 9) uniform sampler2D lightingTexture;
+layout(set = 3, binding = 12) uniform sampler2D hiZTexture;
+// Depth at the resolution of the hierarchical depth buffer, which is the one of the rays
+layout(set = 3, binding = 13) uniform sampler2D hiZDepthTexture;
#ifdef AUTO_EXPOSURE
layout(set = 3, binding = 11) uniform sampler2D exposureTexture;
#endif
@@ -59,8 +60,7 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer {
int halfRes;
ivec2 resolution;
uint frameCount;
- int padding1;
- Shadow shadow;
+ int hiZLevelCount;
} uniforms;
vec4 SampleCatmullRom(vec2 uv) {
@@ -117,7 +117,6 @@ vec4 SampleCatmullRom(vec2 uv) {
}
shared int maxSteps;
-shared int stepSize;
void main() {
@@ -125,7 +124,6 @@ void main() {
if (gl_LocalInvocationIndex == 0u) {
maxSteps = 0;
- stepSize = 0;
}
barrier();
@@ -169,12 +167,10 @@ void main() {
material.roughness *= material.roughnessMap || material.terrain ? roughness : 1.0;
if (material.roughness < 0.1) {
- atomicMax(maxSteps, 128);
- atomicMax(stepSize, 8);
+ atomicMax(maxSteps, 64);
}
else {
- atomicMax(maxSteps, 64);
- atomicMax(stepSize, 16);
+ atomicMax(maxSteps, 32);
}
barrier();
@@ -232,19 +228,14 @@ void main() {
vec2 hitPixel;
vec3 hitPoint;
-#ifdef UPSCALE
- float jitter = GetInterleavedGradientNoise(vec2(highResPixel), 32u) / float(sampleCount) + i / float(sampleCount);
-#else
- float jitter = GetInterleavedGradientNoise(vec2(highResPixel), 32u) / float(sampleCount) + i / float(sampleCount);
-#endif
#ifdef RT
bool stopBehindGeometry = true;
#else
bool stopBehindGeometry = false;
#endif
- if (traceScreenSpaceAdvanced(viewRayOrigin, viewDir, depthTexture, 1.0, stepSize, 0.9, maxSteps,
- rayLength, false, stopBehindGeometry, hitPixel, hitPoint)) {
- vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(lightingTexture, 0));
+ if (traceScreenSpaceHiZ(viewRayOrigin, viewDir, hiZTexture, uniforms.hiZLevelCount, vec2(textureSize(hiZDepthTexture, 0)),
+ maxSteps, rayLength, stopBehindGeometry, hitPixel, hitPoint)) {
+ vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(hiZDepthTexture, 0));
//radiance = SampleCatmullRom(hitTexCoord).rgb;
radiance = textureLod(lightingTexture, hitTexCoord, 0.0).rgb;
@@ -258,7 +249,7 @@ void main() {
}
#ifdef AUTO_EXPOSURE
- float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r;
+ float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure;
#else
float radianceLimit = uniforms.radianceLimit;
#endif
diff --git a/data/shader/reflection/temporal.csh b/data/shader/reflection/temporal.csh
index 477c2641a..39e5ff1fa 100644
--- a/data/shader/reflection/temporal.csh
+++ b/data/shader/reflection/temporal.csh
@@ -11,6 +11,7 @@
#include <../common/material.hsh>
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
+#include <../common/denoiser.hsh>
layout (local_size_x = 16, local_size_y = 16) in;
@@ -34,21 +35,20 @@ layout(set = 3, binding = 13) uniform sampler2D historyRoughnessMetallicAoTextur
vec2 invResolution = 1.0 / vec2(imageSize(resolveImage));
vec2 resolution = vec2(imageSize(resolveImage));
-const int kernelRadius = 5;
+const int kernelRadius = 3;
const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius);
const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius;
shared vec4 sharedRadianceDepth[sharedDataSize];
+shared vec2 sharedObjectMotion[sharedDataSize];
layout(push_constant) uniform constants {
- vec4 cameraLocationLast;
float temporalWeight;
float historyClipMax;
float currentClipFactor;
float roughnessCutoff;
int resetHistory;
- uint frameCount;
} pushConstants;
const ivec2 offsets[9] = ivec2[9](
@@ -70,13 +70,6 @@ const ivec2 pixelOffsets[4] = ivec2[4](
ivec2(1, 1)
);
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
vec4 FetchTexel(ivec2 texel) {
vec4 color = texelFetch(currentTexture, texel, 0);
@@ -97,8 +90,10 @@ void LoadGroupSharedData() {
texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1));
vec4 radianceRayLength = FetchTexel(texel);
+ float depth = texelFetch(depthTexture, texel, 0).r;
sharedRadianceDepth[i].rgb = RGBToYCoCg(radianceRayLength.rgb);
- sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(texelFetch(depthTexture, texel, 0).r);
+ sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(depth);
+ sharedObjectMotion[i] = GetObjectMotion(velocityTexture, texel, depth, resolution);
}
barrier();
@@ -143,31 +138,27 @@ ivec2 FindNearest3x3(ivec2 pixel) {
}
-float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) {
-
- vec3 origin = history;
- vec3 dir = current - history;
-
- // Make sure dir isn't zero
- dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x;
- dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y;
- dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z;
-
- vec3 invDir = 1.0 / dir;
+vec3 GetHistoryWorldPosition(ivec2 historyPixel) {
- vec3 t0 = (boxMin - origin) * invDir;
- vec3 t1 = (boxMax - origin) * invDir;
-
- vec3 intersect = min(t0, t1);
- return max(intersect.x, max(intersect.y, intersect.z));
+ float historyDepth = texelFetch(historyDepthTexture, historyPixel, 0).r;
+ vec2 ndc = (vec2(historyPixel) + 0.5) * invResolution * 2.0 - 1.0;
+ vec4 position = globalData.ipvMatrixLast * vec4(ndc, historyDepth, 1.0);
+ return position.xyz / position.w;
}
-bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 history, out vec4 historyMoments) {
-
+// The bilinear footprint is complete when all four history texels are valid, their range limits a bicubic filter.
+// The confidence is the valid part of the footprint, it shortens the history of partly valid reprojections
+bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 history, out vec4 historyMoments,
+ out bool completeFootprint, out vec4 historyMin, out vec4 historyMax, out float footprintConfidence) {
+
+ footprintConfidence = 0.0;
history = vec4(0.0);
historyMoments = vec4(0.0);
+ historyMin = vec4(1e30);
+ historyMax = vec4(-1e30);
+ int validCount = 0;
float totalWeight = 0.0;
float x = fract(historyPixel.x);
float y = fract(historyPixel.y);
@@ -177,8 +168,11 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his
vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg);
float depth = texelFetch(depthTexture, pixel, 0).r;
- float linearDepth = ConvertDepthToViewSpaceDepth(depth);
- float depthPhi = normalPhi / abs(linearDepth);
+ vec3 viewPosition = ConvertDepthToViewSpace(depth, (vec2(pixel) + 0.5) * invResolution);
+ vec3 position = vec3(globalData.ivMatrix * vec4(viewPosition, 1.0));
+ vec3 worldNormal = normalize(mat3(globalData.ivMatrix) * normal);
+ // The distance to the surface plane stays stable at grazing angles, unlike the depth
+ float depthPhi = normalPhi / abs(viewPosition.z);
float roughness = texelFetch(roughnessMetallicAoTexture, pixel, 0).r;
uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r;
@@ -193,22 +187,28 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his
vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, offsetPixel, 0).rg);
confidence *= pow(max(dot(historyNormal, normal), 0.0), normalPhi);
- float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r;
- float historyLinearDepth = historyDepth;
-
- confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi));
+ float planeDistance = abs(dot(GetHistoryWorldPosition(offsetPixel) - position, worldNormal));
+ confidence *= min(1.0 , exp(-planeDistance * depthPhi));
uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r;
confidence *= historyMaterialIdx == materialIdx ? 1.0 : 0.0;
if (confidence > 0.2) {
+ vec4 historyTexel = texelFetch(historyTexture, offsetPixel, 0);
+ historyMin = min(historyMin, historyTexel);
+ historyMax = max(historyMax, historyTexel);
+ validCount++;
+
totalWeight += weights[i];
- history += texelFetch(historyTexture, offsetPixel, 0) * weights[i];
+ history += historyTexel * weights[i];
historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i];
}
}
+ completeFootprint = validCount == 4;
+
if (totalWeight > 0.0) {
+ footprintConfidence = totalWeight;
history /= totalWeight;
historyMoments /= totalWeight;
return true;
@@ -223,9 +223,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his
vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, offsetPixel, 0).rg);
confidence *= pow(max(dot(historyNormal, normal), 0.0), normalPhi);
- float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r;
- float historyLinearDepth = ConvertDepthToViewSpaceDepth(historyDepth);
- confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi));
+ float planeDistance = abs(dot(GetHistoryWorldPosition(offsetPixel) - position, worldNormal));
+ confidence *= min(1.0 , exp(-planeDistance * depthPhi));
uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r;
confidence *= historyMaterialIdx == materialIdx ? 1.0 : 0.0;
@@ -238,6 +237,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his
}
if (totalWeight > 0.0) {
+ // None of the footprint texels matched, the neighbors around it are less trustworthy
+ footprintConfidence = totalWeight / 9.0;
history /= totalWeight;
historyMoments /= totalWeight;
return true;
@@ -250,85 +251,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his
}
-float IsHistoryPixelValid(ivec2 pixel, float linearDepth, vec3 normal) {
-
- float confidence = 1.0;
-
- vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, pixel, 0).rg);
- confidence *= pow(max(dot(historyNormal, normal), 0.0), 16.0);
-
- float depthPhi = 128.0 / abs(linearDepth);
- float historyDepth = texelFetch(historyDepthTexture, pixel, 0).r;
- float historyLinearDepth = historyDepth;
- confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi));
-
- return confidence > 0.1 ? 1.0 : 0.0;
-
-}
-
-vec4 GetCatmullRomSample(ivec2 pixel, inout float weight, float linearDepth, vec3 normal) {
-
- pixel = clamp(pixel, ivec2(0), ivec2(imageSize(resolveImage) - 1));
-
- weight *= IsHistoryPixelValid(pixel, linearDepth, normal);
-
- return texelFetch(historyTexture, pixel, 0) * weight;
-
-}
-
-bool SampleCatmullRom(ivec2 pixel, vec2 uv, out vec4 history) {
-
- vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg);
- float depth = texelFetch(depthTexture, pixel, 0).r;
-
- vec2 position = uv * resolution;
-
- vec2 center = floor(position - 0.5) + 0.5;
- vec2 f = position - center;
- vec2 f2 = f * f;
- vec2 f3 = f2 * f;
-
- vec2 w0 = f2 - 0.5 * (f3 + f);
- vec2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0;
- vec2 w3 = 0.5 * (f3 - f2);
- vec2 w2 = 1.0 - w0 - w1 - w3;
-
- ivec2 uv0 = ivec2(center - 1.0);
- ivec2 uv1 = ivec2(center);
- ivec2 uv2 = ivec2(center + 1.0);
- ivec2 uv3 = ivec2(center + 2.0);
-
- ivec2 uvs[4] = { uv0, uv1, uv2, uv3 };
- vec2 weights[4] = { w0, w1, w2, w3 };
-
- history = vec4(0.0);
-
- float totalWeight = 0.0;
-
- for (int x = 0; x <= 3; x++) {
- for (int y = 0; y <= 3; y++) {
- float weight = weights[x].x * weights[y].y;
- ivec2 uv = ivec2(uvs[x].x, uvs[y].y);
-
- history += GetCatmullRomSample(uv, weight, depth, normal);
- totalWeight += weight;
- }
- }
-
- if (totalWeight > 0.5) {
- history /= totalWeight;
- history = max(history, 0.0);
-
- return true;
- }
-
- return false;
-}
-
-void ComputeVarianceMinMax(float roughness, int radius, out vec3 mean, out vec3 std) {
+// The sample count is the effective one of the weighted neighborhood, (sum of weights)^2 / sum of squared weights.
+// The nearby motion is the fastest movement of a neighbor around the same depth relative to the pixel in pixels
+void ComputeVarianceMinMax(int radius, out vec3 mean, out vec3 std, out float sampleCount, out float nearbyMotion) {
vec3 m1 = vec3(0.0);
vec3 m2 = vec3(0.0);
+ float squaredWeight = 0.0;
// This could be varied using the temporal variance estimation
// By using a wide neighborhood for variance estimation (8x8) we introduce block artifacts
// These are similiar to video compression artifacts, the spatial filter mostly clears them up
@@ -339,40 +268,36 @@ void ComputeVarianceMinMax(float roughness, int radius, out vec3 mean, out vec3
float linearDepth = ConvertDepthToViewSpaceDepth(depth);
float depthPhi = max(1.0, abs(0.025 * linearDepth));
- uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r;
-
float totalWeight = 0.0;
+ vec2 centerObjectMotion = sharedObjectMotion[GetSharedMemoryIndex(ivec2(0))];
+ float nearbyMotionSquared = 0.0;
+ float depthScale = 1.442695 / depthPhi;
+
for (int i = -radius; i <= radius; i++) {
for (int j = -radius; j <= radius; j++) {
int sharedMemoryIdx = GetSharedMemoryIndex(ivec2(i, j));
vec3 sampleRadiance = FetchCurrentRadiance(sharedMemoryIdx);
float sampleLinearDepth = FetchDepth(sharedMemoryIdx);
-
- float weight = min(1.0 , exp(-abs(linearDepth - sampleLinearDepth) / depthPhi));
-
+
+ float weight = exp2(-abs(linearDepth - sampleLinearDepth) * depthScale);
+
m1 += sampleRadiance * weight;
m2 += sampleRadiance * sampleRadiance * weight;
totalWeight += weight;
+ squaredWeight += weight * weight;
+
+ nearbyMotionSquared = max(nearbyMotionSquared, GetNearbyMotionSquared(sharedObjectMotion[sharedMemoryIdx],
+ centerObjectMotion, linearDepth, sampleLinearDepth));
}
}
mean = m1 / totalWeight;
std = sqrt(max((m2 / totalWeight) - (mean * mean), 0.0));
-}
-
-float ComputeParallax(vec3 position, vec3 historyPosition) {
-
- vec3 cameraDelta = pushConstants.cameraLocationLast.xyz - globalData.cameraLocation.xyz;
-
- vec3 V = normalize(position);
- vec3 historyV = normalize(historyPosition - cameraDelta);
-
- float cosTheta = saturate(dot(V, historyV));
- return sqrt(1.0 - cosTheta * cosTheta) / max(cosTheta, 1e-6) * 60.0;
-
+ sampleCount = sqr(totalWeight) / squaredWeight;
+ nearbyMotion = sqrt(nearbyMotionSquared);
}
float GetSpecularDominantFactor(float NdotV, float roughness) {
@@ -384,30 +309,26 @@ float GetSpecularDominantFactor(float NdotV, float roughness) {
}
-float GetAccumulationSpeed(float NdotV, float roughness, float parallax) {
+float GetFilteredRayLength(ivec2 pixel) {
- const float accumCurve = 0.5;
- const float accumBasePower = 0.5;
+ float centerDepth = FetchDepth(GetSharedMemoryIndex(ivec2(0)));
+ float depthPhi = 32.0 / abs(centerDepth);
- float acossqr = 1.0 - NdotV;
- float rsqr = sqr(roughness);
-
- float a = pow(saturate(acossqr), accumCurve);
- float b = 1.1 + rsqr;
-
- float parallaxSensitivity = (b + a) / (b - a);
- float powerScale = 1.0 + parallax * parallaxSensitivity;
-
- float f = 1.0 - exp2(-200.0 * rsqr);
- f *= pow(saturate(roughness), accumBasePower * powerScale);
-
- return min(f, pushConstants.temporalWeight);
+ float rayLength = 0.0;
+ float totalWeight = 0.0;
-}
+ // Misses have a ray length of zero and are excluded
+ for (int i = 0; i < 9; i++) {
+ ivec2 samplePixel = clamp(pixel + offsets[i], ivec2(0), ivec2(resolution) - ivec2(1));
+ float sampleRayLength = abs(texelFetch(currentTexture, samplePixel, 0).a);
+ float sampleDepth = FetchDepth(GetSharedMemoryIndex(offsets[i]));
-vec2 SurfacePointReprojection(vec2 pixel, vec2 velocity) {
+ float weight = sampleRayLength > 0.0 ? min(1.0, exp(-abs(centerDepth - sampleDepth) * depthPhi)) : 0.0;
+ rayLength += sampleRayLength * weight;
+ totalWeight += weight;
+ }
- return pixel + velocity * resolution;
+ return totalWeight > 0.0 ? rayLength / totalWeight : 0.0;
}
@@ -437,8 +358,8 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
vec2 uv = (vec2(pixel) + 0.5) * invResolution;
@@ -447,157 +368,157 @@ void main() {
float roughness = textureLod(roughnessMetallicAoTexture, uv, .0).r;
vec3 normal = normalize(DecodeNormal(texelFetch(normalTexture, pixel, 0).rg));
- vec2 surfaceHistoryPixel = SurfacePointReprojection(vec2(pixel), velocity);
- vec2 surfaceHistoryUV = (surfaceHistoryPixel + 0.5) * invResolution;
-
float depth = texelFetch(depthTexture, pixel, 0).r;
- float depthHistory = texelFetch(depthTexture, ivec2(surfaceHistoryPixel), 0).r;
-
- //vec3 position = vec3(globalData.ivMatrix * vec4(ConvertDepthToViewSpace(depth, uv), 1.0));
- //vec3 positionHistory = vec3(inverse(globalData.vMatrixLast) * vec4(ConvertDepthToViewSpace(depthHistory, surfaceHistoryUV), 1.0));
-
vec3 position = ConvertDepthToViewSpace(depth, uv);
- vec3 positionHistory = ConvertDepthToViewSpace(depthHistory, uv);
- float parallax = ComputeParallax(position, positionHistory);
float NdotV = abs(dot(normalize(-position), normal));
float dominantFactor = GetSpecularDominantFactor(NdotV, sqrt(roughness));
vec3 mean, std;
+ float sampleCount, nearbyMotion;
#ifdef UPSCALE
const int radius = int(mix(3.0, float(kernelRadius), min(1.0, roughness * 4.0)));
#else
const int radius = int(mix(2.0, float(kernelRadius), min(1.0, roughness * 4.0)));
#endif
- if (roughness < pushConstants.roughnessCutoff) {
- ComputeVarianceMinMax(roughness, radius, mean, std);
- }
- else {
- // Don't need much denoising here (except for roughness = 1. looks noisy for metallic surfaces)
- ComputeVarianceMinMax(roughness, 3, mean, std);
- }
-
- ivec2 velocityPixel = pixel;
+ // Above the cutoff the probes don't need much denoising (except for roughness = 1. looks noisy for metallic surfaces)
+ ComputeVarianceMinMax(roughness < pushConstants.roughnessCutoff ? radius : 3,
+ mean, std, sampleCount, nearbyMotion);
- uv = (vec2(pixel) + vec2(0.5)) * invResolution + velocity;
vec2 historyPixel = vec2(pixel) + velocity * resolution;
- uv = (historyPixel + 0.5) * invResolution;
+ vec2 historyUv = (historyPixel + 0.5) * invResolution;
- bool valid = true;
- vec4 history = vec4(0.0);
- vec4 historyMoments = vec4(0.0);
- valid = SampleHistory(pixel, historyPixel, 16.0,
- history, historyMoments);
+ vec4 history;
+ vec4 historyMoments;
+ bool completeFootprint;
+ vec4 historyMin, historyMax;
+ float footprintConfidence;
+ bool valid = SampleHistory(pixel, historyPixel, 16.0,
+ history, historyMoments, completeFootprint, historyMin, historyMax, footprintConfidence) && !IsOffscreen(historyUv);
#ifdef BICUBIC_FILTER
- // This should be implemented more efficiently, see
- if (roughness < pushConstants.roughnessCutoff) {
- vec4 catmullRomHistory;
- bool success = SampleCatmullRom(pixel, uv, catmullRomHistory);
- history = success && valid ? catmullRomHistory : history;
- }
+ // The clamp removes ringing and texels outside the footprint that belong to other surfaces
+ if (roughness < pushConstants.roughnessCutoff && completeFootprint)
+ history = clamp(SampleCatmullRom(historyTexture, historyUv, resolution), historyMin, historyMax);
#endif
+ // The history was stored with the pre-exposure of the last frame, the moments hold luma and its square
+ float exposureScale = globalData.preExposure / globalData.lastPreExposure;
+ vec2 momentsExposureScale = vec2(exposureScale, exposureScale * exposureScale);
+ history.rgb *= exposureScale;
+ historyMoments.rg *= momentsExposureScale;
+
vec3 currentColor = RGBToYCoCg(texelFetch(currentTexture, pixel, 0).rgb);
+ // Misses have a ray length of zero. Mirrors use their own ray length, it has no noise and averaging it across
+ // the edges of reflected objects would mix their distances
+ const float virtualCutoff = 0.2;
float rayLength = texelFetch(currentTexture, pixel, 0).a;
+ float filteredRayLength = mix(abs(rayLength), GetFilteredRayLength(pixel), saturate(roughness / virtualCutoff));
if (rayLength != 0 && roughness < pushConstants.roughnessCutoff) {
- vec2 virtualHistoryPixel = VirtualPointReprojection(pixel, imageSize(resolveImage), abs(rayLength));
-
- bool validRepojection = true;
- vec4 historyVirtualRepojection = vec4(0.0);
- vec4 historyMomentsVirtualRepojection = vec4(0.0);
- validRepojection = SampleHistory(pixel, virtualHistoryPixel, 32.0,
- historyVirtualRepojection, historyMomentsVirtualRepojection);
+ vec2 virtualHistoryPixel = VirtualPointReprojection(pixel, imageSize(resolveImage), filteredRayLength);
+ vec2 virtualHistoryUv = (virtualHistoryPixel + 0.5) * invResolution;
+
+ vec4 historyVirtualRepojection;
+ vec4 historyMomentsVirtualRepojection;
+ bool completeVirtualFootprint;
+ vec4 virtualHistoryMin, virtualHistoryMax;
+ float virtualFootprintConfidence;
+ bool validRepojection = SampleHistory(pixel, virtualHistoryPixel, 32.0,
+ historyVirtualRepojection, historyMomentsVirtualRepojection,
+ completeVirtualFootprint, virtualHistoryMin, virtualHistoryMax, virtualFootprintConfidence) &&
+ !IsOffscreen(virtualHistoryUv);
#ifdef BICUBIC_FILTER
- // This should be implemented more efficiently, see
- if (validRepojection) {
- vec4 catmullRomHistory;
- uv = (virtualHistoryPixel + 0.5) * invResolution;
- bool success = SampleCatmullRom(pixel, uv, catmullRomHistory);
- historyVirtualRepojection = success ? catmullRomHistory : historyVirtualRepojection;
- }
+ if (validRepojection && completeVirtualFootprint)
+ historyVirtualRepojection = clamp(SampleCatmullRom(historyTexture, virtualHistoryUv, resolution),
+ virtualHistoryMin, virtualHistoryMax);
#endif
+ historyVirtualRepojection.rgb *= exposureScale;
+ historyMomentsVirtualRepojection.rg *= momentsExposureScale;
- vec3 virtualNormal = normalize(DecodeNormal(texelFetch(historyNormalTexture, ivec2(virtualHistoryPixel), 0).rg));
- float virtualRoughness = texelFetch(historyRoughnessMetallicAoTexture, ivec2(virtualHistoryPixel), 0).r;
+ ivec2 virtualHistoryTexel = clamp(ivec2(virtualHistoryPixel), ivec2(0), ivec2(resolution) - ivec2(1));
+ vec3 virtualNormal = normalize(DecodeNormal(texelFetch(historyNormalTexture, virtualHistoryTexel, 0).rg));
+ float virtualRoughness = texelFetch(historyRoughnessMetallicAoTexture, virtualHistoryTexel, 0).r;
- const float virtualCutoff = 0.2;
float virtualConfidence = dominantFactor * sqr(max((virtualCutoff - roughness) / virtualCutoff, 0.0));
virtualConfidence *= pow(max(dot(virtualNormal, normal), 0.0), 512.0);
virtualConfidence *= pow(1.0 - abs(virtualRoughness - roughness), 32.0);
- valid = valid || validRepojection;
- history = (historyVirtualRepojection * virtualConfidence +
- (1.0 - virtualConfidence) * history);
+ // Only valid reprojections contribute, below the virtual cutoff the virtual one replaces an invalid surface one
+ float virtualWeight = validRepojection ? (valid ? virtualConfidence : (roughness < virtualCutoff ? 1.0 : 0.0)) : 0.0;
+ valid = valid || virtualWeight > 0.0;
+ history = mix(history, historyVirtualRepojection, virtualWeight);
+ historyMoments = mix(historyMoments, historyMomentsVirtualRepojection, virtualWeight);
+ footprintConfidence = mix(footprintConfidence, virtualFootprintConfidence, virtualWeight);
}
vec2 currentMoments;
currentMoments.r = currentColor.r;
currentMoments.g = currentMoments.r * currentMoments.r;
- vec3 historyNeighbourhoodMin = mean - std;
- vec3 historyNeighbourhoodMax = mean + std;
+ // Two standard deviations, a narrower box shortens converged histories at highlights and reflected edges
+ vec3 historyNeighbourhoodMin = mean - 2.0 * std;
+ vec3 historyNeighbourhoodMax = mean + 2.0 * std;
vec3 currentNeighbourhoodMin = mean - pushConstants.currentClipFactor * std;
vec3 currentNeighbourhoodMax = mean + pushConstants.currentClipFactor * std;
currentColor = clamp(currentColor, currentNeighbourhoodMin, currentNeighbourhoodMax);
vec3 historyColor = RGBToYCoCg(history.rgb);
- float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax,
- historyColor, currentColor);
-
- // In case of clipping we might also reject the sample. TODO: Investigate
- clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax,
- historyColor, currentColor);
- float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax);
- currentColor = valid ? currentColor : mean;
-
- historyColor = YCoCgToRGB(historyColor);
- currentColor = YCoCgToRGB(currentColor);
+ float historyLength = historyMoments.b * footprintConfidence;
- float temporalWeight = mix(pushConstants.temporalWeight, 0.0, adjClipBlend);
-
-#ifdef UPSCALE
- float roughnessMinTemporalWeight = 0.75;
-#else
- float roughnessMinTemporalWeight = temporalWeight;
-#endif
- float factor = clamp(32.0 * log(roughness + 1.0), roughnessMinTemporalWeight, temporalWeight);
- //factor = GetAccumulationSpeed(NdotV, roughness, parallax);
- valid = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0
- || uv.y > 1.0) ? false : valid;
+ // Histories outside the neighborhood shorten, small neighborhoods (thin objects, edges) fully from ten samples on
+ float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax,
+ historyColor, currentColor);
+ float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax);
+ historyLength *= 1.0 - adjClipBlend * saturate((sampleCount - 2.0) / 8.0);
- factor = pushConstants.resetHistory > 0 ? 0.0 : factor;
+ historyLength = LimitHistoryByNearbyMotion(historyLength, nearbyMotion);
- float historyLength = historyMoments.b;
- if (factor <= 0.1 * roughness || !valid) {
+ if (pushConstants.resetHistory > 0 || !valid) {
+ valid = false;
historyLength = 0.0;
currentMoments.g = 1.0;
currentMoments.r = 0.0;
}
- factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y)));
- factor = min(factor, historyLength / (historyLength + 1.0));
+ // New and short histories (disocclusions) start from the neighborhood mean instead of single noisy samples.
+ // Mirrors keep their sample, it has no noise and the mean would mix different reflected content
+ currentColor = mix(mean, currentColor, max(saturate(historyLength / 4.0), 1.0 - saturate(roughness / virtualCutoff)));
+
+ historyColor = YCoCgToRGB(historyColor);
+ currentColor = YCoCgToRGB(currentColor);
+
+ float factor = min(pushConstants.temporalWeight, historyLength / (historyLength + 1.0));
#ifdef UPSCALE
- factor = rayLength > 0.0 ? factor : (valid ? mix(1.0, 0.0, adjClipBlend) : factor);
+ // Misses have a ray length of zero, so the upsampling marks pixels it filled in by their position
+ bool traced = pixel % 2 == pixelOffsets[globalData.frameCount % 4];
+ factor = traced ? factor : (valid ? min(1.0 - adjClipBlend, historyLength / (historyLength + 1.0)) : factor);
#endif
vec3 resolve = factor <= 0.0 ? currentColor : mix(currentColor, historyColor, factor);
vec2 momentsResolve = factor <= 0.0 ? currentMoments : mix(currentMoments, historyMoments.rg, factor);
+ // Accumulated for the spatial filter, which limits its radius by the lobe the reflection rays cover
+ // Pixels above the cutoff sample the probes and have no ray length
+ bool traceRay = roughness < pushConstants.roughnessCutoff && filteredRayLength > 0.0;
+ float currentHitDistance = traceRay ? EncodeHitDistance(filteredRayLength) : 1.0;
+ float hitDistance = factor <= 0.0 ? currentHitDistance : mix(currentHitDistance, historyMoments.a, factor);
+
+ float accumulatedFrames = GetAccumulatedFrames(factor, historyLength);
+
// Boost variance when we have a small history length (we trade blur for noise)
- float varianceBoost = max(1.0, 4.0 / (historyLength + 1.0));
+ float varianceBoost = max(1.0, 4.0 / accumulatedFrames);
float variance = max(0.0, momentsResolve.g - momentsResolve.r * momentsResolve.r);
variance *= varianceBoost;
variance = roughness <= 0.1 ? max(variance * roughness, roughness * 1e-6) : variance;
- imageStore(momentsImage, pixel, vec4(momentsResolve, historyLength + 1.0, 0.0));
+ imageStore(momentsImage, pixel, vec4(momentsResolve, accumulatedFrames, hitDistance));
imageStore(resolveImage, pixel, vec4(vec3(resolve), variance));
}
\ No newline at end of file
diff --git a/data/shader/reflection/upsample.csh b/data/shader/reflection/upsample.csh
index 51f6ddeec..db9ad8bfd 100644
--- a/data/shader/reflection/upsample.csh
+++ b/data/shader/reflection/upsample.csh
@@ -9,6 +9,9 @@
layout (local_size_x = 8, local_size_y = 8) in;
+// Needs the work group size
+#include <../common/upsample.hsh>
+
layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D image;
layout(set = 3, binding = 1) uniform sampler2D lowResTexture;
@@ -21,22 +24,14 @@ shared float depths[36];
shared vec3 normals[36];
shared vec4 data[36];
-const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2);
-const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2;
-
layout(push_constant) uniform constants {
int frameCount;
} pushConstants;
void LoadGroupSharedData() {
- ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1);
-
- // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y
- if (gl_LocalInvocationIndex < depthDataSize) {
- ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize);
- offset += workGroupOffset;
- offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0) - 1);
+ ivec2 offset;
+ if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) {
depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r);
vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg);
@@ -49,25 +44,6 @@ void LoadGroupSharedData() {
}
-const ivec2 offsets[9] = ivec2[9](
- ivec2(-1, -1),
- ivec2(0, -1),
- ivec2(1, -1),
- ivec2(-1, 0),
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(-1, 1),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-const ivec2 pixelOffsets[4] = ivec2[4](
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
vec4 Upsample(float referenceDepth, vec3 referenceNormal, vec2 highResPixel) {
highResPixel /= 2.0;
@@ -109,8 +85,8 @@ void main() {
LoadGroupSharedData();
- if (gl_GlobalInvocationID.x > imageSize(image).x ||
- gl_GlobalInvocationID.y > imageSize(image).y)
+ if (gl_GlobalInvocationID.x >= imageSize(image).x ||
+ gl_GlobalInvocationID.y >= imageSize(image).y)
return;
ivec2 resolution = imageSize(image);
diff --git a/data/shader/rtgi/atrous.csh b/data/shader/rtgi/atrous.csh
index 02b3c7205..b0bee5e6c 100644
--- a/data/shader/rtgi/atrous.csh
+++ b/data/shader/rtgi/atrous.csh
@@ -5,6 +5,8 @@
#include <../common/material.hsh>
#include <../common/normalencode.hsh>
+#include <../common/denoiser.hsh>
+
layout (local_size_x = 16, local_size_y = 16) in;
layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage;
@@ -24,6 +26,8 @@ const int kernelRadius = 4;
const int kernelRadius = 8;
#endif
+const int stepSize = kernelRadius / 2;
+
const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius);
const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius;
@@ -37,19 +41,24 @@ struct PixelData {
struct PackedPixelData {
// Contains 16 bit color, variance, normal and roughness
uvec4 data;
- uint materialIdx;
- float depth;
};
+// Separate arrays, a struct with them would be padded to 32 bytes and exceed 32 KB of shared memory on some devices
shared PackedPixelData pixelData[sharedDataSize];
+shared uint pixelMaterialIdx[sharedDataSize];
+shared float pixelDepth[sharedDataSize];
+shared uint groupFilters;
layout(push_constant) uniform constants {
- int stepSize;
float strength;
} pushConstants;
const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 };
+// In pixels, the three passes together reach 14 pixels
+const float maxBlurRadius = 16.0;
+const float minBlurRadius = 1.5;
+
PackedPixelData PackPixelData(PixelData data) {
PackedPixelData compressed;
@@ -57,8 +66,6 @@ PackedPixelData PackPixelData(PixelData data) {
compressed.data.y = packHalf2x16(data.color.ba);
compressed.data.z = packHalf2x16(data.normal.xy);
compressed.data.w = packHalf2x16(vec2(data.normal.z, 0.0));
- compressed.materialIdx = data.materialIdx;
- compressed.depth = data.depth;
return compressed;
}
@@ -71,8 +78,6 @@ PixelData UnpackPixelData(PackedPixelData compressed) {
data.normal.xy = unpackHalf2x16(compressed.data.z);
vec2 temp = unpackHalf2x16(compressed.data.w);
data.normal.z = temp.x;
- data.materialIdx = compressed.materialIdx;
- data.depth = compressed.depth;
return data;
}
@@ -93,13 +98,17 @@ void LoadGroupSharedData() {
data.color = texelFetch(inputTexture, texel, 0);
- data.depth = texelFetch(depthTexture, texel, 0).r;
+ // Linear depth, zero marks the sky
+ float depth = texelFetch(depthTexture, texel, 0).r;
+ data.depth = depth == 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth);
data.materialIdx = texelFetch(materialIdxTexture, texel, 0).r;
data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg);
pixelData[i] = PackPixelData(data);
+ pixelMaterialIdx[i] = data.materialIdx;
+ pixelDepth[i] = data.depth;
}
barrier();
@@ -110,40 +119,10 @@ PixelData GetPixel(ivec2 pixelOffset) {
ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius);
int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize);
- return UnpackPixelData(pixelData[sharedMemoryIdx]);
-
-}
-
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
-float ComputeEdgeStoppingWeight(float centerLuminance, float sampleLuminance,
- vec3 centerNormal, vec3 sampleNormal,
- float centerDepth, float sampleDepth,
- uint centerMaterialIdx, uint sampleMaterialIdx,
- float luminancePhi, float normalPhi,
- float depthPhi, bool noHistory) {
-
- const float epsilon = 1e-10;
-
- float luminanceDiff = abs(centerLuminance - sampleLuminance);
- float luminanceWeight = min(exp(-luminanceDiff / (luminancePhi + epsilon)), 1.0);
-
- luminanceWeight = noHistory ? 1.0 : luminanceWeight;
-
- float normalDiff = saturate(dot(centerNormal, sampleNormal));
- float normalWeight = min(pow(normalDiff, normalPhi), 1.0);
-
- float depthDiff = abs(centerDepth - sampleDepth);
- float depthWeight = min(exp(-depthDiff * depthPhi), 1.0);
-
- float materialWeight = centerMaterialIdx == sampleMaterialIdx ? 1.0 : 0.0;
-
- return luminanceWeight * normalWeight * depthWeight * materialWeight;
+ PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]);
+ data.materialIdx = pixelMaterialIdx[sharedMemoryIdx];
+ data.depth = pixelDepth[sharedMemoryIdx];
+ return data;
}
@@ -173,75 +152,114 @@ float GetFilteredVariance(ivec2 pixel) {
void main() {
- LoadGroupSharedData();
-
ivec2 pixel = ivec2(gl_GlobalInvocationID);
ivec2 resolution = imageSize(outputImage);
+ bool insideImage = pixel.x < resolution.x && pixel.y < resolution.y;
+
+ vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ vec2 texelSize = 1.0 / vec2(resolution);
- if (pixel.x >= resolution.x || pixel.y >= resolution.y)
+ float depth = insideImage ? texelFetch(depthTexture, pixel, 0).r : 1.0;
+ vec4 moments = insideImage ? texelFetch(historyLengthTexture, pixel, 0) : vec4(0.0);
+
+ vec3 viewRay = GetViewRay(texCoord);
+ vec3 centerPosition = viewRay * ConvertDepthToViewSpaceDepth(depth);
+
+ float historyLength = moments.b;
+ bool noHistory = historyLength <= 1.0;
+
+ // The blur radius shrinks with the effectively accumulated frames and is limited by the hit distance.
+ // Short histories need the blur more than the details, the limit only sets in while they grow
+ float historyRadius = maxBlurRadius / sqrt(max(historyLength, 1.0));
+
+ float hitDistance = DecodeHitDistance(moments.a);
+ // The projection flips y, its scale is negative
+ float pixelWorldSize = 2.0 * abs(centerPosition.z) / (abs(globalData.pMatrix[1][1]) * float(resolution.y));
+ float hitRadius = max(hitDistance / pixelWorldSize, maxBlurRadius / max(historyLength, 1.0));
+
+ float blurRadius = max(minBlurRadius, min(historyRadius, hitRadius));
+
+ // Below half the step size the taps of this pass have no weight left
+ bool filterPixel = insideImage && depth < 1.0 && blurRadius >= 0.5 * float(stepSize);
+
+ if (gl_LocalInvocationIndex == 0)
+ groupFilters = 0u;
+ barrier();
+ if (filterPixel)
+ atomicOr(groupFilters, 1u);
+ barrier();
+
+ if (groupFilters != 0u)
+ LoadGroupSharedData();
+
+ if (!insideImage || depth == 1.0)
return;
- vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+ if (!filterPixel) {
+ imageStore(outputImage, pixel, texelFetch(inputTexture, pixel, 0));
+ return;
+ }
+
+ vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay;
+ vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay;
PixelData centerPixelData = GetPixel(ivec2(0));
-
+
vec4 centerColor = centerPixelData.color;
- float centerDepth = centerPixelData.depth;
vec3 centerNormal = centerPixelData.normal;
uint centerMaterialIdx = centerPixelData.materialIdx;
- if (centerDepth == 1.0)
- return;
-
- float historyLength = texelFetch(historyLengthTexture, pixel, 0).b;
- bool noHistory = historyLength <= 1.0;
-
float centerLuminance = Luma(centerColor.rgb);
- float centerLinearDepth = ConvertDepthToViewSpaceDepth(centerDepth);
-
+
vec4 outputColor = centerColor;
float totalWeight = 1.0;
float variance = GetFilteredVariance(pixel);
float stdDeviation = sqrt(max(0.0, variance));
- vec3 viewDir = normalize(ConvertDepthToViewSpace(centerDepth, texCoord));
+ vec3 viewDir = normalize(centerPosition);
float NdotV = abs(dot(viewDir, centerNormal));
float depthPhi = max(32.0, NdotV * 128.0);
+ // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once.
+ // The distance to the surface plane is affine in the offset since the view ray is
+ const float log2e = 1.442695;
+ float planeRay = dot(viewRay, centerNormal);
+ float planeRayDx = dot(viewRayDx, centerNormal);
+ float planeRayDy = dot(viewRayDy, centerNormal);
+ float planeOffset = dot(centerPosition, centerNormal);
+ float planeScale = depthPhi * log2e / abs(centerPosition.z);
+ float luminanceScale = noHistory ? 0.0 : log2e / (stdDeviation * pushConstants.strength + 1e-10);
+ float normalPhi = noHistory ? 2.0 : NdotV * 128.0;
+ float distanceScale = log2e * float(stepSize * stepSize) / sqr(blurRadius);
+
const int radius = 2;
for (int x = -radius; x <= radius; x++) {
- for (int y = -radius; y <= radius; y++) {
- ivec2 samplePixel = pixel + ivec2(x, y) * pushConstants.stepSize;
+ for (int y = -radius; y <= radius; y++) {
+ ivec2 offset = ivec2(x, y) * stepSize;
+ ivec2 samplePixel = pixel + offset;
if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y ||
samplePixel.x < 0 || samplePixel.y < 0
|| (x == 0 && y == 0))
continue;
- PixelData samplePixelData = GetPixel(ivec2(x, y) * pushConstants.stepSize);
+ PixelData samplePixelData = GetPixel(offset);
- if (samplePixelData.depth == 1.0)
+ if (samplePixelData.depth == 0.0 || samplePixelData.materialIdx != centerMaterialIdx)
continue;
vec4 sampleColor = samplePixelData.color;
- vec3 sampleNormal = samplePixelData.normal;
-
- float sampleDepth = samplePixelData.depth;
- float sampleLuminance = Luma(sampleColor.rgb);
-
- uint sampleMaterialIdx = samplePixelData.materialIdx;
- float kernelWeight = kernelWeights[abs(x)] * kernelWeights[abs(y)];
- float edgeStoppingWeight = ComputeEdgeStoppingWeight(
- centerLuminance, sampleLuminance,
- centerNormal, sampleNormal,
- centerDepth, sampleDepth,
- centerMaterialIdx, sampleMaterialIdx,
- stdDeviation * pushConstants.strength,
- noHistory ? 2.0 : NdotV * 128.0, depthPhi, noHistory);
+ // The distance to the surface plane stays stable at grazing angles, unlike the depth
+ float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx +
+ float(offset.y) * planeRayDy) - planeOffset;
+ float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6);
- float weight = kernelWeight * edgeStoppingWeight;
+ float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale +
+ abs(planeDistance) * planeScale + float(x * x + y * y) * distanceScale -
+ normalPhi * log2(normalDot);
+ float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent);
totalWeight += weight;
outputColor += vec4(vec3(weight), weight * weight) * sampleColor;
diff --git a/data/shader/rtgi/rtgi.csh b/data/shader/rtgi/rtgi.csh
index 4f3cca3aa..1e1e6bd7e 100644
--- a/data/shader/rtgi/rtgi.csh
+++ b/data/shader/rtgi/rtgi.csh
@@ -1,5 +1,3 @@
-#define SHADOW_FILTER_1x1
-
#include <../globals.hsh>
#include <../raytracer/lights.hsh>
#include <../raytracer/tracing.hsh>
@@ -22,9 +20,12 @@
#include <../ddgi/ddgi.hsh>
#include <../ddgi/transmission.hsh>
#include <../clouds/shadow.hsh>
-#include <../shadow.hsh>
+#include <../common/denoiser.hsh>
+
+#ifndef RAY_TRACING_PIPELINE
layout (local_size_x = 8, local_size_y = 4) in;
+#endif
layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D rtrImage;
@@ -33,7 +34,6 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture;
layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture;
layout(set = 3, binding = 4) uniform isampler2D offsetTexture;
layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture;
-layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps;
layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture;
layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture;
@@ -65,24 +65,21 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer {
int textureLevel;
float roughnessCutoff;
int halfRes;
- int padding0;
- int padding1;
ivec2 resolution;
- Shadow shadow;
} uniforms;
+#include <../raytracer/lighting.hsh>
+
vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand);
-vec3 EvaluateDirectLight(inout Surface surface, inout float seed);
-float CheckVisibility(Surface surface, float lightDistance);
void main() {
ivec2 resolution = uniforms.resolution;
- if (int(gl_GlobalInvocationID.x) < resolution.x &&
- int(gl_GlobalInvocationID.y) < resolution.y) {
+ if (int(INVOCATION_ID.x) < resolution.x &&
+ int(INVOCATION_ID.y) < resolution.y) {
- ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ ivec2 pixel = ivec2(INVOCATION_ID.xy);
vec2 texCoord = (vec2(pixel) + vec2(0.5)) / vec2(resolution);
@@ -107,11 +104,18 @@ void main() {
Material material = UnpackMaterial(materialIdx);
vec3 reflection = vec3(0.0);
+#ifdef DEFERRED_SHADOW_RAYS
+ int pixelIdx = pixel.y * resolution.x + pixel.x;
+#endif
+
+ // Mean of the encoded hit distances, misses count as one
+ float hitDistanceSum = 0.0;
+ int hitDistanceCount = 0;
if (depth < 1.0) {
#ifdef AUTO_EXPOSURE
- float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r;
+ float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure;
#else
float radianceLimit = uniforms.radianceLimit;
#endif
@@ -120,6 +124,13 @@ void main() {
for (int i = 0; i < sampleCount; i++) {
int sampleIdx = int(uniforms.frameSeed) * sampleCount + i;
+#ifdef DEFERRED_SHADOW_RAYS
+ int deferredSampleIdx = pixelIdx * sampleCount + i;
+ deferredSamples[deferredSampleIdx].radiance.w = 0.0;
+ deferredLightBase = deferredSampleIdx * uniforms.lightSampleCount;
+ for (int j = 0; j < uniforms.lightSampleCount; j++)
+ deferredLights[deferredLightBase + j] = vec4(0.0, 0.0, 0.0, 1.0);
+#endif
vec3 blueNoiseVec = vec3(
SampleBlueNoise(pixel, sampleIdx, 0, scramblingRankingTexture, sobolSequenceTexture),
SampleBlueNoise(pixel, sampleIdx, 1, scramblingRankingTexture, sobolSequenceTexture),
@@ -163,8 +174,8 @@ void main() {
if (isRayValid) {
// Scale offset by depth since the depth buffer inaccuracies increase at a distance and might not match the ray traced geometry anymore
- float viewOffset = max(1.0, 4.0 * length(viewPos));
- ray.origin = worldPos + ray.direction * EPSILON * viewOffset + sampleNormal * EPSILON * viewOffset;
+ float viewOffset = max(1.0, 1.0 * length(viewPos));
+ ray.origin = worldPos + sampleNormal * EPSILON * viewOffset;
ray.hitID = -1;
ray.hitDistance = 0.0;
@@ -179,11 +190,10 @@ void main() {
#endif
vec3 radiance = vec3(0.0);
-#ifdef OPACITY_CHECK
- HitClosestTransparency(ray, INSTANCE_MASK_ALL, 0.0, rayLength);
-#else
- HitClosest(ray, INSTANCE_MASK_ALL, 0.0, rayLength);
-#endif
+ HitClosestOpacityCheck(ray, INSTANCE_MASK_ALL, 0.0, rayLength);
+
+ hitDistanceSum += ray.hitID != -1 ? EncodeHitDistance(ray.hitDistance) : 1.0;
+ hitDistanceCount++;
#ifdef DDGI
radiance = EvaluateHit(ray, sampleNormal, blueNoiseVec.z);
@@ -197,6 +207,12 @@ void main() {
radiance = EvaluateHit(ray, sampleNormal, blueNoiseVec.z);
#endif
+#ifdef DEFERRED_SHADOW_RAYS
+ deferredSamples[deferredSampleIdx].radiance = vec4(radiance, 1.0);
+ deferredSamples[deferredSampleIdx].lobeWeight = vec4(lobeWeight, radianceLimit);
+ continue;
+#endif
+
if (isnan3(radiance) || isinf3(radiance))
radiance = vec3(0.0);
@@ -212,8 +228,16 @@ void main() {
reflection /= float(sampleCount);
}
+#ifdef DEFERRED_SHADOW_RAYS
+ else {
+ for (int i = 0; i < uniforms.sampleCount; i++)
+ deferredSamples[pixelIdx * uniforms.sampleCount + i].radiance.w = 0.0;
+ }
+#endif
- imageStore(rtrImage, pixel, vec4(reflection, 1.0));
+ // With deferred shadow rays the resolve adds the radiance and keeps the hit distance
+ float hitDistance = hitDistanceCount > 0 ? hitDistanceSum / float(hitDistanceCount) : 1.0;
+ imageStore(rtrImage, pixel, vec4(reflection, hitDistance));
}
}
@@ -228,12 +252,8 @@ vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand) {
return textureLod(specularProbe, ray.direction, 3.0).rgb;
}
- // Unpack the compressed triangle and extract surface parameters
- Instance instance = GetInstance(ray);
- Triangle tri = GetTriangle(ray, instance);
-
bool backfaceHit;
- Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, uniforms.textureLevel);
+ Surface surface = GetHitSurface(ray, false, backfaceHit, uniforms.textureLevel);
#ifdef DDGI
// Trick: Offset on secondary bounce towards camera, avoids light leaking (introducing innacuracies ofc)
@@ -255,75 +275,9 @@ vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand) {
radiance += surface.material.emissiveColor;
float curSeed = float(uniforms.frameSeed) / 255.0;
- // Evaluate direct light
- for (int i = 0; i < uniforms.lightSampleCount; i++) {
- radiance += (EvaluateDirectLight(surface, curSeed) / float(uniforms.lightSampleCount));
- curSeed += 1.0 / float(uniforms.lightSampleCount);
- }
+ float raySeed = float(INVOCATION_ID.x * uniforms.resolution.y + INVOCATION_ID.y);
+ radiance += EvaluateDirectLights(surface, raySeed, curSeed, uniforms.lightSampleCount);
return radiance;
}
-
-vec3 EvaluateDirectLight(inout Surface surface, inout float seed) {
-
- if (GetLightCount() == 0)
- return vec3(0.0);
-
- float raySeed = float(gl_GlobalInvocationID.x * uniforms.resolution.y + gl_GlobalInvocationID.y);
-
- float lightPdf;
- Light light = GetLight(surface, raySeed, seed, lightPdf);
-
- float solidAngle, lightDistance;
- SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance);
-
- bool transmittedLight = IsTransmittedLight(surface);
- Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface;
-
-#ifdef USE_SHADOW_MAP
- float shadowFactor = CalculateShadowWorldSpace(uniforms.shadow, cascadeMaps, surface.P,
- lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal)));
-#else
- float shadowFactor = 1.0;
- if (light.castShadow)
- shadowFactor *= CheckVisibility(lightSurface, lightDistance);
-#endif
-
- // Evaluate the BRDF
- vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) :
- EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface);
- reflectance *= surface.material.opacity;
- vec3 radiance = light.radiance * solidAngle * shadowFactor;
-
- // Check for visibilty. This is important to get an
- // estimate of the solid angle of the light from point P
- // on the surface.
-
-#ifdef CLOUD_SHADOWS
- if (light.type == uint(DIRECTIONAL_LIGHT)) {
- vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0));
- float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap);
-
- radiance *= cloudShadowFactor;
- }
-#endif
-
- return reflectance * radiance * lightSurface.NdotL / lightPdf;
-
-}
-
-float CheckVisibility(Surface surface, float lightDistance) {
-
- if (surface.NdotL > 0.0) {
- Ray ray;
- ray.direction = surface.L;
- float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0;
- ray.origin = surface.P + surface.geometryNormal * (side * EPSILON);
- return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON);
- }
- else {
- return 0.0;
- }
-
-}
diff --git a/data/shader/rtgi/rtgi.rgen b/data/shader/rtgi/rtgi.rgen
new file mode 100644
index 000000000..278f23a74
--- /dev/null
+++ b/data/shader/rtgi/rtgi.rgen
@@ -0,0 +1,7 @@
+// RTGI as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing
+#extension GL_EXT_ray_tracing : require
+#extension GL_EXT_shader_invocation_reorder : require
+
+#define RAY_TRACING_PIPELINE
+
+#include
diff --git a/data/shader/rtgi/rtgiResolve.csh b/data/shader/rtgi/rtgiResolve.csh
new file mode 100644
index 000000000..dc5a00f95
--- /dev/null
+++ b/data/shader/rtgi/rtgiResolve.csh
@@ -0,0 +1,52 @@
+#include <../common/utility.hsh>
+#include <../raytracer/deferredShadow.hsh>
+
+layout (local_size_x = 8, local_size_y = 4) in;
+
+layout (set = 3, binding = 0, rgba16f) uniform image2D giImage;
+
+layout(push_constant) uniform constants {
+ ivec2 resolution;
+ int sampleCount;
+ int lightSampleCount;
+} pushConstants;
+
+void main() {
+
+ ivec2 resolution = pushConstants.resolution;
+ if (int(gl_GlobalInvocationID.x) >= resolution.x || int(gl_GlobalInvocationID.y) >= resolution.y)
+ return;
+
+ ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ int pixelIdx = pixel.y * resolution.x + pixel.x;
+
+ vec3 gi = vec3(0.0);
+ for (int i = 0; i < pushConstants.sampleCount; i++) {
+ int sampleIdx = pixelIdx * pushConstants.sampleCount + i;
+ if (deferredSamples[sampleIdx].radiance.w == 0.0)
+ continue;
+
+ vec3 radiance = deferredSamples[sampleIdx].radiance.rgb;
+ for (int j = 0; j < pushConstants.lightSampleCount; j++) {
+ vec4 light = deferredLights[sampleIdx * pushConstants.lightSampleCount + j];
+ radiance += light.rgb * light.w;
+ }
+
+ if (isnan3(radiance) || isinf3(radiance))
+ radiance = vec3(0.0);
+
+ radiance = max(radiance, vec3(0.0));
+
+ float radianceLimit = deferredSamples[sampleIdx].lobeWeight.w;
+ float radianceMax = max(max(max(radiance.r,
+ max(radiance.g, radiance.b)), radianceLimit), 1e-12);
+ radiance *= radianceLimit / radianceMax;
+
+ gi += radiance * deferredSamples[sampleIdx].lobeWeight.rgb;
+ }
+
+ gi /= float(pushConstants.sampleCount);
+ float hitDistance = imageLoad(giImage, pixel).a;
+ imageStore(giImage, pixel, vec4(gi, hitDistance));
+
+}
diff --git a/data/shader/rtgi/temporal.csh b/data/shader/rtgi/temporal.csh
index 4da3d6b35..61f9c410a 100644
--- a/data/shader/rtgi/temporal.csh
+++ b/data/shader/rtgi/temporal.csh
@@ -12,6 +12,7 @@
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
#include <../common/edgePreserving.hsh>
+#include <../common/denoiser.hsh>
layout (local_size_x = 16, local_size_y = 16) in;
@@ -34,13 +35,21 @@ layout(set = 3, binding = 12) uniform usampler2D historyMaterialIdxTexture;
vec2 invResolution = 1.0 / vec2(imageSize(resolveImage));
vec2 resolution = vec2(imageSize(resolveImage));
-const int kernelRadius = 5;
+const int kernelRadius = 3;
const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius);
const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius;
shared vec4 sharedRadianceDepth[sharedDataSize];
shared uint sharedMaterialIdx[sharedDataSize];
+shared float sharedHitDistance[sharedDataSize];
+shared vec2 sharedObjectMotion[sharedDataSize];
+
+// Neighborhood of the encoded hit distance that is accumulated and compared with its history
+const int hitDistanceRadius = 2;
+// Spread of a pixel's encoded hit distance assumed in addition to the measured one,
+// a few neighbors or identical values (all misses) don't give a reliable estimate
+const float hitDistancePriorSpread = 0.1;
layout(push_constant) uniform constants {
float temporalWeight;
@@ -68,20 +77,6 @@ const ivec2 pixelOffsets[4] = ivec2[4](
ivec2(1, 1)
);
-float Luma(vec3 color) {
-
- const vec3 luma = vec3(0.299, 0.587, 0.114);
- return dot(color, luma);
-
-}
-
-vec3 FetchTexel(ivec2 texel) {
-
- vec3 color = max(texelFetch(currentTexture, texel, 0).rgb, 0);
- return color;
-
-}
-
void LoadGroupSharedData() {
ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) - ivec2(kernelRadius);
@@ -93,9 +88,13 @@ void LoadGroupSharedData() {
texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1));
- sharedRadianceDepth[i].rgb = RGBToYCoCg(FetchTexel(texel));
- sharedRadianceDepth[i].a = texelFetch(depthTexture, texel, 0).r;
+ vec4 current = texelFetch(currentTexture, texel, 0);
+ float depth = texelFetch(depthTexture, texel, 0).r;
+ sharedRadianceDepth[i].rgb = RGBToYCoCg(max(current.rgb, 0.0));
+ sharedHitDistance[i] = current.a;
+ sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(depth);
sharedMaterialIdx[i].r = texelFetch(materialIdxTexture, texel, 0).r;
+ sharedObjectMotion[i] = GetObjectMotion(velocityTexture, texel, depth, resolution);
}
barrier();
@@ -146,31 +145,18 @@ ivec2 FindNearest3x3(ivec2 pixel) {
}
-float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) {
-
- vec3 origin = history;
- vec3 dir = current - history;
-
- // Make sure dir isn't zero
- dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x;
- dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y;
- dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z;
+// The bilinear footprint is complete when all four history texels are valid, their range limits a bicubic filter.
+// The confidence is the valid part of the footprint, it shortens the history of partly valid reprojections
+bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 historyMoments,
+ out bool completeFootprint, out vec4 historyMin, out vec4 historyMax, out float footprintConfidence) {
- vec3 invDir = 1.0 / dir;
-
- vec3 t0 = (boxMin - origin) * invDir;
- vec3 t1 = (boxMax - origin) * invDir;
-
- vec3 intersect = min(t0, t1);
- return max(intersect.x, max(intersect.y, intersect.z));
-
-}
-
-bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 historyMoments) {
-
+ footprintConfidence = 0.0;
history = vec4(0.0);
historyMoments = vec4(0.0);
+ historyMin = vec4(1e30);
+ historyMax = vec4(-1e30);
+ int validCount = 0;
float totalWeight = 0.0;
float x = fract(historyPixel.x);
float y = fract(historyPixel.y);
@@ -187,7 +173,6 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi
vec3 viewDir = normalize(position - globalData.cameraLocation.xyz);
float NdotV = abs(dot(viewDir, worldNormal));
- float linearDepth = depth;
float depthPhi = max(1.0, NdotV * 32.0 * abs(ConvertDepthToViewSpaceDepth(depth)));
// Calculate confidence over 2x2 bilinear neighborhood
@@ -202,16 +187,27 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi
float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r;
float depthWeight = min(1.0 , exp(-abs(depth - historyDepth) * depthPhi));
- float confidence = normalWeight * depthWeight;
+ uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r;
+ float materialWeight = historyMaterialIdx == materialIdx ? 1.0 : 0.0;
+
+ float confidence = normalWeight * depthWeight * materialWeight;
+
+ if (confidence > 0.2) {
+ vec4 historyTexel = texelFetch(historyTexture, offsetPixel, 0);
+ historyMin = min(historyMin, historyTexel);
+ historyMax = max(historyMax, historyTexel);
+ validCount++;
- if (confidence > 0.2) {
totalWeight += weights[i];
- history += texelFetch(historyTexture, offsetPixel, 0) * weights[i];
+ history += historyTexel * weights[i];
historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i];
}
}
+ completeFootprint = validCount == 4;
+
if (totalWeight > 0.0) {
+ footprintConfidence = totalWeight;
history /= totalWeight;
historyMoments /= totalWeight;
return true;
@@ -228,7 +224,10 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi
float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r;
float depthWeight = min(1.0 , exp(-abs(depth - historyDepth) * depthPhi));
- float confidence = normalWeight * depthWeight;
+ uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r;
+ float materialWeight = historyMaterialIdx == materialIdx ? 1.0 : 0.0;
+
+ float confidence = normalWeight * depthWeight * materialWeight;
if (confidence > 0.5) {
totalWeight += 1.0;
@@ -238,6 +237,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi
}
if (totalWeight > 0.0) {
+ // None of the footprint texels matched, the neighbors around it are less trustworthy
+ footprintConfidence = totalWeight / 9.0;
history /= totalWeight;
historyMoments /= totalWeight;
return true;
@@ -250,91 +251,20 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi
}
-float IsHistoryPixelValid(ivec2 pixel, float linearDepth, vec3 normal, float depthPhi) {
-
- float confidence = 1.0;
-
- vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, pixel, 0).rg);
- confidence *= GetEdgePreservingNormalWeight(normal, historyNormal, 1.0);
-
- float historyDepth = ConvertDepthToViewSpaceDepth(texelFetch(historyDepthTexture, pixel, 0).r);
- confidence *= min(1.0 , exp(-abs(linearDepth - historyDepth)));
-
- return confidence > 0.1 ? 1.0 : 0.0;
-
-}
-
-vec4 GetCatmullRomSample(ivec2 pixel, inout float weight, float linearDepth, vec3 normal, float depthPhi) {
-
- pixel = clamp(pixel, ivec2(0), ivec2(imageSize(resolveImage) - 1));
-
- weight *= IsHistoryPixelValid(pixel, linearDepth, normal, depthPhi);
-
- return texelFetch(historyTexture, pixel, 0) * weight;
-
-}
-
-bool SampleCatmullRom(ivec2 pixel, vec2 uv, out vec4 history) {
-
- vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg);
- float depth = texelFetch(depthTexture, pixel, 0).r;
- vec2 texCoord = (vec2(pixel) + 0.5) / resolution;
- vec3 position = ConvertDepth(depth, texCoord, globalData.ipvMatrixCurrent);
- vec3 worldNormal = vec3(globalData.ivMatrix * vec4(normal, 0.0));
-
- vec3 viewDir = normalize(position - globalData.cameraLocation.xyz);
- float NdotV = abs(dot(viewDir, worldNormal));
- float linearDepth = ConvertDepthToViewSpaceDepth(depth);
- float depthPhi = max(1.0, NdotV * 16.0 / max(1.0, abs(linearDepth)));
-
- vec2 samplePixel = uv * resolution;
-
- vec2 center = floor(samplePixel - 0.5) + 0.5;
- vec2 f = samplePixel - center;
- vec2 f2 = f * f;
- vec2 f3 = f2 * f;
-
- vec2 w0 = f2 - 0.5 * (f3 + f);
- vec2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0;
- vec2 w3 = 0.5 * (f3 - f2);
- vec2 w2 = 1.0 - w0 - w1 - w3;
-
- ivec2 uv0 = ivec2(center - 1.0);
- ivec2 uv1 = ivec2(center);
- ivec2 uv2 = ivec2(center + 1.0);
- ivec2 uv3 = ivec2(center + 2.0);
-
- ivec2 uvs[4] = { uv0, uv1, uv2, uv3 };
- vec2 weights[4] = { w0, w1, w2, w3 };
-
- history = vec4(0.0);
-
- float totalWeight = 0.0;
-
- for (int x = 0; x <= 3; x++) {
- for (int y = 0; y <= 3; y++) {
- float weight = weights[x].x * weights[y].y;
- ivec2 uv = ivec2(uvs[x].x, uvs[y].y);
-
- history += GetCatmullRomSample(uv, weight, linearDepth, normal, depthPhi);
- totalWeight += weight;
- }
- }
-
- if (totalWeight > 0.5) {
- history /= totalWeight;
- history = max(history, 0.0);
-
- return true;
- }
-
- return false;
-}
-
-void ComputeVarianceMinMax(out vec3 mean, out vec3 std) {
+// Sample counts are effective ones of the weighted neighborhoods, (sum of weights)^2 / sum of squared weights.
+// The hit distance mean comes with its standard error, the noise expected for it without any change.
+// The nearby motion is the fastest movement of a neighbor around the same depth relative to the pixel in pixels
+void ComputeVarianceMinMax(out vec3 mean, out vec3 std, out float sampleCount,
+ out float hitDistanceMean, out float hitDistanceError, out float nearbyMotion) {
vec3 m1 = vec3(0.0);
vec3 m2 = vec3(0.0);
+ float squaredWeight = 0.0;
+
+ float h1 = 0.0;
+ float h2 = 0.0;
+ float hitDistanceWeight = 0.0;
+ float hitDistanceSquaredWeight = 0.0;
// This could be varied using the temporal variance estimation
// By using a wide neighborhood for variance estimation (8x8) we introduce block artifacts
@@ -356,33 +286,52 @@ void ComputeVarianceMinMax(out vec3 mean, out vec3 std) {
float totalWeight = 0.0;
+ vec2 centerObjectMotion = sharedObjectMotion[GetSharedMemoryIndex(ivec2(0))];
+ float nearbyMotionSquared = 0.0;
+ float depthScale = 1.442695 * depthPhi;
+
for (int i = -radius; i <= radius; i++) {
for (int j = -radius; j <= radius; j++) {
int sharedMemoryIdx = GetSharedMemoryIndex(ivec2(i, j));
vec3 sampleRadiance = FetchCurrentRadiance(sharedMemoryIdx);
- float sampleDepth = FetchDepth(sharedMemoryIdx);
+ float sampleLinearDepth = FetchDepth(sharedMemoryIdx);
uint sampleMaterialIdx = FetchMaterialIdx(sharedMemoryIdx);
- ivec2 samplePixel = pixel + ivec2(i, j);
- texCoord = (vec2(pixel) + 0.5) / resolution;
- vec3 samplePosition = ConvertDepth(sampleDepth, texCoord, globalData.ipvMatrixCurrent);
-
- float sampleLinearDepth = ConvertDepthToViewSpaceDepth(sampleDepth);
- float weight = min(1.0 , exp(-abs(linearDepth - sampleLinearDepth) * depthPhi));
+ float weight = exp2(-abs(linearDepth - sampleLinearDepth) * depthScale);
weight *= sampleMaterialIdx != materialIdx ? 0.0 : 1.0;
m1 += sampleRadiance * weight;
m2 += sampleRadiance * sampleRadiance * weight;
- totalWeight += weight;
+ totalWeight += weight;
+ squaredWeight += weight * weight;
+
+ nearbyMotionSquared = max(nearbyMotionSquared, GetNearbyMotionSquared(sharedObjectMotion[sharedMemoryIdx],
+ centerObjectMotion, linearDepth, sampleLinearDepth));
+
+ if (abs(i) <= hitDistanceRadius && abs(j) <= hitDistanceRadius) {
+ float sampleHitDistance = sharedHitDistance[sharedMemoryIdx];
+ h1 += sampleHitDistance * weight;
+ h2 += sampleHitDistance * sampleHitDistance * weight;
+ hitDistanceWeight += weight;
+ hitDistanceSquaredWeight += weight * weight;
+ }
}
}
mean = m1 / totalWeight;
std = sqrt(max((m2 / totalWeight) - (mean * mean), 0.0));
+ sampleCount = sqr(totalWeight) / squaredWeight;
+ nearbyMotion = sqrt(nearbyMotionSquared);
+
+ hitDistanceMean = h1 / hitDistanceWeight;
+ float hitDistanceSampleCount = sqr(hitDistanceWeight) / hitDistanceSquaredWeight;
+ float hitDistanceVariance = max(h2 / hitDistanceWeight - hitDistanceMean * hitDistanceMean, 0.0) *
+ hitDistanceSampleCount / max(hitDistanceSampleCount - 1.0, 1.0);
+ hitDistanceError = sqrt((hitDistanceVariance + sqr(hitDistancePriorSpread)) / hitDistanceSampleCount);
}
void main() {
@@ -390,12 +339,13 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
vec3 mean, std;
- ComputeVarianceMinMax(mean, std);
+ float sampleCount, hitDistanceMean, hitDistanceError, nearbyMotion;
+ ComputeVarianceMinMax(mean, std, sampleCount, hitDistanceMean, hitDistanceError, nearbyMotion);
ivec2 velocityPixel = pixel;
vec2 velocity = texelFetch(velocityTexture, velocityPixel, 0).rg;
@@ -403,18 +353,25 @@ void main() {
vec2 uv = (vec2(pixel) + vec2(0.5)) * invResolution + velocity;
vec2 historyPixel = vec2(pixel) + (velocity * resolution);
- bool valid = true;
vec4 history;
vec4 historyMoments;
- valid = SampleHistory(pixel, historyPixel, history, historyMoments);
+ bool completeFootprint;
+ vec4 historyMin, historyMax;
+ float footprintConfidence;
+ bool valid = SampleHistory(pixel, historyPixel, history, historyMoments,
+ completeFootprint, historyMin, historyMax, footprintConfidence);
#ifdef BICUBIC_FILTER
- // This should be implemented more efficiently, see
- vec4 catmullRomHistory;
- bool success = SampleCatmullRom(pixel, uv, catmullRomHistory);
- history = success && valid ? catmullRomHistory : history;
+ // The clamp removes ringing and texels outside the footprint that belong to other surfaces
+ if (completeFootprint)
+ history = clamp(SampleCatmullRom(historyTexture, uv, resolution), historyMin, historyMax);
#endif
+ // The history was stored with the pre-exposure of the last frame, the moments hold luma and its square
+ float exposureScale = globalData.preExposure / globalData.lastPreExposure;
+ history.rgb *= exposureScale;
+ historyMoments.rg *= vec2(exposureScale, exposureScale * exposureScale);
+
vec3 historyColor = RGBToYCoCg(history.rgb);
vec3 currentColor = RGBToYCoCg(texelFetch(currentTexture, pixel, 0).rgb);
@@ -422,52 +379,57 @@ void main() {
currentMoments.r = currentColor.r;
currentMoments.g = currentMoments.r * currentMoments.r;
- float historyLength = historyMoments.b;
+ float historyLength = historyMoments.b * footprintConfidence;
+
+ // A changed hit distance means the geometry the rays see changed, shorten above two standard errors, reset at six
+ float hitDistanceDeviation = abs(hitDistanceMean - historyMoments.a) / hitDistanceError;
+ historyLength *= saturate((6.0 - hitDistanceDeviation) / 4.0);
+
+ historyLength = LimitHistoryByNearbyMotion(historyLength, nearbyMotion);
- vec3 historyNeighbourhoodMin = mean - std;
- vec3 historyNeighbourhoodMax = mean + std;
+ // Two standard deviations, a narrower box shortens converged histories at highlights and edges
+ vec3 historyNeighbourhoodMin = mean - 2.0 * std;
+ vec3 historyNeighbourhoodMax = mean + 2.0 * std;
vec3 currentNeighbourhoodMin = mean - pushConstants.currentClipFactor * std;
vec3 currentNeighbourhoodMax = mean + pushConstants.currentClipFactor * std;
- // In case of clipping we might also reject the sample. TODO: Investigate
+ // Histories outside the neighborhood shorten, small neighborhoods (thin objects, edges) fully from ten samples on
float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax,
historyColor, currentColor);
float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax);
+ historyLength *= 1.0 - adjClipBlend * saturate((sampleCount - 2.0) / 8.0);
currentColor = clamp(currentColor, currentNeighbourhoodMin, currentNeighbourhoodMax);
- currentColor.r = valid ? currentColor.r : mean.r;
-
- historyColor = YCoCgToRGB(historyColor);
- currentColor = YCoCgToRGB(currentColor);
-
- //float factor = mix(0.0, pushConstants.temporalWeight, 1.0 - adjClipBlend);
- float factor = mix(pushConstants.temporalWeight, 0.5, adjClipBlend);
- factor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0
- || uv.y > 1.0) ? 0.0 : factor;
-
- factor = pushConstants.resetHistory > 0 ? 0.0 : factor;
-
- if (factor == 0.0 || !valid) {
+ if (IsOffscreen(uv) || pushConstants.resetHistory > 0 || !valid) {
historyLength = 0.0;
currentMoments.g = 1.0;
currentMoments.r = 0.0;
}
- factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y)));
- factor = min(factor, historyLength / (historyLength + 1.0));
+ // New and short histories (disocclusions) start from the neighborhood mean instead of single noisy samples
+ currentColor = mix(mean, currentColor, saturate(historyLength / 4.0));
+
+ historyColor = YCoCgToRGB(historyColor);
+ currentColor = YCoCgToRGB(currentColor);
+
+ float factor = min(pushConstants.temporalWeight, historyLength / (historyLength + 1.0));
vec3 resolve = factor <= 0.0 ? currentColor : mix(currentColor, historyColor, factor);
vec2 momentsResolve = factor <= 0.0 ? currentMoments : mix(currentMoments, historyMoments.rg, factor);
+ float hitDistance = factor <= 0.0 ? hitDistanceMean : mix(hitDistanceMean, historyMoments.a, factor);
+
+ float accumulatedFrames = GetAccumulatedFrames(factor, historyLength);
+
// Boost variance when we have a small history length (we trade blur for noise)
- float varianceBoost = max(1.0, 16.0 / (historyLength + 1.0));
+ float varianceBoost = max(1.0, 16.0 / accumulatedFrames);
float variance = max(0.0, momentsResolve.g - momentsResolve.r * momentsResolve.r);
variance *= varianceBoost;
variance = max(variance, 1e-5);
- imageStore(momentsImage, pixel, vec4(momentsResolve, historyLength + 1.0, 0.0));
+ imageStore(momentsImage, pixel, vec4(momentsResolve, accumulatedFrames, hitDistance));
imageStore(resolveImage, pixel, vec4(resolve, variance));
}
\ No newline at end of file
diff --git a/data/shader/shadow.hsh b/data/shader/shadow.hsh
index ed48e3d58..1be96a883 100644
--- a/data/shader/shadow.hsh
+++ b/data/shader/shadow.hsh
@@ -282,7 +282,16 @@ float cascadeLookup(inout Shadow shadow, texture2DArray cascadeMaps, sampler sh
visibility += offsetLookup(cascadeMaps, shadowSampler, shadowCoords.xy, 0.0, 0.0, float(cascadeIndex), resInv, shadowCoords.z, bias);
#endif
#ifdef SHADOW_FILTER_VOGEL
+ // Four taps spread over the disk decide whether the pixel is fully lit or fully shadowed
+ for (int i = 0; i < 16; i += 4) {
+ visibility += offsetLookup(cascadeMaps, shadowSampler, uv, float(cascadeIndex), shadow.edgeSoftness, texelSize, resInv, position, i, shadowCoords.z, bias);
+ }
+ if (visibility == 0.0 || visibility == 4.0)
+ return clamp(visibility * 0.25 + fadeout, 0.0, 1.0);
+
for (int i = 0; i < 16; i++) {
+ if (i % 4 == 0)
+ continue;
visibility += offsetLookup(cascadeMaps, shadowSampler, uv, float(cascadeIndex), shadow.edgeSoftness, texelSize, resInv, position, i, shadowCoords.z, bias);
}
#endif
@@ -406,7 +415,7 @@ float CalculateShadowWorldSpace(inout Shadow shadow, texture2DArray cascadeMaps,
mat4(transpose(cascadeMatrix)), position, position, vec2(texelSize), 0.0, false);
}
-vec3 sampleOffsetDirections[20] = vec3[] (
+const vec3 sampleOffsetDirections[20] = vec3[] (
vec3( 1, 1, 1), vec3( 1, -1, 1), vec3(-1, -1, 1), vec3(-1, 1, 1),
vec3( 1, 1, -1), vec3( 1, -1, -1), vec3(-1, -1, -1), vec3(-1, 1, -1),
vec3( 1, 1, 0), vec3( 1, -1, 0), vec3(-1, -1, 0), vec3(-1, 1, 0),
@@ -442,7 +451,7 @@ float CalculatePointShadow(inout Shadow shadow, textureCube cubeMap, sampler sha
shadowFactor += clamp(texture(samplerCubeShadow(cubeMap, shadowSampler),
vec4(shadowCoords.xyz + sampleOffsetDirections[i] * diskRadius, depth - 0.0001)), 0.0, 1.0);
}
- shadowFactor /= float(samples + 1);
+ shadowFactor /= float(samples);
return shadowFactor;
@@ -450,8 +459,6 @@ float CalculatePointShadow(inout Shadow shadow, textureCube cubeMap, sampler sha
float CalculateSpotShadow(inout Shadow shadow, texture2DArray cascadeMaps, sampler shadowSampler,
vec3 fragmentPosition, vec3 position, vec3 normal, float cosTheta) {
-
- float distance = -fragmentPosition.z;
mat4 shadowMatrix;
shadowMatrix[0] = shadow.cascades[0].cascadeSpace[0];
diff --git a/data/shader/shadowMapping.fsh b/data/shader/shadowMapping.fsh
index 4140ce000..6982b80c0 100644
--- a/data/shader/shadowMapping.fsh
+++ b/data/shader/shadowMapping.fsh
@@ -1,25 +1,51 @@
#include
+#include
+#include
+#include
-#ifdef OPACITY_MAP
+#if defined(OPACITY_MAP) || defined(MATERIAL_GRAPH_SURFACE)
layout(location = 0) in vec2 texCoordVS;
#endif
-layout(push_constant) uniform constants {
- mat4 lightSpaceMatrix;
- uint vegetation;
- uint invertUVs;
- float windTextureLod;
- float windBendScale;
- float windWiggleScale;
- uint textureID;
-} PushConstants;
+#ifdef TRANSLUCENT
+layout(location = 13) flat in float opacityVS;
+#endif
+
+#ifdef MATERIAL_GRAPH_SURFACE
+layout(location = 1) in vec3 worldPositionVS;
+layout(location = 2) in vec3 worldNormalVS;
+layout(location = 3) in vec4 vertexColorsVS;
+layout(location = 10) in vec3 objectPositionVS;
+layout(location = 11) in vec3 instancePositionVS;
+layout(location = 12) in vec3 objectNormalVS;
+#endif
void main() {
-
+
+ float opacity = 1.0;
+#ifdef TRANSLUCENT
+ opacity = opacityVS;
+#endif
+
#ifdef OPACITY_MAP
- float opacity = SampleOpacity(texCoordVS, PushConstants.textureID, 0.0);
- if(opacity < 0.2)
+ opacity *= SampleOpacity(texCoordVS, PushConstants.textureID, 0.0);
+#endif
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ MaterialSurfaceInput surfaceInput = CreateMaterialSurfaceInput(objectPositionVS, normalize(objectNormalVS),
+ worldPositionVS, normalize(worldNormalVS), instancePositionVS, mat3(1.0), texCoordVS, vec2(0.0),
+ vertexColorsVS, gl_FrontFacing ? 1.0 : -1.0, PushConstants.materialGraphOffset);
+ opacity *= EvaluateMaterialSurface(surfaceInput).opacity;
+#endif
+
+#ifdef TRANSLUCENT
+ // A pattern changing every frame lets light through by the opacity, the filtering of the shadow maps and the temporal
+ // accumulation average it to a partial shadow. White noise leaves coarser blotches than interleaved gradient noise
+ if (opacity <= GetInterleavedGradientNoise(gl_FragCoord.xy, 16u))
+ discard;
+#else
+ if (opacity < opacityCutoff)
discard;
#endif
-
-}
\ No newline at end of file
+
+}
diff --git a/data/shader/shadowMapping.hsh b/data/shader/shadowMapping.hsh
new file mode 100644
index 000000000..2fd97caea
--- /dev/null
+++ b/data/shader/shadowMapping.hsh
@@ -0,0 +1,31 @@
+// Has to match ShadowRenderer::DrawData and ShadowRenderer::PushConstants
+
+// Only the wind and the opacity differ between the draws of a merged pipeline
+struct ShadowDraw {
+ float windTextureLod;
+ float windBendScale;
+ float windWiggleScale;
+ float opacity;
+};
+
+layout(push_constant) uniform constants {
+ mat4 lightSpaceMatrix;
+ uint deformOffset;
+ uint jointCount;
+ uint instanceOffset;
+ // With DRAW_DATA the data of a draw is at firstDraw + gl_DrawID, the draws of a multi draw follow each other
+ uint firstDraw;
+ uint invertUVs;
+ uint textureID;
+ uint materialGraphOffset;
+ float uvAnimationX;
+ float uvAnimationY;
+ float uvTiling;
+ ShadowDraw draw;
+} PushConstants;
+
+#ifdef DRAW_DATA
+layout(std430, set = 3, binding = 10) readonly buffer ShadowDraws {
+ ShadowDraw shadowDraws[];
+};
+#endif
diff --git a/data/shader/shadowMapping.vsh b/data/shader/shadowMapping.vsh
index 87af352ce..820d7585c 100644
--- a/data/shader/shadowMapping.vsh
+++ b/data/shader/shadowMapping.vsh
@@ -1,51 +1,185 @@
#include
#include
+#include
+#include
+#include
+#include
layout(location=0) in vec3 vPosition;
-#ifdef OPACITY_MAP
+#ifdef MATERIAL_GRAPH
+layout(location=1) in vec4 vNormal;
+#ifdef TANGENTS
+layout(location=3) in vec4 vTangent;
+#endif
+#ifdef VERTEX_COLORS
+layout(location=4) in vec4 vVertexColors;
+#endif
+#endif
+#if defined(OPACITY_MAP) || (defined(MATERIAL_GRAPH) && defined(TEX_COORDS))
layout(location=2) in vec2 vTexCoord;
#endif
+#ifdef SKINNED
+layout(location=5) in uvec4 vJoints;
+layout(location=6) in vec4 vWeights;
+#endif
+#if defined(MATERIAL_GRAPH) && defined(TEX_COORDS_1)
+layout(location=7) in vec2 vTexCoord1;
+#endif
-#ifdef OPACITY_MAP
+#if defined(OPACITY_MAP) || defined(MATERIAL_GRAPH_SURFACE)
layout(location=0) out vec2 texCoordVS;
#endif
+#ifdef TRANSLUCENT
+layout(location=13) flat out float opacityVS;
+#endif
+
+#ifdef MATERIAL_GRAPH_SURFACE
+layout(location=1) out vec3 worldPositionVS;
+layout(location=2) out vec3 worldNormalVS;
+layout(location=3) out vec4 vertexColorsVS;
+layout(location=10) out vec3 objectPositionVS;
+layout(location=11) out vec3 instancePositionVS;
+layout(location=12) out vec3 objectNormalVS;
+#endif
+
+#ifdef INSTANCE_BUFFER
+#include
+#else
layout(std430, set = 1, binding = 1) readonly buffer Matrices {
mat3x4 matrices[];
};
+#endif
-layout(set = 3, binding = 0) uniform sampler2D windNoiseMap;
+#ifdef SKINNED
+layout(std430, set = 1, binding = 4) readonly buffer JointMatrices {
+ mat3x4 jointMatrices[];
+};
+#endif
-layout(push_constant) uniform constants {
- mat4 lightSpaceMatrix;
- uint vegetation;
- uint invertUVs;
- float windTextureLod;
- float windBendScale;
- float windWiggleScale;
- uint textureID;
-} PushConstants;
+#ifdef SOFT_BODY
+// Positions with the packed normal in w, each instance has the offset of its vertices
+layout(std430, set = 1, binding = 24) readonly buffer SoftBodyVertices {
+ vec4 softBodyVertices[];
+};
+
+layout(std430, set = 1, binding = 26) readonly buffer SoftBodyVertexOffsets {
+ uint softBodyVertexOffsets[];
+};
+#endif
+
+layout(set = 3, binding = 0) uniform sampler2D windNoiseMap;
void main() {
+#ifdef INSTANCE_BUFFER
+ mat4 mMatrix = GetInstanceMatrix(instanceIndices[gl_InstanceIndex]);
+#else
mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex]));
-
+#endif
+
+#ifdef DRAW_DATA
+ ShadowDraw draw = shadowDraws[PushConstants.firstDraw + uint(gl_DrawID)];
+#else
+ ShadowDraw draw = PushConstants.draw;
+#endif
+#ifdef TRANSLUCENT
+ opacityVS = draw.opacity;
+#endif
+
#ifdef OPACITY_MAP
- texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord;
+ texCoordVS = TransformTexCoord(vTexCoord, PushConstants.invertUVs > 0,
+ vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY), PushConstants.uvTiling);
#endif
mat4 matrix = mMatrix;
vec3 position = vPosition;
- if (PushConstants.vegetation > 0) {
+#ifdef SKINNED
+ uint jointOffset = PushConstants.deformOffset + (gl_InstanceIndex - PushConstants.instanceOffset) * PushConstants.jointCount;
+ vec4 weights = vWeights / dot(vWeights, vec4(1.0));
+
+ mat3x4 skinMatrix = weights.x * jointMatrices[jointOffset + vJoints.x] +
+ weights.y * jointMatrices[jointOffset + vJoints.y] +
+ weights.z * jointMatrices[jointOffset + vJoints.z] +
+ weights.w * jointMatrices[jointOffset + vJoints.w];
+
+ position = vec4(vPosition, 1.0) * skinMatrix;
+#endif
+
+#ifdef SOFT_BODY
+ vec4 softBodyVertex = softBodyVertices[softBodyVertexOffsets[PushConstants.deformOffset + gl_InstanceIndex -
+ PushConstants.instanceOffset] + gl_VertexIndex];
+ position = softBodyVertex.xyz;
+#endif
+
+#ifdef MATERIAL_GRAPH
+ vec3 graphNormal = vNormal.xyz;
+ vec2 graphTexCoord = vec2(0.0);
+ vec2 graphTexCoord1 = vec2(0.0);
+ vec3 graphTangent = vec3(1.0, 0.0, 0.0);
+ vec4 graphColor = vec4(1.0);
+#ifdef SKINNED
+ graphNormal = vec4(graphNormal, 0.0) * skinMatrix;
+#endif
+#ifdef SOFT_BODY
+ graphNormal = unpackUnitVector(floatBitsToInt(softBodyVertex.w)).xyz;
+#endif
+#ifdef TEX_COORDS
+ graphTexCoord = TransformTexCoord(vTexCoord, PushConstants.invertUVs > 0,
+ vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY), PushConstants.uvTiling);
+#endif
+#ifdef TEX_COORDS_1
+ graphTexCoord1 = PushConstants.invertUVs > 0 ? vec2(vTexCoord1.x, 1.0 - vTexCoord1.y) : vTexCoord1;
+#endif
+#ifdef TANGENTS
+ graphTangent = vTangent.xyz;
+#endif
+#ifdef VERTEX_COLORS
+ graphColor = vVertexColors;
+#endif
- // This is not well optimized and could use some work
- vec3 windPosition = vec3(mMatrix * vec4(position, 1.0));
- vec2 windDir = normalize((inverse(mMatrix) * vec4(globalData.windDir.x, 0.0, globalData.windDir.y, 0.0)).xz);
- position = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale,
- PushConstants.windWiggleScale, PushConstants.windTextureLod, globalData.time, windPosition);
+ MaterialVertexInput graphInput = CreateMaterialVertexInput(vPosition, position, graphNormal, graphTangent, graphTexCoord, graphTexCoord1,
+ graphColor, mMatrix, globalData.time, PushConstants.materialGraphOffset);
+#ifdef MATERIAL_GRAPH_VERTEX_OPACITY
+#ifdef TRANSLUCENT
+ opacityVS *= EvaluateMaterialOpacity(graphInput);
+ if (opacityVS <= 0.0) {
+#else
+ if (EvaluateMaterialOpacity(graphInput) < opacityCutoff) {
+#endif
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ return;
}
+#endif
+
+ WriteMaterialVaryings(graphInput);
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ texCoordVS = graphTexCoord;
+ objectPositionVS = vPosition;
+ objectNormalVS = graphNormal;
+ instancePositionVS = vec3(mMatrix[3]);
+ worldNormalVS = graphInput.worldNormal;
+ vertexColorsVS = graphColor;
+#endif
+
+#ifdef MATERIAL_GRAPH_VERTEX_OFFSET
+ position += EvaluateMaterialVertexOffset(graphInput);
+#endif
+
+#ifdef MATERIAL_GRAPH_SURFACE
+ worldPositionVS = vec3(mMatrix * vec4(position, 1.0));
+#endif
+#endif
+
+#ifdef VEGETATION
+ vec3 windPosition = vec3(mMatrix * vec4(position, 1.0));
+ vec2 windDir = GetWindDirection(mMatrix);
+ position = WindAnimation(windNoiseMap, position, windDir, draw.windBendScale,
+ draw.windWiggleScale, draw.windTextureLod, globalData.time, windPosition);
+#endif
gl_Position = PushConstants.lightSpaceMatrix * matrix * vec4(position, 1.0f);
diff --git a/data/shader/skybox.csh b/data/shader/skybox.csh
index 148ca41ce..a68bec0b2 100644
--- a/data/shader/skybox.csh
+++ b/data/shader/skybox.csh
@@ -18,8 +18,8 @@ vec2 resolution = vec2(imageSize(colorImage));
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(colorImage).x ||
- pixel.y > imageSize(colorImage).y)
+ if (pixel.x >= imageSize(colorImage).x ||
+ pixel.y >= imageSize(colorImage).y)
return;
float depth = texelFetch(depthTexture, pixel, 0).r;
@@ -34,7 +34,7 @@ void main() {
vec3 cubemapCoord = normalize(worldPos - globalData.cameraLocation.xyz);
- vec3 color = textureLod(skyCubemap, cubemapCoord, 0).rgb;
+ vec3 color = textureLod(skyCubemap, cubemapCoord, 0).rgb * globalData.skyCubemapExposure;
vec3 cameraLocationDiff = globalData.cameraLocation.xyz - pushConstants.cameraLocationLast.xyz;
diff --git a/data/shader/ssgi/ssgi.csh b/data/shader/ssgi/ssgi.csh
index 923166543..82973bdf0 100644
--- a/data/shader/ssgi/ssgi.csh
+++ b/data/shader/ssgi/ssgi.csh
@@ -34,6 +34,7 @@ layout(set = 3, binding = 6) uniform sampler2D directLightTexture;
layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture;
layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture;
+layout(set = 3, binding = 14) uniform sampler2D hiZTexture;
layout(set = 1, binding = 12) uniform samplerCube diffuseProbe;
@@ -55,6 +56,7 @@ layout(std140, set = 3, binding = 9) uniform UniformBuffer {
uint rayCount;
uint sampleCount;
int downsampled2x;
+ int hiZLevelCount;
} uniforms;
float Luma(vec3 color) {
@@ -80,8 +82,10 @@ void main() {
float depth = texelFetch(depthTexture, pixel, 0).r;
- vec2 recontructTexCoord = (2.0 * vec2(pixel) + pixelOffset + vec2(0.5)) / (2.0 * vec2(resolution));
- vec3 viewPos = ConvertDepthToViewSpace(depth, texCoord);
+ // The downsampled data belongs to one pixel of the 2x2 block
+ vec2 recontructTexCoord = uniforms.downsampled2x > 0 ?
+ (2.0 * vec2(pixel) + pixelOffset + vec2(0.5)) / (2.0 * vec2(resolution)) : texCoord;
+ vec3 viewPos = ConvertDepthToViewSpace(depth, recontructTexCoord);
vec3 worldPos = vec3(globalData.ivMatrix * vec4(viewPos, 1.0));
vec3 viewVec = vec3(globalData.ivMatrix * vec4(viewPos, 0.0));
vec3 viewNorm = normalize(DecodeNormal(textureLod(normalTexture, texCoord, 0).rg));
@@ -110,7 +114,7 @@ void main() {
if (depth < 1.0) {
#ifdef AUTO_EXPOSURE
- float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r;
+ float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure;
#else
float radianceLimit = uniforms.radianceLimit;
#endif
@@ -148,17 +152,19 @@ void main() {
vec2 hitPixel;
vec3 hitPoint;
- float jitter = GetInterleavedGradientNoise(vec2(pixel)) / float(uniforms.rayCount) + j / float(uniforms.rayCount);
- if (traceScreenSpaceAdvanced(viewRayOrigin, viewDir, depthTexture, 4.0, 16.0, jitter, 64.0, 1000.0, false, false, hitPixel, hitPoint)) {
+ if (traceScreenSpaceHiZ(viewRayOrigin, viewDir, hiZTexture, uniforms.hiZLevelCount, vec2(textureSize(depthTexture, 0)),
+ 32, rayLength, false, hitPixel, hitPoint)) {
vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(depthTexture, 0));
vec3 stepViewNorm = normalize(DecodeNormal(texelFetch(normalTexture, ivec2(hitPixel), 0).rg));
float depth = texelFetch(depthTexture, ivec2(hitPixel), 0).r;
hitPoint = ConvertDepthToViewSpace(depth, hitTexCoord);
float NdotV = saturate(dot(-viewDir, stepViewNorm));
- NdotL = saturate(dot(viewNorm, hitPoint));
if (NdotV > 0.0) {
- irradiance += textureLod(directLightTexture, hitTexCoord, 0).rgb;
+ vec3 radiance = textureLod(directLightTexture, hitTexCoord, 0).rgb;
+ float radianceMax = max(max(max(radiance.r,
+ max(radiance.g, radiance.b)), radianceLimit), 1e-12);
+ irradiance += radiance * (radianceLimit / radianceMax);
}
else {
aoHits += 1.0;
@@ -167,10 +173,6 @@ void main() {
}
}
- float irradianceMax = max(max(max(irradiance.r,
- max(irradiance.g, irradiance.b)), radianceLimit), 1e-12);
- irradiance *= (radianceLimit / irradianceMax);
-
// Supplement misses with the probe irradiance
irradiance += float(uniforms.rayCount - hits) * probeIrradiance;
irradiance /= (float(uniforms.rayCount));
diff --git a/data/shader/ssgi/temporal.csh b/data/shader/ssgi/temporal.csh
index ad56de661..257da1d02 100644
--- a/data/shader/ssgi/temporal.csh
+++ b/data/shader/ssgi/temporal.csh
@@ -5,6 +5,7 @@
#include <../common/flatten.hsh>
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
+#include <../globals.hsh>
layout (local_size_x = 8, local_size_y = 8) in;
@@ -248,21 +249,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out float h
}
-float EdgeFadeOut(vec2 screenPos, float fadeDist) {
-
- screenPos = abs(screenPos * 2.0 - 1.0);
- vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist;
- return saturate(1.0 - max(fadeOut.x, fadeOut.y));
-
-}
-
void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
vec4 mean, std;
@@ -288,6 +281,8 @@ void main() {
vec4 history;
float historyLength;
valid = SampleHistory(pixel, historyPixel, history, historyLength);
+ // The history was stored with the pre-exposure of the last frame
+ history.rgb *= globalData.preExposure / globalData.lastPreExposure;
vec4 historyValue = history;
vec4 currentValue = texelFetch(currentTexture, pixel, 0);
@@ -299,14 +294,10 @@ void main() {
// At the edge we have invalid information we want to get rid of
historyLength = mix(min(historyLength, 8.0), historyLength, EdgeFadeOut(uv, 0.05));
- float factor = 31.0 / 32.0;
- factor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0
- || uv.y > 1.0) ? 0.0 : factor;
-
- factor = pushConstants.resetHistory > 0 ? 0.0 : factor;
- factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y)));
+ float factor = max(0.75, 31.0 / 32.0 - 20.0 * max(abs(velocity.x), abs(velocity.y)));
- if (factor == 0.0 || !valid) {
+ bool offscreen = uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0;
+ if (offscreen || pushConstants.resetHistory > 0 || !valid) {
historyLength = 0.0;
}
diff --git a/data/shader/taa.csh b/data/shader/taa.csh
index 202985be9..e572f285d 100644
--- a/data/shader/taa.csh
+++ b/data/shader/taa.csh
@@ -2,6 +2,7 @@
#include
#include
#include
+#include
layout (local_size_x = 8, local_size_y = 8) in;
@@ -13,9 +14,8 @@ layout(set = 3, binding = 3) uniform sampler2D velocityTexture;
layout(set = 3, binding = 4) uniform sampler2D depthTexture;
layout(set = 3, binding = 5) uniform sampler2D lastVelocityTexture;
-#ifndef PATHTRACE
layout(set = 3, binding = 6) uniform usampler2D stencilTexture;
-#endif
+layout(set = 3, binding = 7) uniform usampler2D lastStencilTexture;
layout(push_constant) uniform constants {
vec2 resolution;
@@ -33,10 +33,6 @@ const float maxVelocityBlend = 0.2;
#define TAA_CLIP
//#define TAA_DENOISE
-#ifdef PATHTRACE
-#define TAA_CLIP
-#endif
-
const ivec2 offsets[9] = ivec2[9](
ivec2(-1, -1),
ivec2(0, -1),
@@ -243,6 +239,8 @@ vec4 SampleHistory(vec2 texCoord) {
#else
historyColor = texture(historyTexture, texCoord);
#endif
+ // The history was stored with the pre-exposure of the last frame
+ historyColor.rgb *= globalData.preExposure / globalData.lastPreExposure;
#ifdef TAA_TONE
historyColor.rgb = Tonemap(historyColor.rgb);
@@ -313,8 +311,8 @@ void main() {
LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
LoadLocalData();
@@ -357,6 +355,19 @@ void main() {
vec2 uv = (vec2(pixel) + vec2(0.5)) * PushConstants.invResolution + velocity;
+ StencilFeatures features = DecodeStencilFeatures(texelFetch(stencilTexture, pixel, 0).r);
+ bool rejectHistory = features.noTemporalAccumulation;
+ if (PushConstants.resetHistory == 0) {
+ ivec2 historyPixel = clamp(ivec2(uv * PushConstants.resolution), ivec2(0), ivec2(PushConstants.resolution) - 1);
+ StencilFeatures historyFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, historyPixel, 0).r);
+ StencilFeatures previousFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, pixel, 0).r);
+ rejectHistory = rejectHistory || historyFeatures.noTemporalAccumulation || previousFeatures.noTemporalAccumulation;
+ }
+ if (rejectHistory) {
+ imageStore(resolveImage, pixel, vec4(texelFetch(currentTexture, pixel, 0).rgb, 0.0));
+ return;
+ }
+
// Maybe we might want to filter the current input pixel
vec4 history = SampleHistory(uv);
@@ -370,12 +381,10 @@ void main() {
float range = 1.4;
float localAntiFlicker = mix(0.6, 5.0, 1.0 - velocityBlend);
-#ifndef PATHTRACE
#ifdef TAA_DENOISE
range += localAntiFlicker;
#else
range += mix(0.0, localAntiFlicker, historyContrast);
-#endif
#endif
localNeighbourhoodMin = average - range * (average - localNeighbourhoodMin);
@@ -391,11 +400,7 @@ void main() {
historyColor = clamp(historyColor, localNeighbourhoodMin, localNeighbourhoodMax);
#endif
-#ifndef PATHTRACE
float blendFactor = mix(minVelocityBlend, maxVelocityBlend, velocityBlend);
-#else
- float blendFactor = mix(minVelocityBlend, maxVelocityBlend, velocityBlend);
-#endif
#ifdef TAA_YCOCG
historyColor = YCoCgToRGB(historyColor);
@@ -407,10 +412,7 @@ void main() {
currentColor.rgb = InverseTonemap(currentColor.rgb);
#endif
-#ifndef PATHTRACE
- StencilFeatures features = DecodeStencilFeatures(texelFetch(stencilTexture, pixel, 0).r);
blendFactor = features.responsivePixel ? 0.5 : blendFactor;
-#endif
// Check if we sampled outside the viewport area
blendFactor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0
diff --git a/data/shader/terrain/shadowmapping.fsh b/data/shader/terrain/shadowmapping.fsh
deleted file mode 100644
index 48f3365be..000000000
--- a/data/shader/terrain/shadowmapping.fsh
+++ /dev/null
@@ -1,5 +0,0 @@
-void main() {
-
-
-
-}
\ No newline at end of file
diff --git a/data/shader/terrain/shadowmapping.vsh b/data/shader/terrain/shadowmapping.vsh
index ff316028a..14f33db4b 100644
--- a/data/shader/terrain/shadowmapping.vsh
+++ b/data/shader/terrain/shadowmapping.vsh
@@ -2,6 +2,8 @@ layout (location = 0) in vec3 vPosition;
layout (set = 3, binding = 0) uniform usampler2D heightField;
+out float gl_ClipDistance[1];
+
layout(push_constant) uniform constants {
mat4 lightSpaceMatrix;
vec4 translation;
@@ -56,14 +58,13 @@ void main() {
vec2 texCoords = localPosition;
texCoords /= PushConstants.nodeSideLength;
- float heightDiscretized = texture(heightField, texCoords).r;
- // The middle of the texel should match the vertex position
- float height = float(heightDiscretized) / 65535.0 * PushConstants.heightScale;
+ uint heightDiscretized = texture(heightField, texCoords).r;
+ // The middle of the texel should match the vertex position, 65535 marks holes
+ float height = float(heightDiscretized) / 65534.0 * PushConstants.heightScale;
gl_Position = PushConstants.lightSpaceMatrix * vec4(vec3(position.x, height, position.y) + PushConstants.translation.xyz, 1.0);
- if (heightDiscretized == 65535u) {
- gl_Position = vec4(0.0, 0.0, 0.0, intBitsToFloat(int(0xFFC00000u)));
- }
+ // The triangles around holes are clipped, see terrain.vsh
+ gl_ClipDistance[0] = heightDiscretized == 65535u ? -1e20 : 1.0;
}
\ No newline at end of file
diff --git a/data/shader/terrain/terrain.fsh b/data/shader/terrain/terrain.fsh
index 1697f13bd..9ffc0c976 100644
--- a/data/shader/terrain/terrain.fsh
+++ b/data/shader/terrain/terrain.fsh
@@ -16,10 +16,6 @@ layout (location = 6) out vec2 velocityFS;
layout (set = 3, binding = 1) uniform sampler2D normalMap;
layout (set = 3, binding = 2) uniform usampler2D splatMap;
-layout (set = 3, binding = 3) uniform sampler2DArray baseColorMaps;
-layout (set = 3, binding = 4) uniform sampler2DArray roughnessMaps;
-layout (set = 3, binding = 5) uniform sampler2DArray aoMaps;
-layout (set = 3, binding = 6) uniform sampler2DArray normalMaps;
layout (set = 3, binding = 10) uniform sampler2D noiseMap;
@@ -64,19 +60,18 @@ vec3 hueShift(vec3 color, float hue) {
return vec3(color * cosAngle + cross(k, color) * sin(hue) + k * dot(k, color) * (1.0 - cosAngle));
}
-vec4 sampleTexture(sampler2DArray texArray, vec2 coords, vec2 origCoords, uint index) {
+vec4 SampleTexture(uint textureIdx, vec2 coords, vec2 ddx, vec2 ddy) {
- float lod = textureQueryLod(texArray, origCoords).x;
- return textureLod(texArray, vec3(coords, nonuniformEXT(float(index))), lod + globalData.mipLodBias);
+ return textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coords, ddx, ddy);
}
-vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) {
+vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) {
- vec3 q00 = nonuniformEXT(sampleTexture(baseColorMaps, coords * tiling.x, origCoords * tiling.x, indices.x).rgb);
- vec3 q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(baseColorMaps, coords * tiling.y, origCoords * tiling.y, indices.y).rgb : q00);
- vec3 q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(baseColorMaps, coords * tiling.z, origCoords * tiling.z, indices.z).rgb : q00);
- vec3 q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(baseColorMaps, coords * tiling.w, origCoords * tiling.w, indices.w).rgb : q00);
+ vec3 q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].baseColorTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).rgb;
+ vec3 q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].baseColorTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).rgb : q00;
+ vec3 q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].baseColorTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).rgb : q00;
+ vec3 q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].baseColorTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).rgb : q00;
// Interpolate samples horizontally
vec3 h0 = mix(q00, q10, off.x);
@@ -87,12 +82,12 @@ vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ori
}
-float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) {
+float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) {
- float q00 = nonuniformEXT(sampleTexture(roughnessMaps, coords * tiling.x, origCoords * tiling.x, indices.x).r);
- float q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(roughnessMaps, coords * tiling.y, origCoords * tiling.y, indices.y).r : q00);
- float q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(roughnessMaps, coords * tiling.z, origCoords * tiling.z, indices.z).r : q00);
- float q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(roughnessMaps, coords * tiling.w, origCoords * tiling.w, indices.w).r : q00);
+ float q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].roughnessTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).r;
+ float q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].roughnessTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).r : q00;
+ float q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].roughnessTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).r : q00;
+ float q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].roughnessTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).r : q00;
// Interpolate samples horizontally
float h0 = mix(q00, q10, off.x);
@@ -103,12 +98,12 @@ float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 or
}
-float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) {
+float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) {
- float q00 = nonuniformEXT(sampleTexture(aoMaps, coords * tiling.x, origCoords * tiling.x, indices.x).r);
- float q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(aoMaps, coords * tiling.y, origCoords * tiling.y, indices.y).r : q00);
- float q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(aoMaps, coords * tiling.z, origCoords * tiling.z, indices.z).r : q00);
- float q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(aoMaps, coords * tiling.w, origCoords * tiling.w, indices.w).r : q00);
+ float q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].aoTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).r;
+ float q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].aoTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).r : q00;
+ float q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].aoTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).r : q00;
+ float q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].aoTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).r : q00;
// Interpolate samples horizontally
float h0 = mix(q00, q10, off.x);
@@ -119,12 +114,12 @@ float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoord
}
-vec3 SampleNormal(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) {
+vec3 SampleNormal(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) {
- vec3 q00 = nonuniformEXT(sampleTexture(normalMaps, coords * tiling.x, origCoords * tiling.x, indices.x).rgb);
- vec3 q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(normalMaps, coords * tiling.y, origCoords * tiling.y, indices.y).rgb : q00);
- vec3 q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(normalMaps, coords * tiling.z, origCoords * tiling.z, indices.z).rgb : q00);
- vec3 q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(normalMaps, coords * tiling.w, origCoords * tiling.w, indices.w).rgb : q00);
+ vec3 q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].normalTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).rgb;
+ vec3 q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].normalTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).rgb : q00;
+ vec3 q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].normalTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).rgb : q00;
+ vec3 q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].normalTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).rgb : q00;
// Interpolate samples horizontally
vec3 h0 = mix(q00, q10, off.x);
@@ -192,7 +187,11 @@ void main() {
vec2 flooredCoords = floor(position + vec2(noiseX, noiseY));
float rand = random(flooredCoords);
vec2 rotTexCoords = rotateUV(position, rand);
- //rotTexCoords = materialTexCoords;
+
+ // Gradients of the rotated coordinates without the jumps between the randomly rotated cells
+ float gradientScale = exp2(globalData.mipLodBias);
+ vec2 ddx = rotateUV(dFdx(materialTexCoords) * gradientScale + vec2(0.5), rand) - vec2(0.5);
+ vec2 ddy = rotateUV(dFdy(materialTexCoords) * gradientScale + vec2(0.5), rand) - vec2(0.5);
vec4 tiling = vec4(
Materials.materials[nonuniformEXT(indices.x)].tiling,
@@ -209,7 +208,7 @@ void main() {
off
);
- baseColorFS *= SampleBaseColor(off, indices, tiling, rotTexCoords, materialTexCoords);
+ baseColorFS *= SampleBaseColor(off, indices, tiling, rotTexCoords, ddx, ddy);
baseColorFS = hueShift(baseColorFS, noiseZ - 0.5);
baseColorFS = baseColorFS * (noiseW * 0.5 + 0.5);
@@ -256,7 +255,7 @@ void main() {
Materials.materials[nonuniformEXT(indices.w)].normalScale,
off
);
- vec3 normal = SampleNormal(off, indices, tiling, rotTexCoords, materialTexCoords);
+ vec3 normal = SampleNormal(off, indices, tiling, rotTexCoords, ddx, ddy);
vec3 tang = vec3(1.0, 0.0, 0.0);
tang.y = -((norm.x*tang.x) / norm.y) - ((norm.z*tang.z) / norm.y);
tang = normalize(tang);
@@ -264,8 +263,8 @@ void main() {
mat3 tbn = mat3(tang, bitang, norm);
normal = normalize(tbn * (2.0 * normal - 1.0));
normal = mix(norm, normal, normalScale);
- //ao *= SampleAo(off, indices, tiling, rotTexCoords, materialTexCoords);
- //roughness *= SampleRoughness(off, indices, tiling, rotTexCoords, materialTexCoords);
+ //ao *= SampleAo(off, indices, tiling, rotTexCoords, ddx, ddy);
+ //roughness *= SampleRoughness(off, indices, tiling, rotTexCoords, ddx, ddy);
#else
vec3 normal = norm;
#endif
diff --git a/data/shader/terrain/terrain.tcsh b/data/shader/terrain/terrain.tcsh
index 6dedb4ad7..3beda76b1 100644
--- a/data/shader/terrain/terrain.tcsh
+++ b/data/shader/terrain/terrain.tcsh
@@ -85,7 +85,7 @@ void main() {
maxVec += dir;
minVec -= dir;
- if (IsTileVisible(minVec, maxVec)) {
+ if (!hole && IsTileVisible(minVec, maxVec)) {
#ifndef DISTANCE
vec3 midAB = vec3(gl_in[0].gl_Position + gl_in[1].gl_Position) / 2.0;
diff --git a/data/shader/terrain/terrain.tesh b/data/shader/terrain/terrain.tesh
index 584487215..b8df018de 100644
--- a/data/shader/terrain/terrain.tesh
+++ b/data/shader/terrain/terrain.tesh
@@ -10,7 +10,6 @@ layout(quads, equal_spacing, cw) in;
layout (set = 3, binding = 1) uniform sampler2D normalMap;
layout (set = 3, binding = 2) uniform usampler2D splatMap;
-layout (set = 3, binding = 7) uniform sampler2DArray displacementMaps;
layout (set = 3, binding = 10) uniform sampler2D noiseMap;
layout (set = 3, binding = 8, std140) uniform UBO {
@@ -49,6 +48,12 @@ layout(location=1) out vec2 texCoords;
layout(location=2) out vec3 ndcCurrent;
layout(location=3) out vec3 ndcLast;
+float SampleDisplacementTexture(uint textureIdx, vec2 coords) {
+
+ return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coords, 0.0).r;
+
+}
+
float SampleDisplacement(vec2 off, vec2 coords, uvec4 indices) {
vec2 position = materialTexCoords + PushConstants.nodeLocation;
@@ -63,12 +68,12 @@ float SampleDisplacement(vec2 off, vec2 coords, uvec4 indices) {
if (indices.x == indices.y &&
indices.x == indices.z &&
indices.x == indices.w)
- return texture(displacementMaps, vec3(rotTexCoords, float(indices.x))).r;
+ return SampleDisplacementTexture(Materials.materials[indices.x].displacementTextureIdx, rotTexCoords);
- float q00 = texture(displacementMaps, vec3(rotTexCoords, float(indices.x))).r;
- float q10 = texture(displacementMaps, vec3(rotTexCoords, float(indices.y))).r;
- float q01 = texture(displacementMaps, vec3(rotTexCoords, float(indices.z))).r;
- float q11 = texture(displacementMaps, vec3(rotTexCoords, float(indices.w))).r;
+ float q00 = SampleDisplacementTexture(Materials.materials[indices.x].displacementTextureIdx, rotTexCoords);
+ float q10 = SampleDisplacementTexture(Materials.materials[indices.y].displacementTextureIdx, rotTexCoords);
+ float q01 = SampleDisplacementTexture(Materials.materials[indices.z].displacementTextureIdx, rotTexCoords);
+ float q11 = SampleDisplacementTexture(Materials.materials[indices.w].displacementTextureIdx, rotTexCoords);
// Interpolate samples horizontally
float h0 = mix(q00, q10, off.x);
@@ -95,9 +100,6 @@ void main(){
float u = gl_TessCoord.x;
float v = gl_TessCoord.y;
- bool hole = gl_in[3].gl_Position.w < 0.0 || gl_in[2].gl_Position.w < 0.0 ||
- gl_in[1].gl_Position.w < 0.0 || gl_in[0].gl_Position.w < 0.0;
-
// world position
vec4 position =
((1.0 - u) * (1.0 - v) * gl_in[3].gl_Position +
@@ -138,7 +140,8 @@ void main(){
Materials.materials[indices.w].displacementScale,
off
);
- float displacement = SampleDisplacement(off, materialTexCoords, indices)
+ // Around the surface instead of above it, so objects placed on the physical ground don't look sunk in
+ float displacement = (SampleDisplacement(off, materialTexCoords, indices) - 0.5)
* displacementScale * weight;
position.xyz += norm * displacement;
@@ -151,10 +154,5 @@ void main(){
vec4 last = globalData.pvMatrixLast * position;
ndcLast = vec3(last.xy, last.w);
-
- if (hole) {
- gl_Position = vec4(0.0, 0.0, 0.0, -1.0);
- ndcLast = ndcCurrent;
- }
}
\ No newline at end of file
diff --git a/data/shader/terrain/terrain.vsh b/data/shader/terrain/terrain.vsh
index 42b3be624..d484e3020 100644
--- a/data/shader/terrain/terrain.vsh
+++ b/data/shader/terrain/terrain.vsh
@@ -10,6 +10,7 @@ layout(set = 3, binding = 0) uniform usampler2D heightField;
layout(set = 3, binding = 2) uniform usampler2D splatMap;
#ifdef DISTANCE
+out float gl_ClipDistance[1];
layout(location=0) out vec2 materialTexCoords;
layout(location=1) out vec2 texCoords;
layout(location=2) out vec3 ndcCurrent;
@@ -108,12 +109,14 @@ void main() {
ndcLast = vec3(last.xy, last.w);
#endif
- // Produce NaNs here
- if (heightDiscretized == 65535u) {
- gl_Position = vec4(0.0, 0.0, 0.0, intBitsToFloat(int(0xFFC00000u)));
-#ifdef DISTANCE
- ndcLast = ndcCurrent;
+ // Holes leave out the patches around the vertex, the control shader culls them. Without tessellation the
+ // triangles around it are clipped, the large distance leaves at most sub-pixel slivers of them
+ bool hole = heightDiscretized == 65535u;
+#ifndef DISTANCE
+ if (hole)
+ gl_Position.w = -1.0;
+#else
+ gl_ClipDistance[0] = hole ? -1e20 : 1.0;
#endif
- }
}
\ No newline at end of file
diff --git a/data/shader/terrain/terrainMaterial.hsh b/data/shader/terrain/terrainMaterial.hsh
index a76204fc9..28a079510 100644
--- a/data/shader/terrain/terrainMaterial.hsh
+++ b/data/shader/terrain/terrainMaterial.hsh
@@ -17,7 +17,11 @@ struct TerrainMaterial {
float tiling;
- int padding;
+ uint baseColorTextureIdx;
+ uint roughnessTextureIdx;
+ uint aoTextureIdx;
+ uint normalTextureIdx;
+ uint displacementTextureIdx;
};
diff --git a/data/shader/text.fsh b/data/shader/text.fsh
index 8629d60b0..b66f4e4d5 100644
--- a/data/shader/text.fsh
+++ b/data/shader/text.fsh
@@ -1,9 +1,11 @@
#include
+#include
layout (location=0) out vec4 colorFS;
#ifdef TEXT_3D
layout (location=1) out vec2 velocityFS;
+layout (location=2) out uint stencilFS;
#endif
layout(location=0) in vec3 texCoordVS;
@@ -72,11 +74,15 @@ void main() {
if (colorFS.a < 0.5)
discard;
+ StencilFeatures features = CreateStencilFeatures();
+ features.noTemporalAccumulation = true;
+ stencilFS = EncodeStencilFeatures(features);
+
vec2 ndcL = ndcLastVS.xy / ndcLastVS.z;
vec2 ndcC = ndcCurrentVS.xy / ndcCurrentVS.z;
+ // The current position is unjittered already (see text.vsh), the last one used the jittered matrix
ndcL -= globalData.jitterLast;
- ndcC -= globalData.jitterCurrent;
velocityFS = (ndcL - ndcC) * 0.5;
#endif
diff --git a/data/shader/text.vsh b/data/shader/text.vsh
index ec84c473f..06059b40d 100644
--- a/data/shader/text.vsh
+++ b/data/shader/text.vsh
@@ -83,7 +83,8 @@ void main() {
vec3 worldPosition = right * screenPositionVS.x + down * screenPositionVS.y;
worldPosition = worldPosition + pushConstants.position.xyz - right * halfSize.x - down * halfSize.y;
- gl_Position = globalData.pMatrix * globalData.vMatrix * vec4(worldPosition, 1.0);
+ // Text isn't accumulated temporally (see text.fsh), the jitter would only make it shake
+ gl_Position = globalData.pMatrixUnjitterd * globalData.vMatrix * vec4(worldPosition, 1.0);
ndcCurrentVS = vec3(gl_Position.xy, gl_Position.w);
// For moving objects we need the last frames matrix
diff --git a/data/shader/translucent/translucent.hsh b/data/shader/translucent/translucent.hsh
new file mode 100644
index 000000000..ab59cb1a5
--- /dev/null
+++ b/data/shader/translucent/translucent.hsh
@@ -0,0 +1,369 @@
+// Forward shading of translucent surfaces, included by the geometry fragment shader with TRANSLUCENT. One blend mode
+// macro is set: BLEND_ALPHA (premultiplied), BLEND_ADDITIVE or BLEND_MULTIPLY
+
+#define SHADOW_FILTER_VOGEL
+
+#include <../deferred/deferred.hsh>
+#include <../structures.hsh>
+#include <../shadow.hsh>
+#include <../common/light.hsh>
+#include <../brdf/brdfEval.hsh>
+#include <../clouds/shadow.hsh>
+#include <../volumetric/froxelSlices.hsh>
+
+#ifdef DDGI
+#include <../ddgi/ddgi.hsh>
+#endif
+
+layout(set = 3, binding = 11) uniform sampler shadowSampler;
+#ifdef CLOUD_SHADOWS
+layout(set = 3, binding = 12) uniform sampler2D cloudMap;
+#endif
+
+#include <../deferred/directLight.hsh>
+
+// Light tiles which reach from the near plane to the opaque surfaces, with the buckets of deferred/lightCulling.hsh
+const int lightBucketCount = 128;
+
+layout(std430, set = 3, binding = 13) readonly buffer TranslucentLightBuckets {
+ int lightBuckets[];
+};
+
+layout(set = 3, binding = 14) uniform sampler2D refractionTexture;
+layout(set = 3, binding = 15) uniform sampler2D refractionDepthTexture;
+// The closest back faces of refracting surfaces with their normals pointing out of them
+layout(set = 3, binding = 20) uniform sampler2D refractionBackDepthTexture;
+layout(set = 3, binding = 21) uniform sampler2D refractionBackNormalTexture;
+#ifdef REFLECTION
+// Traced from the closest alpha blended surface, see the front layer of the translucent renderer
+layout(set = 3, binding = 16) uniform sampler2D reflectionTexture;
+layout(set = 3, binding = 17) uniform sampler2D reflectionDepthTexture;
+#endif
+#ifdef FOG
+layout(set = 3, binding = 18) uniform sampler3D integratedFroxelTexture;
+#endif
+
+layout(std140, set = 3, binding = 19) uniform TranslucentUniformBuffer {
+ vec2 resolution;
+ // Maps the unjittered screen coordinates to the froxel columns
+ vec2 froxelGridScale;
+ int lightBucketCount;
+ int lightTileCountX;
+ int specularProbeMipLevels;
+ int refractionMipLevels;
+ float froxelNear;
+ float froxelFar;
+ float froxelExtendedFar;
+ int froxelSliceCount;
+ float froxelDistributionExponent;
+} translucentUniforms;
+
+vec3 GetTranslucentDirectLight(Surface surface, vec3 geometryNormal, ivec2 pixel, vec2 texCoord) {
+
+ ivec2 tile = pixel / ivec2(16);
+ int bucketOffset = (tile.x + tile.y * translucentUniforms.lightTileCountX) * lightBucketCount;
+
+ vec3 direct = vec3(0.0);
+ for (int i = 0; i < translucentUniforms.lightBucketCount; i++) {
+ uint lightBucket = uint(lightBuckets[bucketOffset + i]);
+ if (lightBucket == 0u)
+ continue;
+
+ uint bucketBitCount = findMSB(lightBucket) + 1u;
+ for (uint j = 0u; j < bucketBitCount; j++) {
+ if ((lightBucket & (1u << j)) == 0u)
+ continue;
+
+ uint lightIdx = uint(i) * 32u + j;
+ direct += EvaluateLight(lights[lightIdx], surface, geometryNormal, lightIdx == 0u, pixel, texCoord);
+ }
+ }
+ return direct;
+
+}
+
+vec3 GetTranslucentIndirectDiffuse(Surface surface, vec3 geometryNormal) {
+
+ vec3 worldView = -normalize(vec3(globalData.ivMatrix * vec4(surface.P, 0.0)));
+ vec3 worldPosition = vec3(globalData.ivMatrix * vec4(surface.P, 1.0));
+ vec3 worldNormal = normalize(vec3(globalData.ivMatrix * vec4(surface.N, 0.0)));
+ vec3 geometryWorldNormal = normalize(vec3(globalData.ivMatrix * vec4(geometryNormal, 0.0)));
+
+ vec3 prefilteredDiffuse = textureLod(diffuseProbe, worldNormal, 0).rgb;
+#ifdef DDGI
+#ifdef DDGI_SCROLL
+ vec4 prefilteredDiffuseLocal = ddgiData.volumeEnabled > 0 ?
+ GetLocalIrradiance(worldPosition, worldView, worldNormal, geometryWorldNormal, prefilteredDiffuse) : vec4(0.0, 0.0, 0.0, 1.0);
+#else
+ vec4 prefilteredDiffuseLocal = ddgiData.volumeEnabled > 0 ?
+ GetLocalIrradiance(worldPosition, worldView, worldNormal, geometryWorldNormal) : vec4(0.0, 0.0, 0.0, 1.0);
+#endif
+ prefilteredDiffuseLocal = IsInsideVolume(worldPosition) ? prefilteredDiffuseLocal : vec4(0.0, 0.0, 0.0, 1.0);
+ prefilteredDiffuse = (prefilteredDiffuseLocal.rgb + prefilteredDiffuse * prefilteredDiffuseLocal.a) * ddgiData.volumeStrength;
+#endif
+ return prefilteredDiffuse * EvaluateIndirectDiffuseBRDF(surface) * surface.material.ao;
+
+}
+
+vec3 GetTranslucentIndirectSpecular(Surface surface, vec2 texCoord) {
+
+ vec3 R = normalize(mat3(globalData.ivMatrix) * reflect(-surface.V, surface.N));
+ float mipLevel = surface.material.roughness * float(translucentUniforms.specularProbeMipLevels - 1);
+ vec3 indirectSpecular = textureLod(specularProbe, R, mipLevel).rgb;
+
+#ifdef REFLECTION
+ // Only the closest alpha blended surface has traced reflections, the ones behind it use the probe
+ float reflectionDepth = textureLod(reflectionDepthTexture, texCoord, 0.0).r;
+ float reflectionViewDepth = ConvertDepthToViewSpace(reflectionDepth, texCoord).z;
+ if (abs(reflectionViewDepth - surface.P.z) < 0.01 * abs(surface.P.z))
+ indirectSpecular = textureLod(reflectionTexture, texCoord, 0.0).rgb;
+#endif
+
+ return indirectSpecular * EvaluateIndirectSpecularBRDF(surface) * surface.material.ao;
+
+}
+
+// The in-scattered light (rgb) and transmittance (a) between the camera and the surface
+vec4 GetTranslucentFog(vec3 viewPosition, vec2 texCoord) {
+
+#ifdef FOG
+ FroxelSlices slices = FroxelSlices(translucentUniforms.froxelNear, translucentUniforms.froxelFar,
+ translucentUniforms.froxelExtendedFar, translucentUniforms.froxelSliceCount, translucentUniforms.froxelDistributionExponent);
+
+ // Each slice stores the integral up to its far end, inside the first slice it is interpolated from the camera
+ float slice = GetFroxelSlice(slices, -viewPosition.z);
+ vec2 unjitteredTexCoord = texCoord - 0.5 * globalData.jitterCurrent;
+ vec2 gridTexCoord = unjitteredTexCoord * translucentUniforms.froxelGridScale;
+ float sliceTexCoord = (max(slice - 1.0, 0.0) + 0.5) / float(translucentUniforms.froxelSliceCount);
+ vec4 integrated = textureLod(integratedFroxelTexture, vec3(gridTexCoord, sliceTexCoord), 0.0);
+ return mix(vec4(0.0, 0.0, 0.0, 1.0), integrated, clamp(slice, 0.0, 1.0));
+#else
+ return vec4(0.0, 0.0, 0.0, 1.0);
+#endif
+
+}
+
+vec2 ProjectToTexCoord(vec3 viewPosition) {
+
+ vec4 projected = globalData.pMatrix * vec4(viewPosition, 1.0);
+ return projected.xy / projected.w * 0.5 + 0.5;
+
+}
+
+bool IsOnScreen(vec2 texCoord) {
+
+ return all(greaterThanEqual(texCoord, vec2(0.0))) && all(lessThanEqual(texCoord, vec2(1.0)));
+
+}
+
+// Results of TraceBackground: the ray hit the background, left the screen or the distance without a hit (the image goes on
+// there like at its edge), was lost behind the camera, or ran behind a surface in front of the refracting one, which
+// hides the background there
+const int traceHit = 0;
+const int traceLeft = 1;
+const int traceLost = 2;
+const int traceOccluded = 3;
+
+// Marches the ray through the depth of the background copy with steps growing with the distance. The texture coordinate
+// is where the ray hit or left the screen, or where it ended. Surfaces closer than the refracting one at surfaceDepth
+// (view space) are in front of it, the ray is never behind them
+int TraceBackground(vec3 origin, vec3 direction, float maxDistance, float surfaceDepth, out vec2 hitTexCoord) {
+
+ const int stepCount = 24;
+ hitTexCoord = ProjectToTexCoord(origin);
+ float lastDistance = 0.0;
+ for (int i = 1; i <= stepCount; i++) {
+ float distance = maxDistance * sqr(float(i) / float(stepCount));
+ vec3 position = origin + direction * distance;
+ if (position.z >= 0.0)
+ return traceLost;
+
+ vec2 texCoord = ProjectToTexCoord(position);
+ if (!IsOnScreen(texCoord)) {
+ // Where the ray crosses the edge of the screen, the neighbors which still hit continue there
+ float near = lastDistance, far = distance;
+ for (int j = 0; j < 5; j++) {
+ float middle = 0.5 * (near + far);
+ vec2 middleTexCoord = ProjectToTexCoord(origin + direction * middle);
+ if (IsOnScreen(middleTexCoord)) {
+ near = middle;
+ hitTexCoord = middleTexCoord;
+ }
+ else {
+ far = middle;
+ }
+ }
+ return traceLeft;
+ }
+
+ float backgroundViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, texCoord, 0.0).r);
+ if (backgroundViewDepth > surfaceDepth)
+ return traceOccluded;
+
+ hitTexCoord = texCoord;
+ if (backgroundViewDepth > position.z) {
+ // Refine between the last two steps. Surfaces are taken as thick, a ray which passes behind one ends on it, what
+ // it would hit behind isn't on the screen
+ float near = lastDistance, far = distance;
+ for (int j = 0; j < 4; j++) {
+ float middle = 0.5 * (near + far);
+ vec3 middlePosition = origin + direction * middle;
+ vec2 middleTexCoord = ProjectToTexCoord(middlePosition);
+ float middleViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, middleTexCoord, 0.0).r);
+ if (middleViewDepth > middlePosition.z && middleViewDepth <= surfaceDepth) {
+ far = middle;
+ hitTexCoord = middleTexCoord;
+ }
+ else {
+ near = middle;
+ }
+ }
+ return traceHit;
+ }
+ lastDistance = distance;
+ }
+
+ return traceLeft;
+
+}
+
+// The angle of the cone rough surfaces scatter refracted rays into. A microfacet tilted by an angle only turns the ray by
+// the fraction 1 - 1 / n of it, at both sides of the surface
+float GetRefractionSpread(float roughness, float refractiveIndex) {
+
+ return 2.0 * sqr(roughness) * abs(1.0 - 1.0 / refractiveIndex);
+
+}
+
+// The mip of the background which blurs it like the cone of the refracted rays where they hit it, far from the surface
+// the blur is larger
+float GetRefractionMipLevel(float spread, vec3 surfacePosition, vec2 hitTexCoord) {
+
+ vec3 hitPosition = ConvertDepthToViewSpace(textureLod(refractionDepthTexture, hitTexCoord, 0.0).r, hitTexCoord);
+ float radius = spread * distance(hitPosition, surfacePosition);
+ float pixels = radius * abs(globalData.pMatrix[1][1]) * float(textureSize(refractionTexture, 0).y) / max(-hitPosition.z, 0.001);
+ return clamp(log2(max(pixels, 1.0)), 0.0, float(translucentUniforms.refractionMipLevels - 1));
+
+}
+
+// The background seen through the surface. With SCREEN_SPACE_REFRACTION the ray is refracted where it enters, leaves
+// closed surfaces through their back faces and open ones after the thickness, where it's refracted again. Otherwise the
+// background is only displaced by the normal like behind thin glass. Rough surfaces blur the background
+vec3 GetRefractedBackground(Surface surface, vec2 texCoord, float refractiveIndex, float thickness) {
+
+ // Toward the edges of the screen the refraction fades out, the background behind the surface continues to the edge
+ refractiveIndex = mix(1.0, refractiveIndex, EdgeFadeOut(texCoord, 0.1));
+ float spread = GetRefractionSpread(surface.material.roughness, refractiveIndex);
+#ifdef SCREEN_SPACE_REFRACTION
+ vec3 incident = normalize(surface.P);
+ vec3 normal = dot(surface.N, incident) < 0.0 ? surface.N : -surface.N;
+ vec3 inside = refract(incident, normal, 1.0 / refractiveIndex);
+
+ vec3 exitPosition = surface.P + inside * thickness;
+ vec3 exitDirection = refract(inside, normal, refractiveIndex);
+ float backDepth = textureLod(refractionBackDepthTexture, texCoord, 0.0).r;
+ float backViewDepth = ConvertDepthToViewSpaceDepth(backDepth);
+ bool closed = backDepth < 1.0 && backViewDepth < surface.P.z;
+ if (closed) {
+ // The distance to the back face along the refracted ray, found in a few fixed point steps
+ float distance = length(ConvertDepthToViewSpace(backDepth, texCoord) - surface.P);
+ vec2 exitTexCoord = texCoord;
+ for (int i = 0; i < 3; i++) {
+ vec2 stepTexCoord = ProjectToTexCoord(surface.P + inside * distance);
+ float stepDepth = IsOnScreen(stepTexCoord) ? textureLod(refractionBackDepthTexture, stepTexCoord, 0.0).r : 1.0;
+ if (stepDepth >= 1.0)
+ break;
+ exitTexCoord = stepTexCoord;
+ distance = length(ConvertDepthToViewSpace(stepDepth, stepTexCoord) - surface.P);
+ }
+
+ vec3 backNormal = DecodeNormal(textureLod(refractionBackNormalTexture, exitTexCoord, 0.0).rg);
+ exitPosition = surface.P + inside * distance;
+ exitDirection = refract(inside, -backNormal, refractiveIndex);
+ // Total internal reflection keeps the ray inside, it's approximated by the reflected direction
+ if (dot(exitDirection, exitDirection) == 0.0)
+ exitDirection = reflect(inside, -backNormal);
+ }
+
+ // Open surfaces like water planes are a slab of the thickness, the background inside it is seen directly
+ vec2 backgroundTexCoord;
+ int result = closed ? traceLost : TraceBackground(surface.P, inside, thickness, surface.P.z, backgroundTexCoord);
+ if (result != traceHit && result != traceOccluded)
+ result = TraceBackground(exitPosition, exitDirection, 64.0, surface.P.z, backgroundTexCoord);
+ // Where surfaces in front of this one hide the refracted background, the one straight behind is seen
+ if (result == traceOccluded)
+ backgroundTexCoord = texCoord;
+ bool seesBackground = result != traceLost;
+
+ // Lenses magnify the background and its blur by how fast the hit moves between neighboring pixels, which is measured
+ // in the pixel quad. The smaller direction ignores jumps at the outlines of what is hit
+ vec2 hitPixel = backgroundTexCoord * translucentUniforms.resolution;
+ float magnification = clamp(min(length(dFdx(hitPixel)), length(dFdy(hitPixel))), 1.0, 16.0);
+ if (seesBackground)
+ return textureLod(refractionTexture, backgroundTexCoord,
+ GetRefractionMipLevel(spread * magnification, surface.P, backgroundTexCoord)).rgb;
+
+ // Rays behind the camera see the probe, its mips are filtered for the roughness of reflections
+ vec3 worldDirection = normalize(mat3(globalData.ivMatrix) * exitDirection);
+ float probeMipLevel = sqrt(spread) * float(translucentUniforms.specularProbeMipLevels - 1);
+ return textureLod(specularProbe, worldDirection, probeMipLevel).rgb;
+#else
+ vec3 offsetPosition = surface.P - vec3(surface.N.xy * (refractiveIndex - 1.0) * thickness, 0.0);
+ // Off screen the image goes on like at its edge
+ vec2 offsetTexCoord = clamp(ProjectToTexCoord(offsetPosition), vec2(0.0), vec2(1.0));
+ // Surfaces in front of this one stay in front, they would bleed into it
+ float backgroundViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, offsetTexCoord, 0.0).r);
+ vec2 refractedTexCoord = backgroundViewDepth < surface.P.z ? offsetTexCoord : texCoord;
+ return textureLod(refractionTexture, refractedTexCoord, GetRefractionMipLevel(spread, surface.P, refractedTexCoord)).rgb;
+#endif
+
+}
+
+// The color to blend for the material at the view space position with the opacity as coverage. The blend state of the
+// mode combines it with the background, the coverage is written for the reactive mask
+vec4 ShadeTranslucent(Material material, vec3 normal, vec3 geometryNormal, vec3 viewPosition, float opacity,
+ float refractiveIndex, float thickness, out float coverage) {
+
+ ivec2 pixel = ivec2(gl_FragCoord.xy);
+ vec2 texCoord = gl_FragCoord.xy / translucentUniforms.resolution;
+ vec4 fog = GetTranslucentFog(viewPosition, texCoord);
+
+#ifdef BLEND_MULTIPLY
+ // Darkens the background by the color, the fog in front of the surface isn't darkened
+ coverage = 1.0;
+ vec3 factor = mix(vec3(1.0), material.baseColor, opacity);
+ return vec4(mix(vec3(1.0), factor, fog.a), 1.0);
+#else
+ Surface surface = CreateSurface(normalize(-viewPosition), normal, vec3(0.0, -1.0, 0.0), material);
+ surface.P = viewPosition;
+#ifdef BLEND_ADDITIVE
+ surface.material.opacity = 1.0;
+#else
+ // The direct light weights the diffuse part by it
+ surface.material.opacity = opacity;
+#endif
+
+ vec3 direct = GetTranslucentDirectLight(surface, geometryNormal, pixel, texCoord);
+ vec3 indirectDiffuse = GetTranslucentIndirectDiffuse(surface, geometryNormal);
+ vec3 specular = GetTranslucentIndirectSpecular(surface, texCoord);
+ vec3 emissive = material.emissiveColor * globalData.preExposure;
+
+ coverage = opacity;
+#ifdef BLEND_ADDITIVE
+ // Adds light only, the fog in front of the surface is already in the background
+ vec3 color = (direct + indirectDiffuse + specular + emissive) * opacity;
+ return vec4(color * fog.a, 0.0);
+#else
+ // Reflections and emission keep their strength on clear surfaces
+ vec3 color = direct + indirectDiffuse * opacity + specular + emissive;
+ color = color * fog.a + fog.rgb * opacity;
+ if (refractiveIndex == 1.0)
+ return vec4(color, opacity);
+
+ // The refracted background replaces the one behind the surface
+ vec3 background = GetRefractedBackground(surface, texCoord, refractiveIndex, thickness);
+ return vec4(color + background * (1.0 - opacity), 1.0);
+#endif
+#endif
+
+}
diff --git a/data/shader/upsampleSpatial.csh b/data/shader/upsampleSpatial.csh
index 08e53fc29..009059e03 100644
--- a/data/shader/upsampleSpatial.csh
+++ b/data/shader/upsampleSpatial.csh
@@ -61,8 +61,8 @@ vec4 SampleCatmullRom(vec2 uv) {
void main() {
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(textureOut).x ||
- pixel.y > imageSize(textureOut).y)
+ if (pixel.x >= imageSize(textureOut).x ||
+ pixel.y >= imageSize(textureOut).y)
return;
vec2 uv = (vec2(pixel)) / vec2(imageSize(textureOut));
diff --git a/data/shader/vegetation/depth.fsh b/data/shader/vegetation/depth.fsh
deleted file mode 100644
index 7ea44cedc..000000000
--- a/data/shader/vegetation/depth.fsh
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifdef OPACITY_MAP
-layout(binding = 1) uniform sampler2D opacityMap;
-#endif
-
-in vec3 positionVS;
-in vec2 texCoordVS;
-
-void main() {
-
-#ifdef OPACITY_MAP
- float opacity = texture(opacityMap, texCoordVS).r;
- if (opacity < 0.2)
- discard;
-#endif
-
-}
\ No newline at end of file
diff --git a/data/shader/vegetation/depth.vsh b/data/shader/vegetation/depth.vsh
deleted file mode 100644
index 41a386733..000000000
--- a/data/shader/vegetation/depth.vsh
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <../wind.hsh>
-#include
-
-// Per vertex attributes
-layout(location=0) in vec3 vPosition;
-layout(location=2) in vec2 vTexCoord;
-
-// Vertex out parameters
-out vec3 positionVS;
-out vec2 texCoordVS;
-
-// Uniforms
-uniform mat4 pMatrix;
-uniform mat4 vMatrix;
-
-uniform float time;
-uniform float deltaTime;
-
-uniform bool invertUVs;
-
-// Functions
-void main() {
-
- Instance instance = instanceData[gl_InstanceID + gl_BaseInstance];
- texCoordVS = invertUVs ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord;
-
- mat4 mvMatrix = vMatrix;
-
- vec3 position = instance.position.xyz + vPosition;
- position = instance.position.xyz + WindAnimation(vPosition, time, instance.position.xyz);
-
- vec4 positionToCamera = mvMatrix * vec4(position, 1.0);
- positionVS = positionToCamera.xyz;
-
- gl_Position = pMatrix * positionToCamera;
-
-}
\ No newline at end of file
diff --git a/data/shader/vegetation/vegetation.fsh b/data/shader/vegetation/vegetation.fsh
index 94a033287..a3dc6fa10 100644
--- a/data/shader/vegetation/vegetation.fsh
+++ b/data/shader/vegetation/vegetation.fsh
@@ -1,4 +1,5 @@
#include <../globals.hsh>
+#include <../common/opacity.hsh>
#include <../common/random.hsh>
#include <../common/normalencode.hsh>
@@ -74,7 +75,7 @@ void main() {
#ifdef VERTEX_COLORS
opacity *= vertexColorsVS.a;
#endif
- if (opacity < 0.2)
+ if (opacity < opacityCutoff)
discard;
#endif
diff --git a/data/shader/volumetric/fog.hsh b/data/shader/volumetric/fog.hsh
index e7d87370d..cb65b3534 100644
--- a/data/shader/volumetric/fog.hsh
+++ b/data/shader/volumetric/fog.hsh
@@ -1,37 +1,47 @@
struct Fog {
- vec4 extinctionCoefficients;
+ vec4 albedo;
float density;
float heightFalloff;
float height;
float scatteringAnisotropy;
- float scatteringFactor;
- float extinctionFactor;
float ambientFactor;
};
-// https://developer.amd.com/wordpress/media/2012/10/Wenzel-Real-time_Atmospheric_Effects_in_Games.pdf
-float ComputeVolumetricFog(Fog fog, vec3 viewPos, vec3 worldPos) {
- viewPos.y -= fog.height;
+// The fog has one medium: the density is its extinction, constant below the fog height and falling off exponentially
+// above it. The scattering is the albedo times the extinction, the froxels and the rays to the lights use the same extinction
+
+float GetVolumetricFogDensity(Fog fog, vec3 worldPos) {
+
worldPos.y -= fog.height;
- vec3 viewToWorldPos = worldPos - viewPos;
+ return clamp(exp(-fog.heightFalloff * worldPos.y), 0.0, 1.0);
+
+}
- float fogIntegration = length(viewToWorldPos) *
- exp(-fog.heightFalloff * viewPos.y);
+// Integral of the density profile over the height relative to the fog height
+float IntegrateVolumetricFogDensity(Fog fog, float height) {
- float t = fog.heightFalloff * viewToWorldPos.y;
- if (abs(t) > 0.0001) {
- fogIntegration *= (1.0 - exp(-t)) / t;
- }
+ if (height <= 0.0 || fog.heightFalloff <= 0.0)
+ return height;
+ return (1.0 - exp(-fog.heightFalloff * height)) / fog.heightFalloff;
- return max(exp(-fog.density * fogIntegration), 0.0);
}
-float GetVolumetricFogDensity(Fog fog, vec3 worldPos) {
+// Transmittance between two points
+float ComputeVolumetricFog(Fog fog, vec3 viewPos, vec3 worldPos) {
- worldPos.y -= fog.height;
+ float startHeight = viewPos.y - fog.height;
+ float endHeight = worldPos.y - fog.height;
+ float heightDifference = endHeight - startHeight;
- return clamp(exp(-fog.heightFalloff * worldPos.y), 0.0, 1.0);
+ // The mean density along the ray, the integral over the height divided by the height difference. Below a centimeter
+ // the difference of the integrals loses its precision, the density hardly changes there
+ float meanDensity = abs(heightDifference) > 0.01 ?
+ (IntegrateVolumetricFogDensity(fog, endHeight) - IntegrateVolumetricFogDensity(fog, startHeight)) / heightDifference :
+ GetVolumetricFogDensity(fog, viewPos);
+
+ float opticalDepth = fog.density * meanDensity * distance(viewPos, worldPos);
+ return exp(-opticalDepth);
}
diff --git a/data/shader/volumetric/fogVolumes.hsh b/data/shader/volumetric/fogVolumes.hsh
new file mode 100644
index 000000000..94f3497fd
--- /dev/null
+++ b/data/shader/volumetric/fogVolumes.hsh
@@ -0,0 +1,52 @@
+#ifdef FOG_VOLUMES
+
+#define FOG_VOLUME_BOX 0
+#define FOG_VOLUME_ELLIPSOID 1
+
+struct FogVolume {
+ vec4 worldToUnit0;
+ vec4 worldToUnit1;
+ vec4 worldToUnit2;
+
+ vec4 scatteringAndDensity;
+ vec4 emissiveAndEdgeFade;
+ vec4 noiseOffsetAndFrequency;
+
+ float noiseAmount;
+ float noiseCoverage;
+ float noiseSharpness;
+ int noiseOctaves;
+
+ float heightFalloff;
+ float ambientFactor;
+ int shape;
+ float selfShadowing;
+
+ float scatteringAnisotropy;
+ float padding0;
+ float padding1;
+ float padding2;
+};
+
+layout(std430, set = 3, binding = 11) buffer FogVolumes {
+ FogVolume fogVolumes[];
+};
+
+layout(std430, set = 3, binding = 13) buffer FogVolumeMasks {
+ uint fogVolumeMasks[];
+};
+
+uint GetFogVolumeClusterIndex() {
+
+ return gl_WorkGroupID.x + (gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x;
+
+}
+
+vec3 GetFogVolumeUnitPosition(FogVolume volume, vec3 worldPosition) {
+
+ vec4 position = vec4(worldPosition, 1.0);
+ return vec3(dot(volume.worldToUnit0, position), dot(volume.worldToUnit1, position), dot(volume.worldToUnit2, position));
+
+}
+
+#endif
diff --git a/data/shader/volumetric/froxel.hsh b/data/shader/volumetric/froxel.hsh
new file mode 100644
index 000000000..493aa7fb6
--- /dev/null
+++ b/data/shader/volumetric/froxel.hsh
@@ -0,0 +1,67 @@
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+#include
+
+#define FROXEL_CLUSTER_SIZE 4
+// Thin fog is far below the normal range of the half floats of the froxels
+#define FROXEL_DATA_SCALE 256.0
+
+layout(push_constant) uniform constants {
+ ivec2 columnCount;
+ ivec2 resolution;
+ int sliceCount;
+ int tileSize;
+ float near;
+ float far;
+ int lightCount;
+ int resetHistory;
+ int fogVolumeCount;
+ vec4 jitter;
+ float extendedFar;
+ float distributionExponent;
+ float padding1;
+ float padding2;
+} pushConstants;
+
+FroxelSlices GetFroxelSlices() {
+
+ return FroxelSlices(pushConstants.near, pushConstants.far, pushConstants.extendedFar, pushConstants.sliceCount,
+ pushConstants.distributionExponent);
+
+}
+
+float GetFroxelSliceDepth(float slice) {
+
+ return GetFroxelSliceDepth(GetFroxelSlices(), slice);
+
+}
+
+float GetFroxelSlice(float viewDepth) {
+
+ return GetFroxelSlice(GetFroxelSlices(), viewDepth);
+
+}
+
+// The grid is fixed to the unjittered projection, a jittered grid shows up as pulsing of small lights
+vec2 UnjitteredToJitteredTexCoord(vec2 texCoord) {
+
+ return texCoord + 0.5 * globalData.jitterCurrent;
+
+}
+
+vec2 GetFroxelColumnTexCoord(ivec2 column, vec2 volumetricResolution) {
+
+ return UnjitteredToJitteredTexCoord((vec2(column) + 0.5) * float(pushConstants.tileSize) / volumetricResolution);
+
+}
+
+vec3 GetFroxelPosition(ivec3 froxel, vec3 offset, vec2 volumetricResolution) {
+
+ vec2 texCoord = (vec2(froxel.xy) + offset.xy) * float(pushConstants.tileSize) / volumetricResolution;
+
+ float viewDepth = GetFroxelSliceDepth(float(froxel.z) + offset.z);
+
+ vec3 rayDirection = normalize(ConvertDepthToViewSpace(1.0, UnjitteredToJitteredTexCoord(texCoord)));
+ return rayDirection * (viewDepth / max(-rayDirection.z, 1e-3));
+
+}
diff --git a/data/shader/volumetric/froxelApply.csh b/data/shader/volumetric/froxelApply.csh
new file mode 100644
index 000000000..46e298331
--- /dev/null
+++ b/data/shader/volumetric/froxelApply.csh
@@ -0,0 +1,78 @@
+layout (local_size_x = 8, local_size_y = 8) in;
+
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+#include <../common/stencil.hsh>
+
+#include
+
+layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D volumetricImage;
+layout(set = 3, binding = 1) uniform sampler2D depthTexture;
+layout(set = 3, binding = 3) uniform sampler2D oceanDepthTexture;
+layout(set = 3, binding = 4) uniform usampler2D oceanStencilTexture;
+layout(set = 3, binding = 20) uniform sampler3D integratedFroxelTexture;
+
+// Cubic B-spline in x and y from four linear samples, see "Fast Third-Order Texture Filtering", Sigg and Hadwiger 2005
+vec4 SampleIntegratedFroxels(vec3 texCoord) {
+
+ vec2 size = vec2(pushConstants.columnCount);
+ vec2 coord = texCoord.xy * size - 0.5;
+ vec2 index = floor(coord);
+ vec2 fraction = coord - index;
+ vec2 oneMinusFraction = 1.0 - fraction;
+
+ vec2 w0 = oneMinusFraction * oneMinusFraction * oneMinusFraction / 6.0;
+ vec2 w1 = (4.0 - 6.0 * fraction * fraction + 3.0 * fraction * fraction * fraction) / 6.0;
+ vec2 w3 = fraction * fraction * fraction / 6.0;
+ vec2 w2 = 1.0 - w0 - w1 - w3;
+
+ vec2 g0 = w0 + w1;
+ vec2 g1 = w2 + w3;
+ vec2 coord0 = (index - 0.5 + w1 / g0) / size;
+ vec2 coord1 = (index + 1.5 + w3 / g1) / size;
+
+ vec4 sample00 = textureLod(integratedFroxelTexture, vec3(coord0.x, coord0.y, texCoord.z), 0.0);
+ vec4 sample10 = textureLod(integratedFroxelTexture, vec3(coord1.x, coord0.y, texCoord.z), 0.0);
+ vec4 sample01 = textureLod(integratedFroxelTexture, vec3(coord0.x, coord1.y, texCoord.z), 0.0);
+ vec4 sample11 = textureLod(integratedFroxelTexture, vec3(coord1.x, coord1.y, texCoord.z), 0.0);
+
+ return g0.y * (g0.x * sample00 + g1.x * sample10) + g1.y * (g0.x * sample01 + g1.x * sample11);
+
+}
+
+void main() {
+
+ ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
+ ivec2 resolution = imageSize(volumetricImage);
+ if (any(greaterThanEqual(pixel, resolution)))
+ return;
+
+ vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
+
+ float depth = textureLod(depthTexture, texCoord, 0.0).r;
+ vec3 endPos = ConvertDepthToViewSpace(depth, texCoord);
+
+#ifdef OCEAN
+ StencilFeatures features = DecodeStencilFeatures(textureLod(oceanStencilTexture, texCoord, 0.0).r);
+
+ float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r;
+ vec3 oceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord);
+
+ if (oceanDepth < depth && !features.underWaterPixel) {
+ endPos = oceanPos;
+ }
+#endif
+
+ // Each slice stores the integral up to its far end, inside the first slice it is interpolated from the camera
+ float slice = GetFroxelSlice(-endPos.z);
+ vec2 unjitteredTexCoord = texCoord - 0.5 * globalData.jitterCurrent;
+ vec2 gridTexCoord = unjitteredTexCoord * vec2(resolution) / vec2(pushConstants.columnCount * pushConstants.tileSize);
+ float sliceTexCoord = (max(slice - 1.0, 0.0) + 0.5) / float(pushConstants.sliceCount);
+ vec4 integrated = SampleIntegratedFroxels(vec3(gridTexCoord, sliceTexCoord));
+
+ float firstSliceWeight = clamp(slice, 0.0, 1.0);
+ integrated = mix(vec4(0.0, 0.0, 0.0, 1.0), integrated, firstSliceWeight);
+
+ imageStore(volumetricImage, pixel, integrated);
+
+}
diff --git a/data/shader/volumetric/froxelCulling.csh b/data/shader/volumetric/froxelCulling.csh
new file mode 100644
index 000000000..c5c3b8788
--- /dev/null
+++ b/data/shader/volumetric/froxelCulling.csh
@@ -0,0 +1,122 @@
+// One light list per froxel cluster
+
+layout (local_size_x = 64) in;
+
+#include <../deferred/lightCulling.hsh>
+#include <../structures.hsh>
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+
+#include
+#include
+
+layout (std430, set = 3, binding = 8) buffer VolumetricLights {
+ VolumetricLight volumetricLights[];
+};
+
+layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer {
+ int lightIndices[];
+};
+
+const int lightCountPerCluster = 63;
+
+shared int sharedLightIndices[lightCountPerCluster];
+shared int sharedLightCount;
+#ifdef FOG_VOLUMES
+shared uint sharedFogVolumeMask;
+#endif
+
+void main() {
+
+ ivec3 cluster = ivec3(gl_WorkGroupID);
+ ivec3 firstFroxel = cluster * FROXEL_CLUSTER_SIZE;
+ ivec3 lastFroxel = min(firstFroxel + FROXEL_CLUSTER_SIZE, ivec3(pushConstants.columnCount, pushConstants.sliceCount));
+
+ vec2 volumetricResolution = vec2(pushConstants.resolution);
+
+ vec3 corners[8];
+ for (int i = 0; i < 8; i++) {
+ ivec3 froxel = ivec3((i & 1) > 0 ? lastFroxel.x : firstFroxel.x, (i & 2) > 0 ? lastFroxel.y : firstFroxel.y,
+ (i & 4) > 0 ? lastFroxel.z - 1 : firstFroxel.z);
+ vec3 offset = vec3(0.0, 0.0, (i & 4) > 0 ? 1.0 : 0.0);
+ corners[i] = GetFroxelPosition(froxel, offset, volumetricResolution);
+ }
+
+ Plane planes[4];
+ GetFrustumPlanes(planes, corners);
+ AABB aabb = CalculateAABB(corners);
+
+ if (gl_LocalInvocationIndex == 0u) {
+ sharedLightCount = 0;
+#ifdef FOG_VOLUMES
+ sharedFogVolumeMask = 0u;
+#endif
+ }
+
+ barrier();
+
+ for (int i = int(gl_LocalInvocationIndex); i < pushConstants.lightCount; i += int(gl_WorkGroupSize.x)) {
+ VolumetricLight light = volumetricLights[i];
+ float radius = light.direction.w;
+ uint lightType = floatBitsToUint(light.color.a);
+
+ Sphere sphere;
+ if (lightType == POINT_LIGHT) {
+ sphere.center = light.location.xyz;
+ sphere.radius = radius;
+ }
+ else if (lightType == SPOT_LIGHT) {
+ sphere = CalculateSphereFromSpotLight(light.location, light.direction, radius);
+ }
+ else {
+ continue;
+ }
+
+ if (SphereAABBIntersection(sphere, aabb) && SphereFrustumIntersection(sphere, planes)) {
+ int lightIdx = atomicAdd(sharedLightCount, 1);
+ if (lightIdx < lightCountPerCluster)
+ sharedLightIndices[lightIdx] = i;
+ }
+ }
+
+#ifdef FOG_VOLUMES
+ vec3 clusterCenter = vec3(0.0);
+ for (int i = 0; i < 8; i++)
+ clusterCenter += corners[i] / 8.0;
+
+ float clusterRadius = 0.0;
+ for (int i = 0; i < 8; i++)
+ clusterRadius = max(clusterRadius, distance(corners[i], clusterCenter));
+
+ vec3 worldClusterCenter = vec3(globalData.ivMatrix * vec4(clusterCenter, 1.0));
+
+ for (int i = int(gl_LocalInvocationIndex); i < pushConstants.fogVolumeCount; i += int(gl_WorkGroupSize.x)) {
+ FogVolume volume = fogVolumes[i];
+
+ // Each row is the gradient of a unit axis, this also keeps flat and long volumes tight
+ vec3 unitCenter = GetFogVolumeUnitPosition(volume, worldClusterCenter);
+ vec3 unitRadius = clusterRadius * vec3(length(volume.worldToUnit0.xyz),
+ length(volume.worldToUnit1.xyz), length(volume.worldToUnit2.xyz));
+
+ if (all(lessThanEqual(abs(unitCenter), vec3(1.0) + unitRadius)))
+ atomicOr(sharedFogVolumeMask, 1u << uint(i));
+ }
+#endif
+
+ barrier();
+
+ int lightCount = min(lightCountPerCluster, sharedLightCount);
+ int clusterOffset = int(cluster.x + (cluster.y + cluster.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x) *
+ (lightCountPerCluster + 1);
+ for (int i = int(gl_LocalInvocationIndex); i < lightCount; i += int(gl_WorkGroupSize.x)) {
+ lightIndices[clusterOffset + i + 1] = sharedLightIndices[i];
+ }
+
+ if (gl_LocalInvocationIndex == 0u) {
+ lightIndices[clusterOffset] = lightCount;
+#ifdef FOG_VOLUMES
+ fogVolumeMasks[GetFogVolumeClusterIndex()] = sharedFogVolumeMask;
+#endif
+ }
+
+}
diff --git a/data/shader/volumetric/froxelFilter.csh b/data/shader/volumetric/froxelFilter.csh
new file mode 100644
index 000000000..d1874025e
--- /dev/null
+++ b/data/shader/volumetric/froxelFilter.csh
@@ -0,0 +1,34 @@
+layout (local_size_x = 4, local_size_y = 4, local_size_z = 4) in;
+
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+
+#include
+
+layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D froxelImage;
+layout(set = 3, binding = 1) uniform sampler3D froxelTexture;
+
+const float weights[7] = float[](0.071303, 0.131514, 0.189879, 0.214607, 0.189879, 0.131514, 0.071303);
+
+void main() {
+
+ ivec3 froxel = ivec3(gl_GlobalInvocationID);
+ ivec3 froxelCount = ivec3(pushConstants.columnCount, pushConstants.sliceCount);
+ if (any(greaterThanEqual(froxel, froxelCount)))
+ return;
+
+#ifdef HORIZONTAL
+ ivec3 offset = ivec3(1, 0, 0);
+#else
+ ivec3 offset = ivec3(0, 1, 0);
+#endif
+
+ vec4 result = vec4(0.0);
+ for (int i = -3; i <= 3; i++) {
+ ivec3 coord = clamp(froxel + i * offset, ivec3(0), froxelCount - 1);
+ result += weights[i + 3] * texelFetch(froxelTexture, coord, 0);
+ }
+
+ imageStore(froxelImage, froxel, result);
+
+}
diff --git a/data/shader/volumetric/froxelInject.csh b/data/shader/volumetric/froxelInject.csh
new file mode 100644
index 000000000..75efa86c8
--- /dev/null
+++ b/data/shader/volumetric/froxelInject.csh
@@ -0,0 +1,346 @@
+#extension GL_EXT_nonuniform_qualifier : require
+
+#include
+
+// volumetricLights.hsh reads gl_WorkGroupSize, which has to be declared before
+layout (local_size_x = FROXEL_CLUSTER_SIZE, local_size_y = FROXEL_CLUSTER_SIZE, local_size_z = FROXEL_CLUSTER_SIZE) in;
+
+#include
+#include
+#include <../common/random.hsh>
+
+layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D froxelImage;
+layout(set = 3, binding = 1) uniform sampler3D historyFroxelTexture;
+
+#ifdef SKY_PROBE
+layout(set = 1, binding = 12) uniform samplerCube diffuseProbe;
+#endif
+
+// Punctual lights only contribute to the first 100 units of a view ray
+const float punctualLightDistance = 100.0;
+
+// Integrates the inverse square falloff along the part of the view ray inside the froxel, such that the energy doesn't
+// depend on the jitter. The shadow is sampled where the falloff has most of its energy. The fog volumes have their own
+// phase function, their light is returned in volumeScattering where hasVolumes is set
+vec3 ComputePunctualLightScattering(uint lightType, vec3 rayDirection, float rayStart, float rayEnd, float sampleOffset,
+ float angularRadius, bool hasVolumes, float volumeAnisotropy, out vec3 volumeScattering) {
+
+ vec3 lightScattering = vec3(0.0);
+ volumeScattering = vec3(0.0);
+
+ for (int j = 0; j < sharedLightIndicesCount; j++) {
+ VolumetricLight light = sharedLights[j];
+
+ float radius = light.direction.w;
+
+ float closestDistance = dot(light.location.xyz, rayDirection);
+ float sqrRayDistance = max(dot(light.location.xyz, light.location.xyz) - closestDistance * closestDistance, 0.0);
+ if (sqrRayDistance >= radius * radius)
+ continue;
+
+ // The ray stands for a whole froxel column, a light inside of it is spread over the footprint of the column
+ float footprint = angularRadius * max(closestDistance, 0.0);
+ float offset = sqrt(sqrRayDistance + footprint * footprint + 0.1);
+
+ vec3 position = rayDirection * clamp(closestDistance, rayStart, rayEnd);
+ vec3 pointToLight = light.location.xyz - position;
+ float sqrDistance = dot(pointToLight, pointToLight);
+
+ float attenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 2.0));
+ if (attenuation == 0.0)
+ continue;
+
+ float angleStart = atan((rayStart - closestDistance) / offset);
+ float angleEnd = atan((rayEnd - closestDistance) / offset);
+ float falloff = (angleEnd - angleStart) / (offset * (rayEnd - rayStart));
+
+ vec3 shadowPosition = rayDirection * (closestDistance + offset * tan(mix(angleStart, angleEnd, sampleOffset)));
+
+ if (lightType == SPOT_LIGHT) {
+ vec3 L = normalize(light.location.xyz - shadowPosition);
+ float strength = dot(L, normalize(-light.direction.xyz));
+ float angleAttenuation = saturate(strength * light.specific0 + light.specific1);
+ if (angleAttenuation == 0.0)
+ continue;
+
+ attenuation *= sqr(angleAttenuation);
+ }
+
+ float NdotL = dot(-pointToLight / max(sqrt(sqrDistance), 0.001), rayDirection);
+ float shadowValue = GetShadowFactorPunctualLight(j, lightType, shadowPosition);
+
+ vec3 incomingLight = shadowValue * light.color.rgb * attenuation * light.intensity * falloff;
+ lightScattering += ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) * incomingLight;
+ if (hasVolumes)
+ volumeScattering += ComputeScattering(volumeAnisotropy, NdotL) * incomingLight;
+ }
+
+ return lightScattering;
+
+}
+
+vec3 ComputePunctualLightSample(uint lightType, ivec3 froxel, vec3 offset, vec2 volumetricResolution,
+ bool hasVolumes, float volumeAnisotropy, out vec3 volumeScattering) {
+
+ volumeScattering = vec3(0.0);
+
+ vec3 columnStart = normalize(GetFroxelPosition(froxel, vec3(0.0, 0.5, 1.0), volumetricResolution));
+ vec3 columnEnd = normalize(GetFroxelPosition(froxel, vec3(1.0, 0.5, 1.0), volumetricResolution));
+ float angularRadius = 0.5 * distance(columnStart, columnEnd);
+
+ vec3 segmentStart = GetFroxelPosition(froxel, vec3(offset.xy, 0.0), volumetricResolution);
+ vec3 segmentEnd = GetFroxelPosition(froxel, vec3(offset.xy, 1.0), volumetricResolution);
+
+ float rayStart = length(segmentStart);
+ float rayLength = length(segmentEnd);
+ float rayEnd = min(rayLength, punctualLightDistance);
+
+ return rayStart < rayEnd ? ComputePunctualLightScattering(lightType, segmentEnd / rayLength, rayStart, rayEnd, offset.z,
+ angularRadius, hasVolumes, volumeAnisotropy, volumeScattering) : vec3(0.0);
+
+}
+
+vec4 GetHistory(vec3 position, vec2 volumetricResolution, out bool valid) {
+
+ vec3 worldPosition = vec3(globalData.ivMatrix * vec4(position, 1.0));
+
+ vec4 lastClipSpace = globalData.pvMatrixLast * vec4(worldPosition, 1.0);
+ vec2 lastTexCoord = (lastClipSpace.xy / lastClipSpace.w - globalData.jitterLast) * 0.5 + 0.5;
+ float lastViewDepth = -(globalData.vMatrixLast * vec4(worldPosition, 1.0)).z;
+
+ vec2 gridScale = volumetricResolution / vec2(pushConstants.columnCount * pushConstants.tileSize);
+ vec3 historyTexCoord = vec3(lastTexCoord * gridScale, GetFroxelSlice(lastViewDepth) / float(pushConstants.sliceCount));
+
+ valid = pushConstants.resetHistory == 0 && lastClipSpace.w > 0.0 &&
+ all(greaterThanEqual(historyTexCoord, vec3(0.0))) && all(lessThanEqual(historyTexCoord, vec3(1.0)));
+ return textureLod(historyFroxelTexture, historyTexCoord, 0.0);
+
+}
+
+vec3 GetSkyAmbient() {
+
+#ifdef SKY_PROBE
+ return 0.5 * (textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb + textureLod(diffuseProbe, vec3(0.0, -1.0, 0.0), 0.0).rgb);
+#else
+ return vec3(1.0);
+#endif
+
+}
+
+#ifdef FOG_VOLUMES
+float GetValueNoise(vec3 position) {
+
+ ivec3 cell = ivec3(floor(position));
+ vec3 weight = fract(position);
+ weight = weight * weight * (3.0 - 2.0 * weight);
+
+ float values[8];
+ for (int i = 0; i < 8; i++) {
+ uvec3 corner = uvec3(cell + ivec3(i & 1, (i >> 1) & 1, (i >> 2) & 1));
+ // The hash is symmetric in its last components
+ values[i] = floatConstruct(hash(corner + uvec3(0u, 0x3C6EF372u, 0x9E3779B9u)));
+ }
+
+ float bottom = mix(mix(values[0], values[1], weight.x), mix(values[2], values[3], weight.x), weight.y);
+ float top = mix(mix(values[4], values[5], weight.x), mix(values[6], values[7], weight.x), weight.y);
+ return mix(bottom, top, weight.z);
+
+}
+
+// Coverage is the part of the volume which keeps its fog, the rest is cut out as gaps
+float GetFogVolumeNoise(FogVolume volume, vec3 worldPosition) {
+
+ vec3 position = (worldPosition - volume.noiseOffsetAndFrequency.xyz) * volume.noiseOffsetAndFrequency.w;
+
+ float noise = 0.0;
+ float weight = 1.0;
+ float totalWeight = 0.0;
+ for (int i = 0; i < volume.noiseOctaves; i++) {
+ noise += weight * GetValueNoise(position + 17.0 * float(i));
+ totalWeight += weight;
+ weight *= 0.5;
+ position *= 2.03;
+ }
+ noise /= totalWeight;
+
+ // Layered value noise rarely leaves this range
+ float threshold = mix(0.8, 0.2, volume.noiseCoverage);
+ float softness = mix(0.3, 0.01, volume.noiseSharpness);
+ return smoothstep(threshold - softness, threshold + softness, noise);
+
+}
+
+float GetFogVolumeDensity(FogVolume volume, vec3 worldPosition) {
+
+ vec3 unitPosition = GetFogVolumeUnitPosition(volume, worldPosition);
+
+ vec3 absPosition = abs(unitPosition);
+ float edgeDistance = 1.0 - (volume.shape == FOG_VOLUME_BOX ?
+ max(absPosition.x, max(absPosition.y, absPosition.z)) : length(unitPosition));
+ if (edgeDistance <= 0.0)
+ return 0.0;
+
+ float density = volume.scatteringAndDensity.a * smoothstep(0.0, max(volume.emissiveAndEdgeFade.a, 0.001), edgeDistance);
+ density *= exp(-volume.heightFalloff * (unitPosition.y * 0.5 + 0.5));
+
+ if (volume.noiseAmount > 0.0)
+ density *= mix(1.0, GetFogVolumeNoise(volume, worldPosition), volume.noiseAmount);
+
+ return density;
+
+}
+
+// Ignores the noise, the falloff and the fade at the edges
+float GetFogVolumeTransmittanceToLight(FogVolume volume, vec3 worldPosition, vec3 worldToLight) {
+
+ vec3 unitPosition = GetFogVolumeUnitPosition(volume, worldPosition);
+ vec3 unitDirection = vec3(dot(volume.worldToUnit0.xyz, worldToLight), dot(volume.worldToUnit1.xyz, worldToLight),
+ dot(volume.worldToUnit2.xyz, worldToLight));
+
+ float exitDistance;
+ if (volume.shape == FOG_VOLUME_BOX) {
+ vec3 axisDistance = (vec3(1.0) - unitPosition * sign(unitDirection)) / max(abs(unitDirection), vec3(1e-6));
+ exitDistance = min(axisDistance.x, min(axisDistance.y, axisDistance.z));
+ }
+ else {
+ float a = dot(unitDirection, unitDirection);
+ float b = dot(unitPosition, unitDirection);
+ float c = dot(unitPosition, unitPosition) - 1.0;
+ exitDistance = (-b + sqrt(max(b * b - a * c, 0.0))) / a;
+ }
+
+ // The second term stands in for light which reaches the point after scattering several times
+ float opticalDepth = volume.selfShadowing * volume.scatteringAndDensity.a * max(exitDistance, 0.0);
+ return max(exp(-opticalDepth), 0.3 * exp(-0.25 * opticalDepth));
+
+}
+#endif
+
+void main() {
+
+ // No early return, all invocations have to reach the barriers when loading the lights
+ ivec3 froxel = ivec3(gl_GlobalInvocationID);
+ bool validFroxel = all(lessThan(froxel.xy, pushConstants.columnCount)) && froxel.z < pushConstants.sliceCount;
+
+ vec2 volumetricResolution = vec2(pushConstants.resolution);
+
+ vec3 jitter = pushConstants.jitter.xyz;
+ // The last slice reaches up to the camera far plane, a jittered depth makes the distance flicker
+ if (froxel.z == pushConstants.sliceCount - 1)
+ jitter.z = 0.5;
+ vec3 position = GetFroxelPosition(froxel, jitter, volumetricResolution);
+ vec3 rayDirection = normalize(position);
+ vec3 worldPosition = vec3(globalData.ivMatrix * vec4(position, 1.0));
+
+ float heightDensity = GetVolumetricFogDensity(uniforms.fog, worldPosition);
+ float density = uniforms.fog.density * heightDensity;
+
+ // Weights of the lighting in the volumes, known before the lighting is computed
+ vec3 volumeDirectional = vec3(0.0);
+ vec3 volumeLocal = vec3(0.0);
+ vec3 volumeAmbient = vec3(0.0);
+ vec3 volumeEmissive = vec3(0.0);
+ float volumeExtinction = 0.0;
+
+ // Overlapping volumes share one phase function, their anisotropies are blended by the light they scatter. A single
+ // volume keeps its own exactly
+ float volumeAnisotropyWeighted = 0.0;
+ float volumeAnisotropyWeight = 0.0;
+
+#ifdef FOG_VOLUMES
+ vec3 worldToLight = -normalize(mat3(globalData.ivMatrix) * volumetricLights[0].direction.xyz);
+ uint fogVolumeMask = fogVolumeMasks[GetFogVolumeClusterIndex()];
+ while (fogVolumeMask != 0u) {
+ FogVolume volume = fogVolumes[findLSB(fogVolumeMask)];
+ fogVolumeMask &= fogVolumeMask - 1u;
+
+ float volumeDensity = GetFogVolumeDensity(volume, worldPosition);
+ if (volumeDensity <= 0.0)
+ continue;
+
+ float transmittance = uniforms.directionalLightCount > 0 ?
+ GetFogVolumeTransmittanceToLight(volume, worldPosition, worldToLight) : 1.0;
+
+ vec3 volumeScattering = volumeDensity * volume.scatteringAndDensity.rgb;
+ float scatteringWeight = dot(volumeScattering, vec3(0.2126, 0.7152, 0.0722));
+ volumeAnisotropyWeighted += scatteringWeight * volume.scatteringAnisotropy;
+ volumeAnisotropyWeight += scatteringWeight;
+
+ volumeDirectional += transmittance * volumeScattering;
+ volumeLocal += volumeScattering;
+ volumeAmbient += volume.ambientFactor * volumeScattering;
+ volumeEmissive += volumeDensity * volume.emissiveAndEdgeFade.rgb;
+ volumeExtinction += volumeDensity;
+ }
+#endif
+
+ // Without a volume at the froxel the second phase function is skipped
+ bool hasVolumes = volumeAnisotropyWeight > 0.0;
+ float volumeAnisotropy = hasVolumes ? volumeAnisotropyWeighted / volumeAnisotropyWeight : 0.0;
+
+ // The lighting is multiplied by the density, shadows are expensive and don't matter without fog
+ bool hasFog = validFroxel && ((density > 0.0 && heightDensity > 0.001) || volumeExtinction > 0.0);
+
+ vec3 directionalScattering = vec3(0.0);
+ vec3 volumeDirectionalScattering = vec3(0.0);
+ for (int j = 0; hasFog && j < uniforms.directionalLightCount; j++) {
+ VolumetricLight light = volumetricLights[j];
+
+ uint lightType = floatBitsToUint(light.color.a);
+
+ bool isMain = j == 0 ? true : false;
+ float shadowValue = GetShadowFactorDirectionalLight(j, light.shadowIdx, lightType, isMain, position);
+
+ vec3 lightPosition = position - 100000.0 * light.direction.xyz;
+ lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0));
+ float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition);
+ float NdotL = dot(rayDirection, normalize(light.direction.xyz));
+
+ vec3 incomingLight = shadowValue * light.color.rgb * light.intensity * extinctionToLight;
+ directionalScattering += ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) * incomingLight;
+ if (hasVolumes)
+ volumeDirectionalScattering += ComputeScattering(volumeAnisotropy, NdotL) * incomingLight;
+ }
+
+ vec3 center = GetFroxelPosition(froxel, vec3(0.5), volumetricResolution);
+
+ vec3 localScattering = vec3(0.0);
+ vec3 volumeLocalScattering = vec3(0.0);
+#ifdef LOCAL_LIGHTS
+ vec3 volumeLightScattering;
+ LoadLightTypeData(POINT_LIGHT);
+ if (hasFog && sharedLightIndicesCount > 0) {
+ localScattering += ComputePunctualLightSample(POINT_LIGHT, froxel, pushConstants.jitter.xyz, volumetricResolution,
+ hasVolumes, volumeAnisotropy, volumeLightScattering);
+ volumeLocalScattering += volumeLightScattering;
+ }
+ LoadLightTypeData(SPOT_LIGHT);
+ if (hasFog && sharedLightIndicesCount > 0) {
+ localScattering += ComputePunctualLightSample(SPOT_LIGHT, froxel, pushConstants.jitter.xyz, volumetricResolution,
+ hasVolumes, volumeAnisotropy, volumeLightScattering);
+ volumeLocalScattering += volumeLightScattering;
+ }
+#endif
+
+ vec3 skyAmbient = hasFog ? GetSkyAmbient() : vec3(0.0);
+
+ vec3 scattering = uniforms.fog.albedo.rgb * density *
+ (directionalScattering + localScattering + uniforms.fog.ambientFactor * skyAmbient);
+ scattering += volumeDirectional * volumeDirectionalScattering + volumeLocal * volumeLocalScattering +
+ volumeAmbient * skyAmbient + volumeEmissive;
+ // Fog volumes have their own extinction, the global fog doesn't change it
+ float extinction = density + volumeExtinction;
+
+ vec4 current = vec4(scattering, extinction) * FROXEL_DATA_SCALE;
+
+ bool validHistory;
+ vec4 history = GetHistory(center, volumetricResolution, validHistory);
+ // A single invalid value would stay in the history forever
+ validHistory = validHistory && !any(isnan(history)) && !any(isinf(history));
+ history.rgb *= globalData.preExposure / globalData.lastPreExposure;
+ vec4 result = validHistory ? mix(history, current, 0.1) : current;
+
+ if (validFroxel)
+ imageStore(froxelImage, froxel, result);
+
+}
diff --git a/data/shader/volumetric/froxelIntegrate.csh b/data/shader/volumetric/froxelIntegrate.csh
new file mode 100644
index 000000000..31e0f9ab6
--- /dev/null
+++ b/data/shader/volumetric/froxelIntegrate.csh
@@ -0,0 +1,88 @@
+layout (local_size_x = 8, local_size_y = 8) in;
+
+#include <../globals.hsh>
+#include <../common/convert.hsh>
+#include <../clouds/shadow.hsh>
+
+#include
+#include
+
+layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D integratedFroxelImage;
+layout(set = 3, binding = 1) uniform sampler3D froxelTexture;
+layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture;
+
+layout(std140, set = 3, binding = 7) uniform UniformBuffer {
+ float intensity;
+ int directionalLightCount;
+ int padding0;
+ int padding1;
+ vec4 planetCenterAndRadius;
+ Fog fog;
+ CloudShadow cloudShadow;
+} uniforms;
+
+void main() {
+
+ ivec2 column = ivec2(gl_GlobalInvocationID.xy);
+ if (any(greaterThanEqual(column, pushConstants.columnCount)))
+ return;
+
+ vec2 volumetricResolution = vec2(pushConstants.resolution);
+ vec2 texCoord = GetFroxelColumnTexCoord(column, volumetricResolution);
+
+ vec3 viewDirection = normalize(ConvertDepthToViewSpace(1.0, texCoord));
+ float distancePerDepth = 1.0 / max(-viewDirection.z, 1e-3);
+ vec3 worldDirection = vec3(globalData.ivMatrix * vec4(viewDirection, 0.0));
+
+ vec3 foginess = vec3(0.0);
+ vec4 extinction = vec4(1.0);
+ vec4 extinctionWithClouds = vec4(1.0);
+
+#ifdef CLOUDS
+ bool receivedCloudExtinction = false;
+ float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoord, 0.0).a, 1.0);
+ vec3 planetCenter = uniforms.planetCenterAndRadius.xyz;
+ float cloudInnerRadius = uniforms.planetCenterAndRadius.w;
+#endif
+
+ float sliceStart = 0.0;
+ for (int i = 0; i < pushConstants.sliceCount; i++) {
+ float sliceEnd = GetFroxelSliceDepth(float(i + 1));
+ float stepLength = (sliceEnd - sliceStart) * distancePerDepth;
+
+ vec4 froxel = texelFetch(froxelTexture, ivec3(column, i), 0) / FROXEL_DATA_SCALE;
+
+ // Extinction of the global fog and the fog volumes, grey for all channels
+ vec4 extinctionCoefficient = vec4(froxel.a);
+
+ vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001);
+ vec4 stepExtinction = exp(-extinctionCoefficient * stepLength);
+
+ vec3 stepScattering = froxel.rgb;
+ vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb;
+
+#ifdef CLOUDS
+ foginess += luminanceIntegral * extinctionWithClouds.rgb;
+
+ vec3 worldPosition = globalData.cameraLocation.xyz +
+ worldDirection * (0.5 * (sliceStart + sliceEnd) * distancePerDepth);
+ float distToPlanetCenter = distance(worldPosition, planetCenter);
+ if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) {
+ extinctionWithClouds *= stepExtinction * cloudExtinction;
+ receivedCloudExtinction = true;
+ }
+ else {
+ extinctionWithClouds *= stepExtinction;
+ }
+#else
+ foginess += luminanceIntegral * extinction.rgb;
+#endif
+
+ extinction *= stepExtinction;
+
+ imageStore(integratedFroxelImage, ivec3(column, i), vec4(foginess * uniforms.intensity, extinction.a));
+
+ sliceStart = sliceEnd;
+ }
+
+}
diff --git a/data/shader/volumetric/froxelSlices.hsh b/data/shader/volumetric/froxelSlices.hsh
new file mode 100644
index 000000000..b4bfac26a
--- /dev/null
+++ b/data/shader/volumetric/froxelSlices.hsh
@@ -0,0 +1,41 @@
+// The depths of the slices of the froxel grid, which is shared by the froxel passes and the translucent surfaces
+
+struct FroxelSlices {
+ float near;
+ float far;
+ float extendedFar;
+ int sliceCount;
+ float distributionExponent;
+};
+
+float GetRegularFroxelSliceDepth(FroxelSlices slices, float slice) {
+
+ float t = pow(clamp(slice / float(slices.sliceCount), 0.0, 1.0), slices.distributionExponent);
+ return slices.near * pow(slices.far / slices.near, t);
+
+}
+
+float GetFroxelSliceDepth(FroxelSlices slices, float slice) {
+
+ float lastSlice = float(slices.sliceCount - 1);
+ if (slice <= lastSlice)
+ return GetRegularFroxelSliceDepth(slices, slice);
+
+ float lastSliceStart = GetRegularFroxelSliceDepth(slices, lastSlice);
+ return mix(lastSliceStart, max(slices.extendedFar, slices.far), slice - lastSlice);
+
+}
+
+float GetFroxelSlice(FroxelSlices slices, float viewDepth) {
+
+ float lastSlice = float(slices.sliceCount - 1);
+ float lastSliceStart = GetRegularFroxelSliceDepth(slices, lastSlice);
+ if (viewDepth >= lastSliceStart) {
+ float lastSliceEnd = max(slices.extendedFar, slices.far);
+ return lastSlice + clamp((viewDepth - lastSliceStart) / max(lastSliceEnd - lastSliceStart, 1e-6), 0.0, 1.0);
+ }
+
+ float t = log(max(viewDepth, slices.near) / slices.near) / log(slices.far / slices.near);
+ return pow(t, 1.0 / slices.distributionExponent) * float(slices.sliceCount);
+
+}
diff --git a/data/shader/volumetric/lightCulling.csh b/data/shader/volumetric/lightCulling.csh
deleted file mode 100644
index e2928118f..000000000
--- a/data/shader/volumetric/lightCulling.csh
+++ /dev/null
@@ -1,120 +0,0 @@
-layout (local_size_x = 16, local_size_y = 16) in;
-
-#include <../deferred/lightCulling.hsh>
-
-#include <../structures.hsh>
-#include <../shadow.hsh>
-#include <../globals.hsh>
-
-#include <../common/convert.hsh>
-#include <../common/utility.hsh>
-
-layout(set = 3, binding = 1) uniform sampler2D depthTexture;
-
-layout (std430, set = 3, binding = 8) buffer VolumetricLights {
- VolumetricLight volumetricLights[];
-};
-
-layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer {
- int lightIndices[];
-};
-
-layout(push_constant) uniform constants {
- int lightCount;
-} pushConstants;
-
-const int lightCountPerTile = 63;
-const int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y);
-
-// Results in 32 * 128 = 4096 possible lights in the tile
-shared int sharedLightIndices[lightCountPerTile];
-shared int sharedLightCount;
-shared uint sharedDepthMax;
-
-int GetLightIndicesOffset() {
-
- int groupOffset = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x);
- return groupOffset * (lightCountPerTile + 1);
-
-}
-
-void main() {
-
- ivec2 resolution = textureSize(depthTexture, 0);
- ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
-
- vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution);
-
- float depth = texelFetch(depthTexture, pixel, 0).r;
- float viewDepth = ConvertDepthToViewSpaceDepth(depth);
-
- if (gl_LocalInvocationIndex == 0u) {
- sharedDepthMax = floatBitsToUint(depth);
- sharedLightCount = 0;
- }
-
- barrier();
-
- atomicMax(sharedDepthMax, floatBitsToUint(depth));
-
- barrier();
-
- float depthMin = 0.0;
- float depthMax = ConvertDepthToViewSpaceDepth(uintBitsToFloat(sharedDepthMax));
-
- vec3 frustumCorners[8];
- GetFrustumCorners(frustumCorners, resolution, 0.0, uintBitsToFloat(sharedDepthMax));
-
- Plane frustumPlanes[4];
- GetFrustumPlanes(frustumPlanes, frustumCorners);
-
- AABB frustumAABB = CalculateAABB(frustumCorners);
-
- vec3 viewPos = ConvertDepthToViewSpace(depth, texCoord);
-
- int localOffset = int(gl_LocalInvocationIndex);
- int lightIdx = 0;
- for (int i = localOffset; i < pushConstants.lightCount && lightIdx < lightCountPerTile; i += groupSize) {
- bool visible = true;
-
- VolumetricLight light = volumetricLights[i];
- float radius = light.direction.w;
-
- uint lightType = floatBitsToUint(light.color.a);
- Sphere sphere;
-
- // Remember: Forward is in -z direction
- if (lightType == POINT_LIGHT) {
- sphere.center = light.location.xyz;
- sphere.radius = radius;
- }
- else if (lightType == SPOT_LIGHT) {
- sphere = CalculateSphereFromSpotLight(light.location, light.direction, radius);
- }
-
- visible = visible && SphereAABBIntersection(sphere, frustumAABB);
- if (visible) {
- visible = SphereFrustumIntersection(sphere, frustumPlanes);
- }
-
- if (visible) {
- lightIdx = atomicAdd(sharedLightCount, 1);
-
- if (lightIdx < lightCountPerTile)
- sharedLightIndices[lightIdx] = i;
- }
- }
-
- barrier();
-
- int lightCount = min(lightCountPerTile, sharedLightCount);
- int lightIndicesOffset = GetLightIndicesOffset();
- for (int i = localOffset; i < lightCount; i += groupSize) {
- lightIndices[i + lightIndicesOffset + 1] = sharedLightIndices[i];
- }
-
- if (gl_LocalInvocationIndex == 0u) {
- lightIndices[lightIndicesOffset] = lightCount;
- }
-
-}
\ No newline at end of file
diff --git a/data/shader/volumetric/volumetric.csh b/data/shader/volumetric/volumetric.csh
deleted file mode 100644
index dc39ed199..000000000
--- a/data/shader/volumetric/volumetric.csh
+++ /dev/null
@@ -1,522 +0,0 @@
-#extension GL_EXT_nonuniform_qualifier : require
-
-layout (local_size_x = 16, local_size_y = 16) in;
-
-#include <../globals.hsh>
-#include <../structures.hsh>
-#include <../common/ign.hsh>
-#include <../common/convert.hsh>
-#include <../common/stencil.hsh>
-#include <../common/utility.hsh>
-#include <../common/random.hsh>
-#include <../clouds/shadow.hsh>
-#include <../common/bluenoise.hsh>
-
-#include
-
-layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D volumetricImage;
-layout(set = 3, binding = 1) uniform sampler2D depthTexture;
-layout(set = 3, binding = 2) uniform sampler2D cloudMap;
-layout(set = 3, binding = 3) uniform sampler2D oceanDepthTexture;
-layout(set = 3, binding = 4) uniform usampler2D oceanStencilTexture;
-layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture;
-layout(set = 3, binding = 6) uniform sampler shadowSampler;
-
-layout(std140, set = 3, binding = 7) uniform UniformBuffer {
- int sampleCount;
- float intensity;
- int fogEnabled;
- float oceanHeight;
- int lightCount;
- int offsetX;
- int offsetY;
- int directionalLightCount;
- vec4 planetCenterAndRadius;
- Fog fog;
- CloudShadow cloudShadow;
-} uniforms;
-
-layout (std430, set = 3, binding = 8) buffer VolumetricLights {
- VolumetricLight volumetricLights[];
-};
-
-layout (std430, set = 3, binding = 9) buffer VolumetricShadows {
- Shadow volumetricShadows[];
-};
-
-layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer {
- int lightIndices[];
-};
-
-layout(set = 3, binding = 11) uniform texture2DArray cascadeMaps[8];
-layout(set = 3, binding = 19) uniform textureCube cubeMaps[8];
-
-const int lightCountPerTile = 63;
-
-shared uint sharedLightIndices[64];
-shared int sharedLightIndicesCount;
-
-vec4 ComputeVolumetricDirectionalLights(vec3 fragPos, float startDepth, vec2 texCoords);
-vec4 ComputeVolumetricPunctualLights(uint lightType, vec3 fragPos, float startDepth, vec2 texCoords);
-float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition);
-float GetShadowFactorPunctualLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition);
-
-int GetLightIndicesOffset() {
-
- int groupOffset = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x);
- return groupOffset * (lightCountPerTile + 1);
-
-}
-
-void LoadLightTypeData(uint requestedLightType) {
-
- barrier();
-
- int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y);
- int localOffset = int(gl_LocalInvocationIndex);
-
- if (localOffset == 0) {
- sharedLightIndicesCount = 0;
- }
-
- barrier();
-
- int groupOffset = GetLightIndicesOffset();
- int lightCount = min(lightCountPerTile, lightIndices[groupOffset]);
-
- int lastIdx = 0;
- for (int i = localOffset; i < lightCount; i += groupSize) {
- uint lightIdx = lightIndices[groupOffset + i + 1];
- uint lightType = floatBitsToUint(volumetricLights[lightIdx].color.a);
- if (requestedLightType != lightType)
- continue;
-
- int idx = atomicAdd(sharedLightIndicesCount, 1);
- if (idx < lightCountPerTile)
- sharedLightIndices[idx] = lightIdx;
- }
-
- barrier();
-
- if (localOffset == 0) {
- sharedLightIndicesCount = min(lightCount, sharedLightIndicesCount);
- }
-
- barrier();
-
-}
-
-void main() {
-
- ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(volumetricImage).x ||
- pixel.y > imageSize(volumetricImage).y)
- return;
-
- vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricImage));
-
- float depth = textureLod(depthTexture, texCoord, 0.0).r;
- vec3 pixelPos = ConvertDepthToViewSpace(depth, texCoord);
-
- vec3 endPos = pixelPos;
-
- float startDepth = 0.0;
-#ifdef OCEAN
- StencilFeatures features = DecodeStencilFeatures(textureLod(oceanStencilTexture, texCoord, 0.0).r);
-
- float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r;
- vec3 oceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord);
-
- // We could use stencil features here, but they are unrealiable. Next option is to just apply
- // simpl fog to the refraction texture when under water
- if (oceanDepth < depth && !features.underWaterPixel) {
- endPos = oceanPos;
- }
-#endif
-
- bool validPixel = pixel.x < imageSize(volumetricImage).x &&
- pixel.y < imageSize(volumetricImage).y;
-
- vec4 radiance = vec4(0.0);
- radiance = ComputeVolumetricDirectionalLights(endPos, startDepth, texCoord);
-
-#ifdef LOCAL_LIGHTS
- LoadLightTypeData(POINT_LIGHT);
- if (sharedLightIndicesCount > 0)
- radiance.rgb += ComputeVolumetricPunctualLights(POINT_LIGHT, endPos, startDepth, texCoord).rgb;
-
- LoadLightTypeData(SPOT_LIGHT);
- if (sharedLightIndicesCount > 0)
- radiance.rgb += ComputeVolumetricPunctualLights(SPOT_LIGHT, endPos, startDepth, texCoord).rgb;
-#endif
-
- if (validPixel)
- imageStore(volumetricImage, pixel, radiance);
-
-}
-
-vec4 ComputeVolumetricDirectionalLights(vec3 fragPos, float startDepth, vec2 texCoords) {
-
- vec2 resolution = vec2(imageSize(volumetricImage));
- vec3 viewPosition = vec3(globalData.ivMatrix * vec4(fragPos, 1.0));
-
- // We compute this in view space
- vec3 rayVector = fragPos;
- float rayLength = max(length(rayVector) - startDepth, 0.0);
- vec3 rayDirection = rayVector / rayLength;
- float stepLength = rayLength / float(uniforms.sampleCount);
- vec3 stepVector = rayDirection * stepLength;
-
- vec3 foginess = vec3(0.0);
- vec4 extinction = vec4(1.0);
- vec4 extinctionWithClouds = vec4(1.0);
-
- vec2 interleavedTexCoords = (0.5 * texCoords + 0.5) * resolution;
-
- float noiseOffset = GetInterleavedGradientNoise(interleavedTexCoords);
- vec3 currentPosition = stepVector * (noiseOffset + startDepth);
-
-#ifdef CLOUDS
- bool receivedCloudExtinction = false;
- float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoords, 0.0).a, 1.0);
-#endif
-
- for (int i = 0; i < uniforms.sampleCount; i++) {
-
- float t0 = float(i) / float(uniforms.sampleCount);
- float t1 = float(i + 1) / float(uniforms.sampleCount);
-
- t0 = t0 * t0;
- t1 = t1 * t1;
-
- float delta = t1 - t0;
- float t = t0 + delta * noiseOffset;
-
- currentPosition = rayDirection * t * rayLength + startDepth;
- stepLength = delta * rayLength;
-
- vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0));
-
- vec3 lightScattering = vec3(0.0);
- vec3 lightAmbient = vec3(1.0);
-
- // First all directional lights
- for(int j = 0; j < uniforms.directionalLightCount; j++) {
- VolumetricLight light = volumetricLights[j];
-
- uint lightType = floatBitsToUint(light.color.a);
-
- bool isMain = j == 0 ? true : false;
- float shadowValue = GetShadowFactorDirectionalLight(j, light.shadowIdx, lightType, isMain, currentPosition);
-
- vec3 lightPosition = currentPosition - 100000.0 * light.direction.xyz;
- lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0));
- float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition);
- float NdotL = dot(normalize(rayDirection), normalize(light.direction.xyz));
-
- float phaseFunction = uniforms.fogEnabled > 0 ?
- ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) : 1.0;
-
- lightScattering += shadowValue * phaseFunction * light.color.rgb * light.intensity * extinctionToLight;
- }
-
-#ifdef CLOUDS
- vec3 planetCenter = uniforms.planetCenterAndRadius.xyz;
- float cloudInnerRadius = uniforms.planetCenterAndRadius.w;
-
- float distToPlanetCenter = distance(worldPosition, planetCenter);
-#endif
-
- float density = uniforms.fog.density * GetVolumetricFogDensity(uniforms.fog, worldPosition);
-
- vec3 scatteringCoefficient = uniforms.fog.scatteringFactor *
- uniforms.fog.extinctionCoefficients.rgb * density;
- vec4 extinctionCoefficient = uniforms.fog.extinctionFactor *
- uniforms.fog.extinctionCoefficients * density;
-
- vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001);
- vec4 stepExtinction = exp(-extinctionCoefficient * stepLength);
-
- vec3 stepScattering = scatteringCoefficient * (lightScattering + vec3(uniforms.fog.ambientFactor) * lightAmbient);
-
- vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb;
-#ifdef CLOUDS
- foginess += luminanceIntegral * extinctionWithClouds.rgb;
-
- if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) {
- extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction * cloudExtinction : vec4(1.0);
- receivedCloudExtinction = true;
- }
- else {
- extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0);
- }
-#else
- foginess += luminanceIntegral * extinction.rgb;
-#endif
-
- extinction *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0);
-
- currentPosition += stepVector;
-
- }
-
- return vec4(foginess * uniforms.intensity, extinction.a);
-
-}
-
-vec4 ComputeVolumetricPunctualLights(uint lightType, vec3 fragPos, float startDepth, vec2 texCoords) {
-
- vec2 resolution = vec2(imageSize(volumetricImage));
- vec3 viewPosition = vec3(globalData.ivMatrix * vec4(fragPos, 1.0));
-
- // We compute this in view space
- vec3 rayVector = fragPos;
- float rayLength = clamp(length(rayVector) - startDepth, 0.0, 100.0);
- vec3 rayDirection = normalize(rayVector);
- float stepLength = rayLength / float(uniforms.sampleCount);
- vec3 stepVector = rayDirection * stepLength;
-
- vec3 foginess = vec3(0.0);
- vec4 extinction = vec4(1.0);
- vec4 extinctionWithClouds = vec4(1.0);
-
- vec2 interleavedTexCoords = (0.5 * texCoords + 0.5) * resolution;
-
- float noiseOffset = GetInterleavedGradientNoise(interleavedTexCoords);
- vec3 currentPosition = stepVector * (noiseOffset + startDepth);
-
-#ifdef CLOUDS
- bool receivedCloudExtinction = false;
- float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoords, 0.0).a, 1.0);
-#endif
-
- for (int i = 0; i < uniforms.sampleCount; i++) {
-
- float t0 = float(i) / float(uniforms.sampleCount);
- float t1 = float(i + 1) / float(uniforms.sampleCount);
-
- t0 = t0 * t0;
- t1 = t1 * t1;
-
- float delta = t1 - t0;
- float t = t0 + delta * noiseOffset;
-
- //currentPosition = rayDirection * t * rayLength + startDepth;
- //stepLength = delta * rayLength;
-
- vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0));
-
- vec3 lightScattering = vec3(0.0);
-
- // Then all punctual lights
- for(int j = 0; j < sharedLightIndicesCount; j++) {
- int lightIdx = int(sharedLightIndices[j]);
- VolumetricLight light = volumetricLights[lightIdx];
-
- float NdotL = 1.0;
- float attenuation = 1.0;
- float sqrDistance = 1.0;
-
- float shadowValue = 1.0;
-
- float radius = light.direction.w;
- if (lightType == POINT_LIGHT) {
- vec3 pointToLight = light.location.xyz - currentPosition;
- sqrDistance = max(0.0, dot(pointToLight, pointToLight));
-
- attenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 4.0));
- if (attenuation == 0.0)
- continue;
-
- NdotL = dot(-normalize(light.location.xyz), rayDirection);
- shadowValue = GetShadowFactorPunctualLight(lightIdx, light.shadowIdx, POINT_LIGHT, false, currentPosition);
- }
- else if (lightType == SPOT_LIGHT) {
- vec3 pointToLight = light.location.xyz - currentPosition;
- sqrDistance = dot(pointToLight, pointToLight);
-
- vec3 L = pointToLight / sqrt(sqrDistance);
-
- float strength = dot(L, normalize(-light.direction.xyz));
- float angleAttenuation = saturate(strength * light.specific0 + light.specific1);
- float distAttenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 4.0));
- if (angleAttenuation == 0.0 || distAttenuation == 0.0)
- continue;
-
- NdotL = dot(-normalize(light.location.xyz), rayDirection);
- attenuation = min(distAttenuation * sqr(angleAttenuation), 1.0);
- shadowValue = GetShadowFactorPunctualLight(lightIdx, light.shadowIdx, SPOT_LIGHT, false, currentPosition);
- }
-
- // No shadows for now
- //shadowValue = 1.0;
-
- float phaseFunction = uniforms.fogEnabled > 0 ?
- ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) : 1.0;
-
- lightScattering += phaseFunction * shadowValue * light.color.rgb * attenuation * light.intensity / max(sqrDistance, 0.1);
- }
-
-#ifdef CLOUDS
- vec3 planetCenter = uniforms.planetCenterAndRadius.xyz;
- float cloudInnerRadius = uniforms.planetCenterAndRadius.w;
-
- float distToPlanetCenter = distance(worldPosition, planetCenter);
-#endif
-
- float density = uniforms.fog.density * GetVolumetricFogDensity(uniforms.fog, worldPosition);
-
- vec3 scatteringCoefficient = uniforms.fog.scatteringFactor *
- uniforms.fog.extinctionCoefficients.rgb * density;
- vec4 extinctionCoefficient = uniforms.fog.extinctionFactor *
- uniforms.fog.extinctionCoefficients * density;
-
- vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001);
- vec4 stepExtinction = exp(-extinctionCoefficient * stepLength);
-
- vec3 stepScattering = scatteringCoefficient * lightScattering;
-
- vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb;
-#ifdef CLOUDS
- foginess += luminanceIntegral * extinctionWithClouds.rgb;
-
- if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) {
- extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction * cloudExtinction : vec4(1.0);
- receivedCloudExtinction = true;
- }
- else {
- extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0);
- }
-#else
- foginess += luminanceIntegral * extinction.rgb;
-#endif
-
- extinction *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0);
-
- currentPosition += stepVector;
-
- }
-
- return vec4(foginess * uniforms.intensity, extinction.a);
-
-}
-
-float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) {
-
- float dist = -currentPosition.z;
-
-#ifndef AE_BINDLESS
- int mapIdx = lightIdx;
-#else
- int mapIdx = volumetricShadows[shadowIdx].mapIdx;
-#endif
-
- if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0)
- return 1.0;
-
- float shadowValue = 1.0;
-
-
- int cascadeIndex = 0;
- cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[0].distance ? 1 : cascadeIndex;
- cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[1].distance ? 2 : cascadeIndex;
- cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[2].distance ? 3 : cascadeIndex;
- cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[3].distance ? 4 : cascadeIndex;
- cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[4].distance ? 5 : cascadeIndex;
-
- cascadeIndex = min(volumetricShadows[shadowIdx].cascadeCount - 1, cascadeIndex);
-
- mat3x4 cascadeMatrix = volumetricShadows[shadowIdx].cascades[0].cascadeSpace;
- cascadeMatrix = cascadeIndex > 0 ? volumetricShadows[shadowIdx].cascades[1].cascadeSpace : cascadeMatrix;
- cascadeMatrix = cascadeIndex > 1 ? volumetricShadows[shadowIdx].cascades[2].cascadeSpace : cascadeMatrix;
- cascadeMatrix = cascadeIndex > 2 ? volumetricShadows[shadowIdx].cascades[3].cascadeSpace : cascadeMatrix;
- cascadeMatrix = cascadeIndex > 3 ? volumetricShadows[shadowIdx].cascades[4].cascadeSpace : cascadeMatrix;
- cascadeMatrix = cascadeIndex > 4 ? volumetricShadows[shadowIdx].cascades[5].cascadeSpace : cascadeMatrix;
-
- float positionLength = dist;
- float positionRatio = positionLength / volumetricShadows[shadowIdx].distance;
- vec3 shadowPosition = positionRatio <= 1.0 ? currentPosition : currentPosition / positionRatio;
- vec4 cascadeSpace = mat4(transpose(cascadeMatrix)) * vec4(currentPosition, 1.0);
- cascadeSpace.xyz /= cascadeSpace.w;
-
- cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5;
-
-#ifdef AE_BINDLESS
- shadowValue = texture(sampler2DArrayShadow(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowSampler),
- vec4(cascadeSpace.xy, cascadeIndex, cascadeSpace.z));
-#else
- shadowValue = texture(sampler2DArrayShadow(cascadeMaps[nonuniformEXT(mapIdx)], shadowSampler),
- vec4(cascadeSpace.xy, cascadeIndex, cascadeSpace.z));
-#endif
-
- vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0));
-
-#ifdef CLOUD_SHADOWS
- if (isMain) {
- vec3 planetCenter = uniforms.planetCenterAndRadius.xyz;
- float cloudInnerRadius = uniforms.planetCenterAndRadius.w;
- float distToPlanetCenter = distance(worldPosition, planetCenter);
- float cloudShadowValue = CalculateCloudShadow(currentPosition, uniforms.cloudShadow, cloudMap);
- cloudShadowValue = distToPlanetCenter < cloudInnerRadius ? cloudShadowValue : 1.0;
- shadowValue = min(shadowValue, cloudShadowValue);
- }
-#endif
-
- return min(shadowValue, 1.0);
-
-}
-
-float GetShadowFactorPunctualLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) {
-
- float dist = -currentPosition.z;
-
-#ifndef AE_BINDLESS
- int mapIdx = lightIdx;
-#else
- int mapIdx = volumetricShadows[shadowIdx].mapIdx;
-#endif
-
- if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0)
- return 1.0;
-
- float shadowValue = 1.0;
- if (lightType == POINT_LIGHT) {
-#ifdef AE_BINDLESS
- mat4 projectionMatrix;
- projectionMatrix[0] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0];
- projectionMatrix[1] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[1];
- projectionMatrix[2] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[2];
- projectionMatrix[3] = volumetricShadows[shadowIdx].cascades[2].cascadeSpace[0];
-
- vec4 shadowCoords = mat4(transpose(volumetricShadows[shadowIdx].cascades[0].cascadeSpace)) * vec4(currentPosition, 1.0);
- shadowCoords.y *= -1.0;
- vec4 absPosition = abs(shadowCoords);
- float depth = -max(absPosition.x, max(absPosition.y, absPosition.z));
- vec4 clip = projectionMatrix * vec4(0.0, 0.0, depth, 1.0);
- depth = clip.z / clip.w;
-
- shadowValue = clamp(texture(samplerCubeShadow(bindlessCubemaps[nonuniformEXT(mapIdx)], shadowSampler),
- vec4(shadowCoords.xyz , depth - 0.0001)), 0.0, 1.0);
-#endif
- }
- else if (lightType == SPOT_LIGHT) {
-#ifdef AE_BINDLESS
- mat4 shadowMatrix;
- shadowMatrix[0] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[0];
- shadowMatrix[1] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[1];
- shadowMatrix[2] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[2];
- shadowMatrix[3] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0];
-
- vec4 cascadeSpace = shadowMatrix * vec4(currentPosition, 1.0);
- cascadeSpace.xyz /= cascadeSpace.w;
-
- cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5;
-
- shadowValue = texture(sampler2DArrayShadow(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowSampler),
- vec4(cascadeSpace.xy, 0.0, cascadeSpace.z));
-#endif
- }
-
- return min(shadowValue, 1.0);
-
-}
\ No newline at end of file
diff --git a/data/shader/volumetric/volumetric.hsh b/data/shader/volumetric/volumetric.hsh
index 8aec38c03..b29e50a7b 100644
--- a/data/shader/volumetric/volumetric.hsh
+++ b/data/shader/volumetric/volumetric.hsh
@@ -1,4 +1,3 @@
-#include
#include <../globals.hsh>
vec2 IntersectSphere(vec3 origin, vec3 direction, vec3 pos, float radius) {
@@ -24,7 +23,7 @@ vec2 IntersectSphere(vec3 origin, vec3 direction, vec3 pos, float radius) {
return vec2(minDist, maxDist);
}
-vec3 ApplyVolumetrics(Fog fog, vec3 inputColor, vec4 volumetricFog, vec4 volumetricClouds,
+vec3 ApplyVolumetrics(vec3 inputColor, vec4 volumetricFog, vec4 volumetricClouds,
vec3 worldViewDirection, vec3 planetCenter, float innerCloudRadius) {
vec2 intersectDists = IntersectSphere(globalData.cameraLocation.xyz, worldViewDirection,
@@ -39,7 +38,7 @@ vec3 ApplyVolumetrics(Fog fog, vec3 inputColor, vec4 volumetricFog, vec4 volumet
#endif
#ifdef FOG
- vec3 outputColor = fog.density > 0.0 ? inputColor * fogExtinction + volumetricFog.rgb : inputColor;
+ vec3 outputColor = inputColor * fogExtinction + volumetricFog.rgb;
#else
vec3 outputColor = inputColor;
#endif
diff --git a/data/shader/volumetric/volumetricLights.hsh b/data/shader/volumetric/volumetricLights.hsh
new file mode 100644
index 000000000..d513bf0d4
--- /dev/null
+++ b/data/shader/volumetric/volumetricLights.hsh
@@ -0,0 +1,241 @@
+#include <../globals.hsh>
+#include <../structures.hsh>
+#include <../common/convert.hsh>
+#include <../common/utility.hsh>
+#include <../clouds/shadow.hsh>
+
+#include
+
+layout(set = 3, binding = 2) uniform sampler2D cloudMap;
+layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture;
+layout(set = 3, binding = 6) uniform sampler shadowSampler;
+layout(set = 3, binding = 12) uniform sampler shadowDepthSampler;
+
+layout(std140, set = 3, binding = 7) uniform UniformBuffer {
+ float intensity;
+ int directionalLightCount;
+ int padding0;
+ int padding1;
+ vec4 planetCenterAndRadius;
+ Fog fog;
+ CloudShadow cloudShadow;
+} uniforms;
+
+layout (std430, set = 3, binding = 8) buffer VolumetricLights {
+ VolumetricLight volumetricLights[];
+};
+
+layout (std430, set = 3, binding = 9) buffer VolumetricShadows {
+ Shadow volumetricShadows[];
+};
+
+layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer {
+ int lightIndices[];
+};
+
+const int lightCountPerTile = 63;
+
+shared uint sharedLightIndices[64];
+shared int sharedLightIndicesCount;
+
+shared VolumetricLight sharedLights[64];
+shared int sharedShadowMapIdx[64];
+shared float sharedShadowDistance[64];
+shared mat4 sharedShadowMatrix[64];
+shared vec4 sharedShadowProjection[64];
+
+// Distance in world units over which the shadow fades in behind an occluder
+const float shadowFadeDistance = 0.1;
+
+float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition);
+float GetShadowFactorPunctualLight(int sharedIdx, uint lightType, vec3 currentPosition);
+
+// Exponential depth test of a gathered 2x2 footprint, filtered bilinearly to avoid hard shadow edges in the fog
+float GetSoftShadow(vec4 occluderDistances, float receiverDistance, vec2 texelPosition) {
+
+ vec4 shadows = exp(min(occluderDistances - receiverDistance, 0.0) / shadowFadeDistance);
+
+ vec2 weight = fract(texelPosition - 0.5);
+ float top = mix(shadows.w, shadows.z, weight.x);
+ float bottom = mix(shadows.x, shadows.y, weight.x);
+ return mix(top, bottom, weight.y);
+
+}
+
+int GetLightIndicesOffset() {
+
+ int groupOffset = int(gl_WorkGroupID.x + (gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x);
+ return groupOffset * (lightCountPerTile + 1);
+
+}
+
+void LoadLightTypeData(uint requestedLightType) {
+
+ barrier();
+
+ int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z);
+ int localOffset = int(gl_LocalInvocationIndex);
+
+ if (localOffset == 0) {
+ sharedLightIndicesCount = 0;
+ }
+
+ barrier();
+
+ int groupOffset = GetLightIndicesOffset();
+ int lightCount = min(lightCountPerTile, lightIndices[groupOffset]);
+
+ for (int i = localOffset; i < lightCount; i += groupSize) {
+ uint lightIdx = lightIndices[groupOffset + i + 1];
+ uint lightType = floatBitsToUint(volumetricLights[lightIdx].color.a);
+ if (requestedLightType != lightType)
+ continue;
+
+ int idx = atomicAdd(sharedLightIndicesCount, 1);
+ if (idx < lightCountPerTile)
+ sharedLightIndices[idx] = lightIdx;
+ }
+
+ barrier();
+
+ if (localOffset == 0) {
+ sharedLightIndicesCount = min(lightCount, sharedLightIndicesCount);
+ }
+
+ barrier();
+
+ for (int i = localOffset; i < sharedLightIndicesCount; i += groupSize) {
+ int lightIdx = int(sharedLightIndices[i]);
+ VolumetricLight light = volumetricLights[lightIdx];
+ sharedLights[i] = light;
+
+ int shadowIdx = light.shadowIdx;
+ int mapIdx = -1;
+ if (shadowIdx >= 0) {
+ mapIdx = volumetricShadows[shadowIdx].mapIdx;
+ sharedShadowDistance[i] = volumetricShadows[shadowIdx].distance;
+ }
+ sharedShadowMapIdx[i] = mapIdx;
+
+ if (mapIdx < 0)
+ continue;
+
+ if (requestedLightType == POINT_LIGHT) {
+ sharedShadowMatrix[i] = mat4(transpose(volumetricShadows[shadowIdx].cascades[0].cascadeSpace));
+ vec4 projection2 = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[2];
+ vec4 projection3 = volumetricShadows[shadowIdx].cascades[2].cascadeSpace[0];
+ sharedShadowProjection[i] = vec4(projection2.z, projection3.z, projection2.w, projection3.w);
+ }
+ else if (requestedLightType == SPOT_LIGHT) {
+ mat4 shadowMatrix;
+ shadowMatrix[0] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[0];
+ shadowMatrix[1] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[1];
+ shadowMatrix[2] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[2];
+ shadowMatrix[3] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0];
+ sharedShadowMatrix[i] = shadowMatrix;
+
+ // Linearizes the shadow map depth: distance = b / (depth + a)
+ mat4 shadowRows = transpose(shadowMatrix);
+ float a = -dot(shadowRows[2].xyz, shadowRows[3].xyz) / dot(shadowRows[3].xyz, shadowRows[3].xyz);
+ float b = shadowRows[2].w + a * shadowRows[3].w;
+ sharedShadowProjection[i] = vec4(a, b, 0.0, 0.0);
+ }
+ }
+
+ barrier();
+
+}
+
+float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) {
+
+ float dist = -currentPosition.z;
+
+ if (shadowIdx < 0)
+ return 1.0;
+
+ int mapIdx = volumetricShadows[shadowIdx].mapIdx;
+
+ if (dist > volumetricShadows[shadowIdx].distance || mapIdx < 0)
+ return 1.0;
+
+ float shadowValue = 1.0;
+
+ int cascadeIndex = 0;
+ cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[0].distance ? 1 : cascadeIndex;
+ cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[1].distance ? 2 : cascadeIndex;
+ cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[2].distance ? 3 : cascadeIndex;
+ cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[3].distance ? 4 : cascadeIndex;
+ cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[4].distance ? 5 : cascadeIndex;
+
+ cascadeIndex = min(volumetricShadows[shadowIdx].cascadeCount - 1, cascadeIndex);
+
+ mat3x4 cascadeMatrix = volumetricShadows[shadowIdx].cascades[max(cascadeIndex, 0)].cascadeSpace;
+
+ vec4 cascadeSpace = mat4(transpose(cascadeMatrix)) * vec4(currentPosition, 1.0);
+ cascadeSpace.xyz /= cascadeSpace.w;
+
+ cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5;
+
+ vec2 texelPosition = cascadeSpace.xy * vec2(textureSize(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), 0).xy);
+ vec4 depths = textureGather(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler),
+ vec3(cascadeSpace.xy, cascadeIndex), 0);
+
+ // The cascades are orthographic, the depth is linear
+ float depthToDistance = 1.0 / length(cascadeMatrix[2].xyz);
+ shadowValue = GetSoftShadow(depths * depthToDistance, cascadeSpace.z * depthToDistance, texelPosition);
+
+ vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0));
+
+#ifdef CLOUD_SHADOWS
+ if (isMain) {
+ vec3 planetCenter = uniforms.planetCenterAndRadius.xyz;
+ float cloudInnerRadius = uniforms.planetCenterAndRadius.w;
+ float distToPlanetCenter = distance(worldPosition, planetCenter);
+ float cloudShadowValue = CalculateCloudShadow(currentPosition, uniforms.cloudShadow, cloudMap);
+ cloudShadowValue = distToPlanetCenter < cloudInnerRadius ? cloudShadowValue : 1.0;
+ shadowValue = min(shadowValue, cloudShadowValue);
+ }
+#endif
+
+ return min(shadowValue, 1.0);
+
+}
+
+float GetShadowFactorPunctualLight(int sharedIdx, uint lightType, vec3 currentPosition) {
+
+ float dist = -currentPosition.z;
+
+ int mapIdx = sharedShadowMapIdx[sharedIdx];
+ if (mapIdx < 0 || dist > sharedShadowDistance[sharedIdx])
+ return 1.0;
+
+ float shadowValue = 1.0;
+ if (lightType == POINT_LIGHT) {
+ vec4 shadowCoords = sharedShadowMatrix[sharedIdx] * vec4(currentPosition, 1.0);
+ shadowCoords.y *= -1.0;
+ vec4 absPosition = abs(shadowCoords);
+ float depth = -max(absPosition.x, max(absPosition.y, absPosition.z));
+ vec4 projection = sharedShadowProjection[sharedIdx];
+ depth = (projection.x * depth + projection.y) / (projection.z * depth + projection.w);
+
+ shadowValue = clamp(texture(samplerCubeShadow(bindlessCubemaps[nonuniformEXT(mapIdx)], shadowSampler),
+ vec4(shadowCoords.xyz , depth - 0.0001)), 0.0, 1.0);
+ }
+ else if (lightType == SPOT_LIGHT) {
+ vec4 cascadeSpace = sharedShadowMatrix[sharedIdx] * vec4(currentPosition, 1.0);
+ float receiverDistance = cascadeSpace.w;
+ cascadeSpace.xyz /= cascadeSpace.w;
+
+ cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5;
+
+ vec2 texelPosition = cascadeSpace.xy * vec2(textureSize(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), 0).xy);
+ vec4 depths = textureGather(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler),
+ vec3(cascadeSpace.xy, 0.0), 0);
+
+ vec4 projection = sharedShadowProjection[sharedIdx];
+ shadowValue = GetSoftShadow(projection.y / (depths + projection.x), receiverDistance, texelPosition);
+ }
+
+ return min(shadowValue, 1.0);
+
+}
diff --git a/data/shader/volumetric/volumetricResolve.csh b/data/shader/volumetric/volumetricResolve.csh
index e2b174a3f..4d0603109 100644
--- a/data/shader/volumetric/volumetricResolve.csh
+++ b/data/shader/volumetric/volumetricResolve.csh
@@ -3,11 +3,13 @@
#include <../common/utility.hsh>
#include <../common/flatten.hsh>
-#include
#include
layout (local_size_x = 8, local_size_y = 8) in;
+// Needs the work group size
+#include <../common/upsample.hsh>
+
layout(set = 3, binding = 0, rgba16f) uniform image2D resolveImage;
layout(set = 3, binding = 1) uniform sampler2D lowResVolumetricTexture;
layout(set = 3, binding = 2) uniform sampler2D lowResDepthTexture;
@@ -18,13 +20,9 @@ layout(set = 3, binding = 3) uniform sampler2D lowResVolumetricCloudsTexture;
#endif
layout(set = 3, binding = 5) uniform UniformBuffer {
- Fog fog;
vec4 planetCenter;
- vec4 mainLightColor;
- vec4 mainLightDirection;
int downsampled2x;
int cloudsEnabled;
- int fogEnabled;
float innerCloudRadius;
float planetRadius;
float cloudDistanceLimit;
@@ -35,20 +33,12 @@ shared float depths[36];
shared vec4 volumetrics[36];
shared vec4 clouds[36];
-const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2);
-const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2;
-
vec3 planetCenter = uniforms.planetCenter.xyz;
void LoadGroupSharedData() {
- ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1);
-
- // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y
- if (gl_LocalInvocationIndex < depthDataSize) {
- ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize);
- offset += workGroupOffset;
- offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0) - ivec2(1));
+ ivec2 offset;
+ if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) {
depths[gl_LocalInvocationIndex] = texelFetch(lowResDepthTexture, offset, 0).r;
volumetrics[gl_LocalInvocationIndex] = texelFetch(lowResVolumetricTexture, offset, 0);
#ifdef CLOUDS
@@ -60,40 +50,6 @@ void LoadGroupSharedData() {
}
-const ivec2 offsets[9] = ivec2[9](
- ivec2(-1, -1),
- ivec2(0, -1),
- ivec2(1, -1),
- ivec2(-1, 0),
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(-1, 1),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-const ivec2 pixelOffsets[4] = ivec2[4](
- ivec2(0, 0),
- ivec2(1, 0),
- ivec2(0, 1),
- ivec2(1, 1)
-);
-
-int NearestDepth(float referenceDepth, float[9] depthVec) {
-
- int idx = 4;
- float nearest = distance(referenceDepth, depthVec[4]);
- for (int i = 0; i < 9; i++) {
- float dist = distance(referenceDepth, depthVec[i]);
- if (dist < nearest) {
- nearest = dist;
- idx = i;
- }
- }
- return idx;
-
-}
-
void Upsample2x(float referenceDepth, vec2 texCoord, out vec4 volumetric, out vec4 volumetricClouds) {
ivec2 pixel = ivec2(gl_LocalInvocationID) / 2 + ivec2(1);
@@ -162,8 +118,8 @@ void main() {
if (uniforms.downsampled2x > 0) LoadGroupSharedData();
ivec2 pixel = ivec2(gl_GlobalInvocationID);
- if (pixel.x > imageSize(resolveImage).x ||
- pixel.y > imageSize(resolveImage).y)
+ if (pixel.x >= imageSize(resolveImage).x ||
+ pixel.y >= imageSize(resolveImage).y)
return;
vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(resolveImage));
@@ -188,28 +144,7 @@ void main() {
vec3 resolve = imageLoad(resolveImage, pixel).rgb;
-#ifndef RAYMARCHED_FOG
- float LdotV = dot(worldDirection, normalize(uniforms.mainLightDirection.xyz));
- float phaseFunction = ComputeScattering(uniforms.fog.scatteringAnisotropy, LdotV);
-
- vec3 worldPosition = vec3(globalData.ivMatrix * vec4(viewPosition, 1.0));
- volumetricFog.a = ComputeVolumetricFog(uniforms.fog, globalData.cameraLocation.xyz, worldPosition);
-
- vec3 lightPosition = worldPosition - 10000.0 * normalize(uniforms.mainLightDirection.xyz);
- lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0));
- float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition);
-
- vec3 scatteringCoefficient = uniforms.fog.scatteringFactor *
- uniforms.fog.extinctionCoefficients.rgb;
-
- vec3 lightScattering = phaseFunction * uniforms.mainLightColor.rgb;
-
- vec3 scattering = scatteringCoefficient * (lightScattering + vec3(uniforms.fog.ambientFactor));
-
- volumetricFog.rgb = scattering * clamp(1.0 - volumetricFog.a, 0.0, 1.0);
-#endif
-
- resolve = ApplyVolumetrics(uniforms.fog, resolve, volumetricFog, volumetricClouds,
+ resolve = ApplyVolumetrics(resolve, volumetricFog, volumetricClouds,
worldDirection, planetCenter, uniforms.innerCloudRadius);
imageStore(resolveImage, pixel, vec4(resolve, 1.0));
diff --git a/data/shader/wind.hsh b/data/shader/wind.hsh
index a2afbd986..f3e15e74c 100644
--- a/data/shader/wind.hsh
+++ b/data/shader/wind.hsh
@@ -10,12 +10,21 @@ vec4 SmoothCurve( vec4 x ) { return x * x *( 3.0 - 2.0 * x ); }
vec4 TriangleWave( vec4 x ) { return abs( fract( x + 0.5 ) * 2.0 - 1.0 ); }
vec4 SmoothTriangleWave( vec4 x ) { return SmoothCurve( TriangleWave( x ) ); }
+// The scene wind in the object space of a vegetation instance
+vec2 GetWindDirection(mat4 modelMatrix) {
+
+ return normalize((inverse(mat3(modelMatrix)) * vec3(globalData.windDir.x, 0.0, globalData.windDir.y)).xz);
+
+}
+
vec3 WindAnimation(sampler2D noiseTexture, vec3 position, vec2 windDir,
float bendFactor, float wiggleFactor, float lod, float animTime, vec3 location) {
vec3 originalPos = position;
float windSpeed = globalData.windSpeed;
+ // Above a breeze the bending grows linearly with the speed, so strong wind and storms visibly bend vegetation
+ float windAmplitude = max(sqrt(windSpeed), windSpeed * 0.5);
float centerDistance = length(position.xz);
float height = max(0.0, position.y * bendFactor * 0.5);
@@ -28,10 +37,10 @@ vec3 WindAnimation(sampler2D noiseTexture, vec3 position, vec2 windDir,
mainBending *= mainBending;
mainBending = mainBending * mainBending - mainBending;
- position.xz += windDir * mainBending * sqrt(windSpeed);
+ position.xz += windDir * mainBending * windAmplitude;
position.xyz = normalize(position - vec3(originalPos.x, 0.0, originalPos.z)) * abs(originalPos.y) + vec3(originalPos.x, 0.0, originalPos.z);
- float branchAmp = .25 * sqrt(windSpeed);
+ float branchAmp = .25 * windAmplitude;
float detailAmp = 0.02;
float edgeAtten = 0.5;
float speed = 0.2;
diff --git a/libs/ImguiExtension/CMakeLists.txt b/libs/ImguiExtension/CMakeLists.txt
index d792b3a74..6b8415aca 100644
--- a/libs/ImguiExtension/CMakeLists.txt
+++ b/libs/ImguiExtension/CMakeLists.txt
@@ -29,5 +29,5 @@ find_package(implot CONFIG REQUIRED)
# We cam do this here, since the ImguiExtension dependency uses the engine and therefore is always included
# after the engine is added
add_library(${PROJECT_NAME} STATIC ${IMGUI_SOURCE_FILES})
-target_compile_definitions(${PROJECT_NAME} PUBLIC ${ATLAS_ENGINE_COMPILE_DEFINITIONS})
-target_link_libraries(${PROJECT_NAME} imgui::imgui implot::implot volk::volk volk::volk_headers SDL2::SDL2 GPUOpen::VulkanMemoryAllocator Jolt::Jolt)
\ No newline at end of file
+target_compile_definitions(${PROJECT_NAME} PUBLIC $)
+target_link_libraries(${PROJECT_NAME} imgui::imgui implot::implot volk::volk volk::volk_headers SDL3::SDL3 GPUOpen::VulkanMemoryAllocator Jolt::Jolt)
\ No newline at end of file
diff --git a/libs/ImguiExtension/ImguiWrapper.cpp b/libs/ImguiExtension/ImguiWrapper.cpp
index e76c876b7..66b102f02 100644
--- a/libs/ImguiExtension/ImguiWrapper.cpp
+++ b/libs/ImguiExtension/ImguiWrapper.cpp
@@ -1,18 +1,23 @@
-// Based on SDL2 Imgui backend: https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp
+// Based on SDL3 Imgui backend: https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl3.cpp
#include "ImguiWrapper.h"
#ifndef AE_OS_APPLE_MOBILE
#define VK_NO_PROTOTYPES
#endif
-#include
+#include
+#include
#include
+#include
#include
+#include
+
namespace Atlas::ImguiExtension {
void ImguiWrapper::Load(Atlas::Window *window) {
+ this->window = window;
ImPlot::CreateContext();
// Setup back-end capabilities flags
@@ -21,20 +26,27 @@ namespace Atlas::ImguiExtension {
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_atlas";
- /*
- io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
- io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
- io.ClipboardUserData = NULL;
- */
-
- mouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
- mouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
- mouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
- mouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
- mouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
- mouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
- mouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
- mouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
+ ImGuiPlatformIO &platformIO = ImGui::GetPlatformIO();
+ platformIO.Platform_ClipboardUserData = this;
+ platformIO.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) {
+ SDL_SetClipboardText(text);
+ };
+ platformIO.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char* {
+ auto wrapper = static_cast(ImGui::GetPlatformIO().Platform_ClipboardUserData);
+ // SDL hands out a copy that has to stay valid until ImGui asks again
+ SDL_free(wrapper->clipboardText);
+ wrapper->clipboardText = SDL_GetClipboardText();
+ return wrapper->clipboardText;
+ };
+
+ mouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT);
+ mouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT);
+ mouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE);
+ mouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE);
+ mouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE);
+ mouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE);
+ mouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE);
+ mouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER);
// Subscribe to events
auto windowEventHandler = std::bind(&ImguiWrapper::WindowHandler, this, std::placeholders::_1);
@@ -55,7 +67,9 @@ namespace Atlas::ImguiExtension {
auto textInputEventHandler = std::bind(&ImguiWrapper::TextInputHandler, this, std::placeholders::_1);
textInputID = Atlas::Events::EventManager::TextInputEventDelegate.Subscribe(textInputEventHandler);
- RecreateImGuiResources();
+ // The resources might have been created already, e.g. for the fonts of the application
+ if (!initialized)
+ RecreateImGuiResources();
}
@@ -66,13 +80,34 @@ namespace Atlas::ImguiExtension {
device->WaitForIdle();
- // Unsubscribe from all events
ImGui_ImplVulkan_Shutdown();
+ if (window) {
+ window->windowEventDelegate.Unsubscribe(windowID);
+ window->mouseButtonEventDelegate.Unsubscribe(mouseButtonID);
+ window->mouseMotionEventDelegate.Unsubscribe(mouseMotionID);
+ window->mouseWheelEventDelegate.Unsubscribe(mouseWheelID);
+ window = nullptr;
+ }
+ Atlas::Events::EventManager::KeyboardEventDelegate.Unsubscribe(keyboardID);
+ Atlas::Events::EventManager::TextInputEventDelegate.Unsubscribe(textInputID);
+ for (auto& cursor : mouseCursors) {
+ SDL_DestroyCursor(cursor);
+ cursor = nullptr;
+ }
+
ImPlot::DestroyContext();
pool.reset();
+ for (auto list : drawListCopies)
+ IM_DELETE(list);
+ drawListCopies.clear();
+ drawDataCopy.Clear();
+
+ SDL_free(clipboardText);
+ clipboardText = nullptr;
+
initialized = false;
}
@@ -83,9 +118,9 @@ namespace Atlas::ImguiExtension {
io.DeltaTime = deltaTime;
- auto w = (float) window->GetWidth();
- auto h = (float) window->GetHeight();
- auto size = glm::vec2(window->GetDrawableSize());
+ auto w = (float) window->GetWidth() / scale;
+ auto h = (float) window->GetHeight() / scale;
+ auto size = vec2(window->GetDrawableSize());
io.DisplaySize = ImVec2(w, h);
if (w > 0.0f && h > 0.0f)
io.DisplayFramebufferScale = ImVec2(size.x / w, size.y / h);
@@ -117,6 +152,8 @@ namespace Atlas::ImguiExtension {
void ImguiWrapper::Render(bool clearSwapChain) {
+ Atlas::CPUProfiler::Scope profilerScope("ImGui");
+
ImGuiIO &io = ImGui::GetIO();
ImGui_ImplVulkan_NewFrame();
@@ -131,15 +168,15 @@ namespace Atlas::ImguiExtension {
commandList->BeginCommands();
- Atlas::Graphics::Profiler::BeginThread("ImGui thread", commandList);
- Atlas::Graphics::Profiler::BeginQuery("ImGui");
+ Atlas::GPUProfiler::BeginThread("ImGui thread", commandList);
+ Atlas::GPUProfiler::BeginQuery("ImGui");
commandList->BeginRenderPass(swapChain, clearSwapChain);
- ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), commandList->commandBuffer);
+ ImGui_ImplVulkan_RenderDrawData(hasDrawDataCopy ? &drawDataCopy : ImGui::GetDrawData(), commandList->commandBuffer);
commandList->EndRenderPass();
- Atlas::Graphics::Profiler::EndQuery();
- Atlas::Graphics::Profiler::EndThread();
+ Atlas::GPUProfiler::EndQuery();
+ Atlas::GPUProfiler::EndThread();
commandList->EndCommands();
@@ -147,15 +184,56 @@ namespace Atlas::ImguiExtension {
}
- void ImguiWrapper::RecreateImGuiResources() {
+ void ImguiWrapper::CopyDrawData() {
- if (initialized) {
- ImGui_ImplVulkan_Shutdown();
+ auto copyVector = [](auto& destination, const auto& source) {
+ destination.resize(source.Size);
+ if (source.Size)
+ std::memcpy(destination.Data, source.Data, source.size_in_bytes());
+ };
+
+ drawDataCopy.Clear();
+ hasDrawDataCopy = true;
+
+ auto drawData = ImGui::GetDrawData();
+ if (!drawData)
+ return;
+
+ drawDataCopy.Valid = drawData->Valid;
+ drawDataCopy.CmdListsCount = drawData->CmdListsCount;
+ drawDataCopy.TotalIdxCount = drawData->TotalIdxCount;
+ drawDataCopy.TotalVtxCount = drawData->TotalVtxCount;
+ drawDataCopy.DisplayPos = drawData->DisplayPos;
+ drawDataCopy.DisplaySize = drawData->DisplaySize;
+ drawDataCopy.FramebufferScale = drawData->FramebufferScale;
+ drawDataCopy.OwnerViewport = drawData->OwnerViewport;
+
+ for (int32_t i = 0; i < drawData->CmdLists.Size; i++) {
+ auto source = drawData->CmdLists[i];
+ if (i >= drawListCopies.Size)
+ drawListCopies.push_back(IM_NEW(ImDrawList)(source->_Data));
+
+ auto copy = drawListCopies[i];
+ copyVector(copy->CmdBuffer, source->CmdBuffer);
+ copyVector(copy->IdxBuffer, source->IdxBuffer);
+ copyVector(copy->VtxBuffer, source->VtxBuffer);
+ copy->Flags = source->Flags;
+ drawDataCopy.CmdLists.push_back(copy);
}
+ }
+
+ void ImguiWrapper::RecreateImGuiResources() {
+
auto instance = Atlas::Graphics::Instance::DefaultInstance;
auto device = instance->GetGraphicsDevice();
+ // Frames in flight still use the old font texture
+ if (initialized) {
+ device->WaitForIdle();
+ ImGui_ImplVulkan_Shutdown();
+ }
+
auto desc = Atlas::Graphics::DescriptorPoolDesc{
.freeDescriptorSets = true
};
@@ -185,12 +263,27 @@ namespace Atlas::ImguiExtension {
//clear font textures from cpu data
ImGui_ImplVulkan_DestroyFontUploadObjects();
+ // The backend only keeps the handle, a queue left locked blocks the render thread forever
+ queue.Unlock();
+
imageViewToDescriptorSetMap.clear();
initialized = true;
}
+ void ImguiWrapper::SetScale(float scale) {
+
+ this->scale = scale;
+
+ }
+
+ float ImguiWrapper::GetScale() const {
+
+ return scale;
+
+ }
+
ImTextureID ImguiWrapper::GetTextureId(const Atlas::Texture::Texture* texture,
VkImageLayout layout) {
@@ -238,7 +331,7 @@ namespace Atlas::ImguiExtension {
ImGuiIO &io = ImGui::GetIO();
- io.MousePos = ImVec2((float) event.x, (float) event.y);
+ io.MousePos = ImVec2(event.x / scale, event.y / scale);
}
@@ -246,10 +339,8 @@ namespace Atlas::ImguiExtension {
ImGuiIO &io = ImGui::GetIO();
- if (event.x > 0) io.MouseWheelH += 1;
- if (event.x < 0) io.MouseWheelH -= 1;
- if (event.y > 0) io.MouseWheel += 1;
- if (event.y < 0) io.MouseWheel -= 1;
+ io.MouseWheelH += event.x;
+ io.MouseWheel += event.y;
}
@@ -280,12 +371,12 @@ namespace Atlas::ImguiExtension {
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) {
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
- SDL_ShowCursor(SDL_FALSE);
+ SDL_HideCursor();
} else {
// Show OS mouse cursor
SDL_SetCursor(
mouseCursors[imgui_cursor] ? mouseCursors[imgui_cursor] : mouseCursors[ImGuiMouseCursor_Arrow]);
- SDL_ShowCursor(SDL_TRUE);
+ SDL_ShowCursor();
}
}
@@ -323,7 +414,7 @@ namespace Atlas::ImguiExtension {
return ImGuiKey_Enter;
case SDLK_ESCAPE:
return ImGuiKey_Escape;
- case SDLK_QUOTE:
+ case SDLK_APOSTROPHE:
return ImGuiKey_Apostrophe;
case SDLK_COMMA:
return ImGuiKey_Comma;
@@ -343,7 +434,7 @@ namespace Atlas::ImguiExtension {
return ImGuiKey_Backslash;
case SDLK_RIGHTBRACKET:
return ImGuiKey_RightBracket;
- case SDLK_BACKQUOTE:
+ case SDLK_GRAVE:
return ImGuiKey_GraveAccent;
case SDLK_CAPSLOCK:
return ImGuiKey_CapsLock;
@@ -427,57 +518,57 @@ namespace Atlas::ImguiExtension {
return ImGuiKey_8;
case SDLK_9:
return ImGuiKey_9;
- case SDLK_a:
+ case SDLK_A:
return ImGuiKey_A;
- case SDLK_b:
+ case SDLK_B:
return ImGuiKey_B;
- case SDLK_c:
+ case SDLK_C:
return ImGuiKey_C;
- case SDLK_d:
+ case SDLK_D:
return ImGuiKey_D;
- case SDLK_e:
+ case SDLK_E:
return ImGuiKey_E;
- case SDLK_f:
+ case SDLK_F:
return ImGuiKey_F;
- case SDLK_g:
+ case SDLK_G:
return ImGuiKey_G;
- case SDLK_h:
+ case SDLK_H:
return ImGuiKey_H;
- case SDLK_i:
+ case SDLK_I:
return ImGuiKey_I;
- case SDLK_j:
+ case SDLK_J:
return ImGuiKey_J;
- case SDLK_k:
+ case SDLK_K:
return ImGuiKey_K;
- case SDLK_l:
+ case SDLK_L:
return ImGuiKey_L;
- case SDLK_m:
+ case SDLK_M:
return ImGuiKey_M;
- case SDLK_n:
+ case SDLK_N:
return ImGuiKey_N;
- case SDLK_o:
+ case SDLK_O:
return ImGuiKey_O;
- case SDLK_p:
+ case SDLK_P:
return ImGuiKey_P;
- case SDLK_q:
+ case SDLK_Q:
return ImGuiKey_Q;
- case SDLK_r:
+ case SDLK_R:
return ImGuiKey_R;
- case SDLK_s:
+ case SDLK_S:
return ImGuiKey_S;
- case SDLK_t:
+ case SDLK_T:
return ImGuiKey_T;
- case SDLK_u:
+ case SDLK_U:
return ImGuiKey_U;
- case SDLK_v:
+ case SDLK_V:
return ImGuiKey_V;
- case SDLK_w:
+ case SDLK_W:
return ImGuiKey_W;
- case SDLK_x:
+ case SDLK_X:
return ImGuiKey_X;
- case SDLK_y:
+ case SDLK_Y:
return ImGuiKey_Y;
- case SDLK_z:
+ case SDLK_Z:
return ImGuiKey_Z;
case SDLK_F1:
return ImGuiKey_F1;
@@ -512,10 +603,10 @@ namespace Atlas::ImguiExtension {
void ImguiWrapper::UpdateKeyModifiers(uint16_t keyModifier) {
ImGuiIO &io = ImGui::GetIO();
- io.AddKeyEvent(ImGuiMod_Ctrl, (keyModifier & KMOD_CTRL) != 0);
- io.AddKeyEvent(ImGuiMod_Shift, (keyModifier & KMOD_SHIFT) != 0);
- io.AddKeyEvent(ImGuiMod_Alt, (keyModifier & KMOD_ALT) != 0);
- io.AddKeyEvent(ImGuiMod_Super, (keyModifier & KMOD_GUI) != 0);
+ io.AddKeyEvent(ImGuiMod_Ctrl, (keyModifier & SDL_KMOD_CTRL) != 0);
+ io.AddKeyEvent(ImGuiMod_Shift, (keyModifier & SDL_KMOD_SHIFT) != 0);
+ io.AddKeyEvent(ImGuiMod_Alt, (keyModifier & SDL_KMOD_ALT) != 0);
+ io.AddKeyEvent(ImGuiMod_Super, (keyModifier & SDL_KMOD_GUI) != 0);
}
diff --git a/libs/ImguiExtension/ImguiWrapper.h b/libs/ImguiExtension/ImguiWrapper.h
index a654a3c98..797b595de 100644
--- a/libs/ImguiExtension/ImguiWrapper.h
+++ b/libs/ImguiExtension/ImguiWrapper.h
@@ -26,8 +26,17 @@ namespace Atlas::ImguiExtension {
void Render(bool clearSwapChain = false);
+ // Copies the draw data after ImGui::Render(), Render() then draws the copy. A render thread can draw it
+ // while the next frame is built, but must not render while it is copied
+ void CopyDrawData();
+
void RecreateImGuiResources();
+ // Scales the whole interface, ImGui works with a smaller display and a larger framebuffer scale
+ void SetScale(float scale);
+
+ float GetScale() const;
+
ImTextureID GetTextureId(const Atlas::Texture::Texture* texture,
VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
@@ -56,6 +65,7 @@ namespace Atlas::ImguiExtension {
void UpdateMouseCursor();
SDL_Cursor *mouseCursors[ImGuiMouseCursor_COUNT];
+ char *clipboardText = nullptr;
int32_t windowID = 0;
int32_t mouseMotionID = 0;
@@ -65,10 +75,16 @@ namespace Atlas::ImguiExtension {
int32_t textInputID = 0;
Atlas::Window *window = nullptr;
+ float scale = 1.0f;
Atlas::Ref pool = nullptr;
std::unordered_map imageViewToDescriptorSetMap;
+ ImDrawData drawDataCopy;
+ // Reused by the copies, such that their buffers aren't allocated every frame
+ ImVector drawListCopies;
+ bool hasDrawDataCopy = false;
+
bool initialized = false;
};
diff --git a/libs/ImguiExtension/Panels.h b/libs/ImguiExtension/Panels.h
index 27ec06544..7cbca9ac9 100644
--- a/libs/ImguiExtension/Panels.h
+++ b/libs/ImguiExtension/Panels.h
@@ -10,6 +10,7 @@
#include "panels/RTGIPanel.h"
#include "panels/MaterialPanel.h"
#include "panels/MaterialsPanel.h"
-#include "panels/GPUProfilerPanel.h"
+#include "panels/ProfilerPanel.h"
#include "panels/WindPanel.h"
#include "panels/SkyPanel.h"
+#include "panels/OceanPanel.h"
diff --git a/libs/ImguiExtension/UiElements.cpp b/libs/ImguiExtension/UiElements.cpp
index da6132ffd..1cb3516be 100644
--- a/libs/ImguiExtension/UiElements.cpp
+++ b/libs/ImguiExtension/UiElements.cpp
@@ -1,7 +1,15 @@
#include "UiElements.h"
+#include
+#include
+
+#include
+#include
+
namespace Atlas::ImguiExtension {
+ UIElements::PropertySearch UIElements::propertySearch;
+
void UIElements::TexturePreview(Ref& wrapper, const Texture::Texture* texture) {
auto lineHeight = ImGui::GetTextLineHeightWithSpacing();
@@ -53,4 +61,469 @@ namespace Atlas::ImguiExtension {
}
+ bool UIElements::BeginProperties(const char* id) {
+
+ // Content hidden by a search still shows the matching rows of its tables
+ auto window = ImGui::GetCurrentWindow();
+ if (IsContentHidden(window))
+ window->SkipItems = false;
+
+ auto start = ImGui::GetCursorScreenPos();
+ if (!ImGui::BeginTable(id, 2, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoSavedSettings)) {
+ UpdateContentVisibility();
+ return false;
+ }
+
+ SetupPropertyLabelColumn("Label");
+ ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch);
+ if (propertySearch.active)
+ propertySearch.tables.push_back({ .start = start });
+ return true;
+
+ }
+
+ void UIElements::PropertyLabel(const char* label, const char* tooltip) {
+
+ auto labelEnd = ImGui::FindRenderedTextEnd(label);
+ auto highlight = false;
+ if (propertySearch.active) {
+ auto& search = propertySearch;
+ const auto& scope = search.scopes[search.depth - 1];
+ if (!scope.matches && !scope.sectionMatches) {
+ if (!MatchesSearchWords(std::string_view(label, labelEnd), tooltip ? tooltip : std::string_view())) {
+ // Like ImGui between rows, the value and everything up to the next row is skipped
+ HideItems(ImGui::GetCurrentWindow());
+ return;
+ }
+ highlight = true;
+ }
+ CountPropertyMatch();
+ if (!search.tables.empty())
+ search.tables.back().shownRows++;
+ }
+
+ ImGui::TableNextRow();
+ ImGui::TableSetColumnIndex(0);
+
+ // Muted and centered on the value, long labels are cut off with an ellipsis and shown in full in the tooltip
+ auto width = ImGui::GetContentRegionAvail().x;
+ auto pos = ImGui::GetCursorScreenPos();
+ auto textSize = ImGui::CalcTextSize(label, nullptr, true);
+ MeasurePropertyLabel(textSize.x);
+ ImGui::Dummy(ImVec2(width, ImGui::GetFrameHeight()));
+ auto textPos = ImVec2(pos.x, pos.y + ImGui::GetStyle().FramePadding.y);
+ auto textEnd = ImVec2(pos.x + width, textPos.y + ImGui::GetTextLineHeight());
+ // Matches of a search stand out
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(highlight ? ImGuiCol_Text : ImGuiCol_TextDisabled));
+ ImGui::RenderTextEllipsis(ImGui::GetWindowDrawList(), textPos, textEnd, textEnd.x, textEnd.x, label,
+ labelEnd, &textSize);
+ ImGui::PopStyleColor();
+ if (tooltip)
+ ImGui::SetItemTooltip("%s", tooltip);
+ else if (textSize.x > width)
+ ImGui::SetItemTooltip("%s", label);
+
+ ImGui::TableSetColumnIndex(1);
+ ImGui::SetNextItemWidth(-FLT_MIN);
+
+ }
+
+ void UIElements::EndProperties() {
+
+ ImGui::EndTable();
+
+ auto& search = propertySearch;
+ if (!search.active || search.tables.empty())
+ return;
+
+ auto table = search.tables.back();
+ search.tables.pop_back();
+ if (table.shownRows == 0)
+ ImGui::SetCursorScreenPos(table.start);
+ UpdateContentVisibility();
+
+ }
+
+ void UIElements::SetupPropertyLabelColumn(const char* name) {
+
+ // At most 40% of the width, which is also the width before the labels of the window were measured
+ auto labelWidth = UpdatePropertyLabelWidth(0.0f);
+ auto maxWidth = 0.4f * ImGui::GetContentRegionAvail().x;
+ auto width = labelWidth > 0.0f ? std::min(labelWidth + 2.0f * ImGui::GetStyle().ItemSpacing.x, maxWidth) : maxWidth;
+
+ ImGui::TableSetupColumn(name, ImGuiTableColumnFlags_WidthFixed, width);
+ // A new table has no maximum width yet, which would clamp the width, the initial width applies instead
+ auto table = ImGui::GetCurrentTable();
+ if (!table->IsInitializing)
+ ImGui::TableSetColumnWidth(table->DeclColumnsCount - 1, width);
+
+ }
+
+ void UIElements::MeasurePropertyLabel(float labelWidth) {
+
+ UpdatePropertyLabelWidth(labelWidth);
+
+ }
+
+ void UIElements::PropertySection(const char* label) {
+
+ auto& search = propertySearch;
+ if (!search.active) {
+ ImGui::SeparatorText(label);
+ return;
+ }
+
+ auto& scope = search.scopes[search.depth - 1];
+ auto labelEnd = ImGui::FindRenderedTextEnd(label);
+ scope.section.clear();
+ scope.sectionMatches = MatchesSearchWords(std::string_view(label, labelEnd));
+ scope.section.assign(label, labelEnd);
+ if (scope.sectionMatches)
+ CountPropertyMatch();
+ UpdateContentVisibility();
+
+ }
+
+ void UIElements::BeginPropertySearch(const std::string& text, uint32_t scope) {
+
+ auto& search = propertySearch;
+ AE_ASSERT(!search.active && "Property searches can't be nested");
+
+ if (text != search.text) {
+ search.text = text;
+ search.words = SplitWords(text);
+ }
+ if (search.words.empty())
+ return;
+
+ search.active = true;
+ search.anyMatch = false;
+ search.depth = 0;
+ search.blockDepth = 0;
+ search.tables.clear();
+ // Never 0, the value of groups which weren't counted yet
+ search.key = ImHashData(&scope, sizeof(scope), ImHashStr(text.c_str())) | 1u;
+ PushPropertyScope(0, {}, false);
+
+ }
+
+ bool UIElements::EndPropertySearch() {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return true;
+
+ AE_ASSERT(search.depth == 1 && search.blockDepth == 0 && search.tables.empty() &&
+ "Property groups, blocks and tables have to end before the search");
+
+ search.active = false;
+ search.depth = 0;
+ return search.anyMatch;
+
+ }
+
+ bool UIElements::PropertySearchBar(const char* id, std::string& text, bool focus) {
+
+ if (focus)
+ ImGui::SetKeyboardFocusHere();
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ return ImGui::InputTextWithHint(id, "Search properties...", &text, ImGuiInputTextFlags_EscapeClearsAll);
+
+ }
+
+ bool UIElements::BeginPropertyGroup(const char* name) {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return true;
+
+ // Nothing is counted in hidden windows or rows
+ auto window = ImGui::GetCurrentWindow();
+ auto contentHidden = IsContentHidden(window);
+ if (window->SkipItems && !contentHidden)
+ return false;
+
+ const auto& parent = search.scopes[search.depth - 1];
+ auto id = ImGui::GetID(name);
+ auto nameView = std::string_view(name, ImGui::FindRenderedTextEnd(name));
+ auto nameMatches = MatchesSearchWords(nameView);
+ auto matches = nameMatches || parent.matches || parent.sectionMatches;
+
+ // The matches of the last time the group was drawn with this search
+ auto recount = false;
+ auto& storage = window->StateStorage;
+ if (!matches && storage.GetInt(ImHashStr("Search key", 0, id)) == int32_t(search.key) &&
+ storage.GetInt(ImHashStr("Search matches", 0, id)) == 0) {
+ if (ImGui::GetFrameCount() - storage.GetInt(ImHashStr("Search frame", 0, id)) < recountInterval)
+ return false;
+ recount = true;
+ }
+
+ auto& scope = PushPropertyScope(id, nameView, matches);
+ if (nameMatches)
+ CountPropertyMatch();
+
+ // The header is shown in hidden content
+ if (contentHidden)
+ window->SkipItems = false;
+
+ // Content can change without a change of the search, e.g. when a resource is loaded. The group is drawn
+ // invisibly then and takes no space without matches
+ if (recount) {
+ scope.recount = true;
+ scope.start = ImGui::GetCursorScreenPos();
+ scope.maxPos = window->DC.CursorMaxPos;
+ ImGui::PushClipRect(scope.start, scope.start, true);
+ }
+
+ return true;
+
+ }
+
+ void UIElements::EndPropertyGroup() {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return;
+
+ AE_ASSERT(search.depth > 1 && "EndPropertyGroup without a group");
+
+ auto& scope = search.scopes[search.depth - 1];
+ if (scope.contentWindow)
+ EndPropertyContent();
+
+ auto window = ImGui::GetCurrentWindow();
+ if (scope.recount) {
+ ImGui::PopClipRect();
+ if (scope.matchCount == 0) {
+ ImGui::SetCursorScreenPos(scope.start);
+ window->DC.CursorMaxPos = scope.maxPos;
+ }
+ }
+
+ if (scope.counted) {
+ auto& storage = window->StateStorage;
+ storage.SetInt(ImHashStr("Search key", 0, scope.id), int32_t(search.key));
+ storage.SetInt(ImHashStr("Search matches", 0, scope.id), scope.matchCount);
+ storage.SetInt(ImHashStr("Search frame", 0, scope.id), ImGui::GetFrameCount());
+ }
+
+ search.depth--;
+ UpdateContentVisibility();
+
+ }
+
+ ImGuiTreeNodeFlags UIElements::PropertyGroupHeaderFlags() {
+
+ // Leaf nodes are always open and keep the open state of the node
+ return propertySearch.active ? ImGuiTreeNodeFlags_Leaf : ImGuiTreeNodeFlags_None;
+
+ }
+
+ void UIElements::BeginPropertyContent() {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return;
+
+ auto& scope = search.scopes[search.depth - 1];
+ AE_ASSERT(search.depth > 1 && !scope.contentWindow && "Property content needs a group and can't be nested");
+
+ scope.contentWindow = ImGui::GetCurrentWindow();
+ scope.contentSkipItems = scope.contentWindow->SkipItems;
+ if (scope.contentSkipItems)
+ scope.counted = false;
+ UpdateContentVisibility();
+
+ }
+
+ void UIElements::EndPropertyContent() {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return;
+
+ auto& scope = search.scopes[search.depth - 1];
+ AE_ASSERT(scope.contentWindow && "EndPropertyContent without BeginPropertyContent");
+
+ scope.contentWindow->SkipItems = scope.contentSkipItems;
+ scope.contentWindow = nullptr;
+
+ }
+
+ bool UIElements::BeginPropertyBlock(const char* label) {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return true;
+
+ // Blocks in hidden rows stay hidden
+ auto window = ImGui::GetCurrentWindow();
+ auto contentHidden = IsContentHidden(window);
+ if (window->SkipItems && !contentHidden)
+ return false;
+
+ const auto& scope = search.scopes[search.depth - 1];
+ if (!scope.matches && !scope.sectionMatches &&
+ !MatchesSearchWords(std::string_view(label, ImGui::FindRenderedTextEnd(label))))
+ return false;
+
+ CountPropertyMatch();
+ if (contentHidden)
+ window->SkipItems = false;
+ search.blockDepth++;
+ return true;
+
+ }
+
+ void UIElements::EndPropertyBlock() {
+
+ auto& search = propertySearch;
+ if (!search.active)
+ return;
+
+ search.blockDepth--;
+ UpdateContentVisibility();
+
+ }
+
+ bool UIElements::MatchesSearch(std::string_view text, std::string_view search) {
+
+ size_t start = 0;
+ while (start < search.size()) {
+ auto end = search.find_first_of(" \t", start);
+ if (end == std::string_view::npos)
+ end = search.size();
+ if (end > start && !ContainsIgnoreCase(text, search.substr(start, end - start)))
+ return false;
+ start = end + 1;
+ }
+ return true;
+
+ }
+
+ UIElements::PropertyScope& UIElements::PushPropertyScope(ImGuiID id, std::string_view name, bool matches) {
+
+ auto& search = propertySearch;
+ if (search.depth == search.scopes.size())
+ search.scopes.emplace_back();
+
+ auto& scope = search.scopes[search.depth++];
+ scope.id = id;
+ scope.name.assign(name);
+ scope.matches = matches;
+ scope.matchCount = 0;
+ scope.counted = true;
+ scope.recount = false;
+ scope.section.clear();
+ scope.sectionMatches = false;
+ scope.contentWindow = nullptr;
+ scope.contentSkipItems = false;
+ return scope;
+
+ }
+
+ bool UIElements::MatchesSearchWords(std::string_view label, std::string_view tooltip) {
+
+ const auto& search = propertySearch;
+ for (const auto& word : search.words) {
+ auto found = ContainsIgnoreCase(label, word) || ContainsIgnoreCase(tooltip, word);
+ for (size_t i = 0; i < search.depth && !found; i++)
+ found = ContainsIgnoreCase(search.scopes[i].name, word) || ContainsIgnoreCase(search.scopes[i].section, word);
+ if (!found)
+ return false;
+ }
+ return true;
+
+ }
+
+ bool UIElements::ContainsIgnoreCase(std::string_view text, std::string_view word) {
+
+ auto iter = std::search(text.begin(), text.end(), word.begin(), word.end(), [](char character0, char character1) {
+ return std::tolower(static_cast(character0)) == std::tolower(static_cast(character1));
+ });
+ return iter != text.end() || word.empty();
+
+ }
+
+ std::vector UIElements::SplitWords(std::string_view text) {
+
+ std::vector words;
+ size_t start = 0;
+ while (start < text.size()) {
+ auto end = text.find_first_of(" \t", start);
+ if (end == std::string_view::npos)
+ end = text.size();
+ if (end > start)
+ words.emplace_back(text.substr(start, end - start));
+ start = end + 1;
+ }
+ return words;
+
+ }
+
+ void UIElements::CountPropertyMatch() {
+
+ auto& search = propertySearch;
+ search.anyMatch = true;
+ for (size_t i = 0; i < search.depth; i++)
+ search.scopes[i].matchCount++;
+
+ }
+
+ bool UIElements::IsContentHidden(ImGuiWindow* window) {
+
+ const auto& search = propertySearch;
+ if (!search.active || !search.tables.empty() || search.blockDepth > 0)
+ return false;
+
+ const auto& scope = search.scopes[search.depth - 1];
+ return scope.contentWindow == window && !scope.contentSkipItems;
+
+ }
+
+ void UIElements::HideItems(ImGuiWindow* window) {
+
+ // Item queries like IsItemHovered would otherwise refer to the last shown item
+ window->SkipItems = true;
+ ImGui::SetLastItemData(0, ImGuiItemFlags_None, ImGuiItemStatusFlags_None, ImRect());
+
+ }
+
+ void UIElements::UpdateContentVisibility() {
+
+ const auto& search = propertySearch;
+ if (!search.active || !search.tables.empty() || search.blockDepth > 0)
+ return;
+
+ const auto& scope = search.scopes[search.depth - 1];
+ if (!scope.contentWindow)
+ return;
+
+ if (scope.contentSkipItems || (!scope.matches && !scope.sectionMatches))
+ HideItems(scope.contentWindow);
+ else
+ scope.contentWindow->SkipItems = false;
+
+ }
+
+ float UIElements::UpdatePropertyLabelWidth(float labelWidth) {
+
+ // The longest label of this frame is collected while the labels are drawn
+ auto window = ImGui::GetCurrentWindow();
+ auto& storage = window->StateStorage;
+ auto lastWidthKey = ImHashStr("Property label width", 0, window->ID);
+ auto widthKey = ImHashStr("Property label width of this frame", 0, window->ID);
+ auto frameKey = ImHashStr("Property label frame", 0, window->ID);
+ auto frame = ImGui::GetFrameCount();
+ if (storage.GetInt(frameKey) != frame) {
+ storage.SetFloat(lastWidthKey, storage.GetFloat(widthKey));
+ storage.SetFloat(widthKey, 0.0f);
+ storage.SetInt(frameKey, frame);
+ }
+ storage.SetFloat(widthKey, std::max(storage.GetFloat(widthKey), labelWidth));
+ return storage.GetFloat(lastWidthKey);
+
+ }
+
}
\ No newline at end of file
diff --git a/libs/ImguiExtension/UiElements.h b/libs/ImguiExtension/UiElements.h
index 0676b5470..ad5e63bae 100644
--- a/libs/ImguiExtension/UiElements.h
+++ b/libs/ImguiExtension/UiElements.h
@@ -1,12 +1,17 @@
#pragma once
#include
+#include
+#include
+#include
#include
#include "System.h"
#include "ImguiWrapper.h"
#include "texture/Texture2D.h"
+struct ImGuiWindow;
+
namespace Atlas::ImguiExtension {
class UIElements {
@@ -18,6 +23,129 @@ namespace Atlas::ImguiExtension {
static void Tooltip(const char* text, float size = 35.0f);
+ // Properties with a muted label on the left and the value filling the rest of the row. Call PropertyLabel
+ // before each value, then EndProperties. Same layout as the property tables of the editor
+ static bool BeginProperties(const char* id);
+
+ // Starts a row, the next item is the value and fills its column
+ static void PropertyLabel(const char* label, const char* tooltip = nullptr);
+
+ static void EndProperties();
+
+ // All label columns of a window are as wide as its longest label. Tables with their own columns set it up
+ // with this and report each of their labels with MeasurePropertyLabel
+ static void SetupPropertyLabelColumn(const char* name);
+
+ static void MeasurePropertyLabel(float labelWidth);
+
+ // Heading of the following properties, hidden while searching
+ static void PropertySection(const char* label);
+
+ // Filters the property rows drawn until EndPropertySearch. Rows are shown when every word of the text is in
+ // their label, tooltip, or the name of a section or group they are in. Panels mark their parts with groups,
+ // sections and blocks, everything else in the content of a group is hidden while searching. Tables in the
+ // content have to be property tables. The scope changes when the searched content does, e.g. with the
+ // selected entity. Does nothing for an empty text
+ static void BeginPropertySearch(const std::string& text, uint32_t scope = 0);
+
+ // Returns whether anything matched
+ static bool EndPropertySearch();
+
+ // Input for the text of a property search, Escape clears it
+ static bool PropertySearchBar(const char* id, std::string& text, bool focus = false);
+
+ // A group of properties below a header, e.g. a component or an element of a list. Groups can be nested. While
+ // searching a group is hidden without matches, then it returns false and EndPropertyGroup isn't called.
+ // Matches are counted while the group is drawn, hidden groups are drawn invisibly from time to time to find
+ // matches in changed content
+ static bool BeginPropertyGroup(const char* name);
+
+ static void EndPropertyGroup();
+
+ // Flags for the tree node or collapsing header of a group, which keep it open while searching
+ static ImGuiTreeNodeFlags PropertyGroupHeaderFlags();
+
+ // The content of a group below its header. While searching, everything in it that isn't a matching property
+ // row, block, nested group or part of a matching section or group is hidden, e.g. buttons and lists
+ static void BeginPropertyContent();
+
+ static void EndPropertyContent();
+
+ // Content outside of property rows, e.g. a button or a list, which is shown when the label matches the
+ // search. Returns false when it's hidden, then EndPropertyBlock isn't called
+ static bool BeginPropertyBlock(const char* label);
+
+ static void EndPropertyBlock();
+
+ // Case-insensitive, every word of the search has to be in the text
+ static bool MatchesSearch(std::string_view text, std::string_view search);
+
+ private:
+ struct PropertyScope {
+ ImGuiID id = 0;
+ std::string name;
+ bool matches = false;
+ int32_t matchCount = 0;
+
+ // Counts are only stored when the whole content was drawn
+ bool counted = true;
+ bool recount = false;
+ ImVec2 start;
+ ImVec2 maxPos;
+
+ std::string section;
+ bool sectionMatches = false;
+
+ ImGuiWindow* contentWindow = nullptr;
+ bool contentSkipItems = false;
+ };
+
+ struct PropertySearch {
+ bool active = false;
+ std::string text;
+ std::vector words;
+ uint32_t key = 0;
+ bool anyMatch = false;
+
+ // The first scope is the search itself, scopes are kept to reuse their strings
+ std::vector scopes;
+ size_t depth = 0;
+ int32_t blockDepth = 0;
+
+ // Property tables of the search, tables without a shown row take no space
+ struct Table {
+ ImVec2 start;
+ int32_t shownRows = 0;
+ };
+ std::vector tables;
+ };
+
+ // Returns the longest label of the current window in the last frame
+ static float UpdatePropertyLabelWidth(float labelWidth);
+
+ static PropertyScope& PushPropertyScope(ImGuiID id, std::string_view name, bool matches);
+
+ // Every word of the search is in the label, the tooltip or the names and sections of the current scopes
+ static bool MatchesSearchWords(std::string_view label, std::string_view tooltip = {});
+
+ static bool ContainsIgnoreCase(std::string_view text, std::string_view word);
+
+ static std::vector SplitWords(std::string_view text);
+
+ static void CountPropertyMatch();
+
+ // Whether the window skips items only because the content of the current scope is hidden
+ static bool IsContentHidden(ImGuiWindow* window);
+
+ static void HideItems(ImGuiWindow* window);
+
+ // Hides the content outside of property tables and blocks unless the section or the group matches
+ static void UpdateContentVisibility();
+
+ static constexpr int32_t recountInterval = 30;
+
+ static PropertySearch propertySearch;
+
};
}
\ No newline at end of file
diff --git a/libs/ImguiExtension/panels/FogPanel.cpp b/libs/ImguiExtension/panels/FogPanel.cpp
index 9407ab056..29ef49869 100644
--- a/libs/ImguiExtension/panels/FogPanel.cpp
+++ b/libs/ImguiExtension/panels/FogPanel.cpp
@@ -6,28 +6,49 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &fog->enable);
- ImGui::SetItemTooltip("Resoltion settings are shared between fog and volumetric clouds");
-
- ImGui::ColorEdit3("Extinction coefficients", &fog->extinctionCoefficients[0]);
- ImGui::DragFloat("Extinction factor", &fog->extinctionFactor, 0.002f, 0.0001f, 4.0f);
- ImGui::DragFloat("Scattering factor", &fog->scatteringFactor, 0.002f, 0.0001f, 4.0f);
- ImGui::DragFloat("Ambient factor", &fog->ambientFactor, 0.001f, 0.0001f, 1.0f);
-
- ImGui::SliderFloat("Density", &fog->density, 0.0f, 0.5f, "%.4f", ImGuiSliderFlags_Logarithmic);
- ImGui::SliderFloat("Height", &fog->height, -10000.0f, 10000.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
- ImGui::SliderFloat("Height falloff", &fog->heightFalloff, 0.0f, 0.5f,
- "%.4f", ImGuiSliderFlags_Logarithmic);
- ImGui::SliderFloat("Scattering anisotropy", &fog->scatteringAnisotropy, -1.0f, 1.0f,
- "%.3f", ImGuiSliderFlags_Logarithmic);
- ImGui::SeparatorText("Volumetric");
- ImGui::Checkbox("Raymarching", &fog->rayMarching);
- ImGui::Checkbox("Local lights", &fog->localLights);
- ImGui::DragInt("Raymarch step count", &fog->rayMarchStepCount, 1, 128);
- ImGui::SliderFloat("Intensity", &fog->volumetricIntensity, 0.0f, 1.0f);
+ if (UIElements::BeginProperties("FogGeneral")) {
+ UIElements::PropertyLabel("Enable", "Resolution settings are shared between fog and volumetric clouds");
+ ImGui::Checkbox("##Enable", &fog->enable);
+
+ UIElements::PropertyLabel("Albedo", "Share of the light the fog removes which it scatters, the rest is absorbed");
+ ImGui::ColorEdit3("##Albedo", &fog->albedo[0]);
+ UIElements::PropertyLabel("Ambient factor");
+ ImGui::DragFloat("##Ambient factor", &fog->ambientFactor, 0.001f, 0.0001f, 1.0f);
+
+ UIElements::PropertyLabel("Density", "Extinction per world unit below the fog height");
+ ImGui::DragFloat("##Density", &fog->density, 0.0001f, 0.0f, 0.5f, "%.5f", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Height");
+ ImGui::DragFloat("##Height", &fog->height, 1.0f, -10000.0f, 10000.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Height falloff");
+ ImGui::DragFloat("##Height falloff", &fog->heightFalloff, 0.0005f, 0.0f, 0.5f,
+ "%.4f", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Scattering anisotropy");
+ ImGui::DragFloat("##Scattering anisotropy", &fog->scatteringAnisotropy, 0.005f, -1.0f, 1.0f,
+ "%.3f", ImGuiSliderFlags_Logarithmic);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Volumetric");
+ if (UIElements::BeginProperties("FogVolumetric")) {
+ UIElements::PropertyLabel("Local lights");
+ ImGui::Checkbox("##Local lights", &fog->localLights);
+ UIElements::PropertyLabel("Froxel tile size");
+ ImGui::DragInt("##Froxel tile size", &fog->froxelTileSize, 0.1f, 4, 32);
+ UIElements::PropertyLabel("Froxel slice count");
+ ImGui::DragInt("##Froxel slice count", &fog->froxelSliceCount, 0.1f, 16, 256);
+ UIElements::PropertyLabel("Froxel filter");
+ ImGui::Checkbox("##Froxel filter", &fog->froxelFilter);
+ UIElements::PropertyLabel("Froxel far distance (0 = camera far)");
+ ImGui::DragFloat("##Froxel far distance (0 = camera far)", &fog->froxelFarDistance, 1.0f, 0.0f, 5000.0f);
+ UIElements::PropertyLabel("Froxel distribution exponent");
+ ImGui::DragFloat("##Froxel distribution exponent", &fog->froxelDistributionExponent, 0.01f, 0.25f, 4.0f);
+ UIElements::PropertyLabel("Intensity");
+ ImGui::DragFloat("##Intensity", &fog->volumetricIntensity, 0.005f, 0.0f, 1.0f);
+ UIElements::EndProperties();
+ }
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/ImguiExtension/panels/GPUProfilerPanel.cpp b/libs/ImguiExtension/panels/GPUProfilerPanel.cpp
deleted file mode 100644
index 52ff79692..000000000
--- a/libs/ImguiExtension/panels/GPUProfilerPanel.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-#include "GPUProfilerPanel.h"
-#include "common/MathHelper.h"
-
-#include "graphics/Profiler.h"
-#include "Clock.h"
-
-namespace Atlas::ImguiExtension {
-
- void GPUProfilerPanel::Render() {
-
- ImGui::PushID(GetNameID());
-
- // All controls in one row
- bool enabled = Graphics::Profiler::enable;
- ImGui::Checkbox("Enable##Profiler", &enabled);
- Graphics::Profiler::enable = enabled;
-
- ImGui::SameLine();
- ImGui::Checkbox("Show graph##Profiler", &showGraph);
-
- if (!showGraph) {
- const char* items[] = { "Chronologically", "Max time", "Min time" };
- ImGui::SameLine();
- ImGui::SetNextItemWidth(std::min(ImGui::GetContentRegionAvail().x * 0.5f, ImGui::GetFontSize() * 10.0f));
- ImGui::Combo("Sort##Performance", &sortItem, items, IM_ARRAYSIZE(items));
- }
-
- if (!enabled)
- ImGui::TextDisabled("The profiler is disabled, enable it to collect GPU timings");
- else if (showGraph)
- perfGraphPanel.Render();
- else
- RenderTable();
-
- ImGui::PopID();
-
- }
-
- void GPUProfilerPanel::RenderTable() {
-
- Graphics::Profiler::OrderBy order;
- switch (sortItem) {
- case 1: order = Graphics::Profiler::OrderBy::MAX_TIME; break;
- case 2: order = Graphics::Profiler::OrderBy::MIN_TIME; break;
- default: order = Graphics::Profiler::OrderBy::CHRONO; break;
- }
-
- // Fraction of the thread time is drawn as a bar behind the time, such that expensive passes stand out
- auto barColor = ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogram);
- barColor.w *= 0.35f;
- auto barColorU32 = ImGui::GetColorU32(barColor);
-
- auto renderTime = [&](double elapsedNs, double totalNs) {
- auto ms = elapsedNs / 1000000.0;
- auto fraction = totalNs > 0.0 ? float(Helper::Math::Saturate(elapsedNs / totalNs)) : 0.0f;
-
- auto cellMin = ImGui::GetCursorScreenPos();
- auto cellWidth = ImGui::GetContentRegionAvail().x;
- auto lineHeight = ImGui::GetTextLineHeight();
- ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(cellMin.x, cellMin.y + lineHeight - 3.0f),
- ImVec2(cellMin.x + cellWidth * fraction, cellMin.y + lineHeight), barColorU32, 1.5f);
-
- char text[32];
- std::snprintf(text, sizeof(text), "%.3f", ms);
- auto textWidth = ImGui::CalcTextSize(text).x;
- ImGui::SetCursorPosX(ImGui::GetCursorPosX() + cellWidth - textWidth);
- ImGui::TextUnformatted(text);
- };
-
- std::function displayQuery;
- displayQuery = [&](Graphics::Profiler::Query& query, double totalNs) {
- ImGui::TableNextRow();
- ImGui::TableNextColumn();
-
- ImGuiTreeNodeFlags expandable = 0;
- if (!query.children.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen |
- ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet;
-
- bool open = ImGui::TreeNodeEx(query.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth);
- ImGui::TableNextColumn();
- renderTime(double(query.timer.elapsedTime), totalNs);
-
- if (open && query.children.size()) {
- for (auto& child : query.children)
- displayQuery(child, totalNs);
- ImGui::TreePop();
- }
-
- };
-
- ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH |
- ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody |
- ImGuiTableFlags_ScrollY;
-
- if (ImGui::BeginTable("PerfTable", 2, flags)) {
- ImGui::TableSetupScrollFreeze(0, 1);
- ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthStretch);
- ImGui::TableSetupColumn("Time (ms)", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed,
- ImGui::GetFontSize() * 14.0f);
- ImGui::TableHeadersRow();
-
- auto threadData = Graphics::Profiler::GetQueriesAverage(64, order);
- for (auto& thread : threadData) {
- double threadTime = 0.0;
- for (const auto& query : thread.queries)
- threadTime += double(query.timer.elapsedTime);
-
- ImGui::TableNextRow();
- ImGui::TableNextColumn();
-
- ImGuiTreeNodeFlags expandable = ImGuiTreeNodeFlags_DefaultOpen;
- if (!thread.queries.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen |
- ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet;
-
- bool open = ImGui::TreeNodeEx(thread.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth);
- ImGui::TableNextColumn();
- renderTime(threadTime, 0.0);
-
- if (open && thread.queries.size()) {
- for (auto &query: thread.queries)
- displayQuery(query, threadTime);
- ImGui::TreePop();
- }
- }
-
- ImGui::EndTable();
- }
-
- }
-
-}
diff --git a/libs/ImguiExtension/panels/GPUProfilerPanel.h b/libs/ImguiExtension/panels/GPUProfilerPanel.h
deleted file mode 100644
index 4e0e911a5..000000000
--- a/libs/ImguiExtension/panels/GPUProfilerPanel.h
+++ /dev/null
@@ -1,29 +0,0 @@
-#pragma once
-
-#include "Panel.h"
-#include "PerformanceGraphPanel.h"
-
-#include
-#include
-#include
-
-namespace Atlas::ImguiExtension {
-
- class GPUProfilerPanel : public Panel {
-
- public:
- GPUProfilerPanel() : Panel("GPU profiler hierarchy") {}
-
- void Render();
-
- void RenderTable();
-
- bool showGraph = false;
-
- int32_t sortItem = 0;
-
- PerformanceGraphPanel perfGraphPanel;
-
- };
-
-}
\ No newline at end of file
diff --git a/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp b/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp
index 4a9369edd..1cdbb9f4c 100644
--- a/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp
+++ b/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp
@@ -2,6 +2,7 @@
#include "StringHelper.h"
#include
+#include
namespace Atlas::ImguiExtension {
@@ -10,130 +11,179 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
// Read-only information
- ImGui::TextDisabled("Probe count");
- ImGui::SameLine();
- ImGui::TextUnformatted(VecToString(volume->probeCount).c_str());
- ImGui::TextDisabled("Cell size");
- ImGui::SameLine();
- ImGui::TextUnformatted(VecToString(volume->cascades[0].cellSize).c_str());
-
- ImGui::SeparatorText("General");
- ImGui::Checkbox("Enable volume", &volume->enable);
- ImGui::Checkbox("Update volume", &volume->update);
- ImGui::Checkbox("Visualize probes", &volume->debug);
-
- ImGui::SeparatorText("Sampling");
- ImGui::Checkbox("Sample emissives", &volume->sampleEmissives);
- ImGui::Checkbox("Use shadow map", &volume->useShadowMap);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Uses the shadow map to calculate shadows in the GI. "
- "This is only possible when cascaded shadow maps are not used.");
+ if (UIElements::BeginProperties("IrradianceVolumeInfo")) {
+ UIElements::PropertyLabel("Probe count");
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextUnformatted(VecToString(volume->probeCount).c_str());
+ UIElements::PropertyLabel("Cell size");
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextUnformatted(VecToString(volume->cascades[0].cellSize).c_str());
+ UIElements::EndProperties();
}
- ImGui::Checkbox("Calculate visibility", &volume->visibility);
- ImGui::Checkbox("Calculate radiance", &volume->radiance);
- bool prevMomentRes = volume->lowerResMoments;
- ImGui::Checkbox("Lower resolution visibility", &volume->lowerResMoments);
- if (prevMomentRes != volume->lowerResMoments) {
- volume->SetMomentsResolution(volume->lowerResMoments);
+ UIElements::PropertySection("General");
+ if (UIElements::BeginProperties("IrradianceVolumeGeneral")) {
+ UIElements::PropertyLabel("Enable volume");
+ ImGui::Checkbox("##Enable volume", &volume->enable);
+ UIElements::PropertyLabel("Update volume");
+ ImGui::Checkbox("##Update volume", &volume->update);
+ UIElements::PropertyLabel("Visualize probes");
+ ImGui::Checkbox("##Visualize probes", &volume->debug);
+ UIElements::EndProperties();
}
- bool prevRadianceRes = volume->lowerResRadiance;
- ImGui::Checkbox("Lower resolution radiance", &volume->lowerResRadiance);
- if (prevRadianceRes != volume->lowerResRadiance) {
- volume->SetRadianceResolution(volume->lowerResRadiance);
- }
+ UIElements::PropertySection("Sampling");
+ if (UIElements::BeginProperties("IrradianceVolumeSampling")) {
+ UIElements::PropertyLabel("Calculate visibility");
+ ImGui::Checkbox("##Calculate visibility", &volume->visibility);
+ UIElements::PropertyLabel("Calculate radiance");
+ ImGui::Checkbox("##Calculate radiance", &volume->radiance);
+
+ bool prevMomentRes = volume->lowerResMoments;
+ UIElements::PropertyLabel("Lower resolution visibility");
+ ImGui::Checkbox("##Lower resolution visibility", &volume->lowerResMoments);
+ if (prevMomentRes != volume->lowerResMoments) {
+ volume->SetMomentsResolution(volume->lowerResMoments);
+ }
- ImGui::Checkbox("Opacity check", &volume->opacityCheck);
-
- ImGui::SeparatorText("Probe grid");
- auto prevCascadeCount = volume->cascadeCount;
- ImGui::SliderInt("Cascades count", &volume->cascadeCount, 1, MAX_IRRADIANCE_VOLUME_CASCADES);
-
- const char* gridResItems [] = { "11x11x11", "15x15x15", "21x21x21", "31x31x31" };
- int currentItem = 0;
- if (volume->probeCount == glm::ivec3(11)) currentItem = 0;
- if (volume->probeCount == glm::ivec3(15)) currentItem = 1;
- if (volume->probeCount == glm::ivec3(21)) currentItem = 2;
- if (volume->probeCount == glm::ivec3(31)) currentItem = 3;
- auto prevItem = currentItem;
- ImGui::Combo("Resolution", ¤tItem, gridResItems, IM_ARRAYSIZE(gridResItems));
-
- if (currentItem != prevItem || prevCascadeCount != volume->cascadeCount) {
- switch (currentItem) {
- case 0: volume->SetProbeCount(glm::ivec3(11), volume->cascadeCount); break;
- case 1: volume->SetProbeCount(glm::ivec3(15), volume->cascadeCount); break;
- case 2: volume->SetProbeCount(glm::ivec3(21), volume->cascadeCount); break;
- case 3: volume->SetProbeCount(glm::ivec3(31), volume->cascadeCount); break;
+ bool prevRadianceRes = volume->lowerResRadiance;
+ UIElements::PropertyLabel("Lower resolution radiance");
+ ImGui::Checkbox("##Lower resolution radiance", &volume->lowerResRadiance);
+ if (prevRadianceRes != volume->lowerResRadiance) {
+ volume->SetRadianceResolution(volume->lowerResRadiance);
}
- }
- const char* rayCountItems[] = { "32", "64", "96", "128", "256", "512" };
- currentItem = 0;
- if (volume->rayCount == 32) currentItem = 0;
- if (volume->rayCount == 64) currentItem = 1;
- if (volume->rayCount == 96) currentItem = 2;
- if (volume->rayCount == 128) currentItem = 3;
- if (volume->rayCount == 256) currentItem = 4;
- if (volume->rayCount == 512) currentItem = 5;
- prevItem = currentItem;
- ImGui::Combo("Ray count", ¤tItem, rayCountItems, IM_ARRAYSIZE(rayCountItems));
-
- if (currentItem != prevItem) {
- switch (currentItem) {
- case 0: volume->SetRayCount(32, 16); break;
- case 1: volume->SetRayCount(64, 16); break;
- case 2: volume->SetRayCount(96, 16); break;
- case 3: volume->SetRayCount(128, 16); break;
- case 4: volume->SetRayCount(256, 16); break;
- case 5: volume->SetRayCount(512, 16); break;
+ UIElements::PropertyLabel("Opacity check");
+ ImGui::Checkbox("##Opacity check", &volume->opacityCheck);
+ auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering;
+ UIElements::PropertyLabel("Shader execution reordering");
+ ImGui::BeginDisabled(!reorderSupported);
+ ImGui::Checkbox("##Shader execution reordering", &volume->shaderExecutionReordering);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, "
+ "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support");
}
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
}
- ImGui::SliderFloat("Strength", &volume->strength, 0.0f, 5.0f);
- if (ImGui::SliderFloat("Probe storage scale", &volume->storageScale, 0.000001f, 1.0f,
- "%.6f", ImGuiSliderFlags_Logarithmic)) {
- volume->ClearProbes();
- }
- if (ImGui::IsItemHovered()) {
- ImGui::SetTooltip("Smaller values increase lighting range at the cost of precision.\n"
- "0.1 gives 10x range; lighting brightness is restored when sampled.\n"
- "Changing this clears probe history.");
- }
+ UIElements::PropertySection("Probe grid");
+ if (UIElements::BeginProperties("IrradianceVolumeProbeGrid")) {
+ auto prevCascadeCount = volume->cascadeCount;
+ UIElements::PropertyLabel("Cascades count");
+ ImGui::SliderInt("##Cascades count", &volume->cascadeCount, 1, MAX_IRRADIANCE_VOLUME_CASCADES);
+
+ const char* gridResItems [] = { "11x11x11", "15x15x15", "21x21x21", "31x31x31" };
+ int currentItem = 0;
+ if (volume->probeCount == ivec3(11)) currentItem = 0;
+ if (volume->probeCount == ivec3(15)) currentItem = 1;
+ if (volume->probeCount == ivec3(21)) currentItem = 2;
+ if (volume->probeCount == ivec3(31)) currentItem = 3;
+ auto prevItem = currentItem;
+ UIElements::PropertyLabel("Resolution");
+ ImGui::Combo("##Resolution", ¤tItem, gridResItems, IM_ARRAYSIZE(gridResItems));
+
+ if (currentItem != prevItem || prevCascadeCount != volume->cascadeCount) {
+ switch (currentItem) {
+ case 0: volume->SetProbeCount(ivec3(11), volume->cascadeCount); break;
+ case 1: volume->SetProbeCount(ivec3(15), volume->cascadeCount); break;
+ case 2: volume->SetProbeCount(ivec3(21), volume->cascadeCount); break;
+ case 3: volume->SetProbeCount(ivec3(31), volume->cascadeCount); break;
+ }
+ }
+
+ const char* rayCountItems[] = { "32", "64", "96", "128", "256", "512" };
+ currentItem = 0;
+ if (volume->rayCount == 32) currentItem = 0;
+ if (volume->rayCount == 64) currentItem = 1;
+ if (volume->rayCount == 96) currentItem = 2;
+ if (volume->rayCount == 128) currentItem = 3;
+ if (volume->rayCount == 256) currentItem = 4;
+ if (volume->rayCount == 512) currentItem = 5;
+ prevItem = currentItem;
+ UIElements::PropertyLabel("Ray count");
+ ImGui::Combo("##Ray count", ¤tItem, rayCountItems, IM_ARRAYSIZE(rayCountItems));
+
+ if (currentItem != prevItem) {
+ switch (currentItem) {
+ case 0: volume->SetRayCount(32, 16); break;
+ case 1: volume->SetRayCount(64, 16); break;
+ case 2: volume->SetRayCount(96, 16); break;
+ case 3: volume->SetRayCount(128, 16); break;
+ case 4: volume->SetRayCount(256, 16); break;
+ case 5: volume->SetRayCount(512, 16); break;
+ }
+ }
- ImGui::SeparatorText("Volume bounds");
- ImGui::Checkbox("Scrolling", &volume->scroll);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Scrolls the volume based on a set position (by default the camera). "
- "This should be used for large scenes where the volume can't cover the whole scene");
+ UIElements::PropertyLabel("Strength");
+ ImGui::SliderFloat("##Strength", &volume->strength, 0.0f, 5.0f);
+ UIElements::PropertyLabel("Probe storage scale");
+ if (ImGui::SliderFloat("##Probe storage scale", &volume->storageScale, 0.000001f, 1.0f,
+ "%.6f", ImGuiSliderFlags_Logarithmic)) {
+ volume->ClearProbes();
+ }
+ if (ImGui::IsItemHovered()) {
+ ImGui::SetTooltip("Smaller values increase lighting range at the cost of precision.\n"
+ "0.1 gives 10x range; lighting brightness is restored when sampled.\n"
+ "Changing this clears probe history.");
+ }
+ UIElements::EndProperties();
}
- if (volume->scroll) {
- auto volumeSize = volume->aabb.GetSize();
- ImGui::DragFloat3("Size", (float*)&volumeSize, 0.5f, 1.0f, 2000.0f);
- volume->aabb = volume->aabb.Scale(volumeSize / volume->aabb.GetSize());
+ UIElements::PropertySection("Volume bounds");
+ if (UIElements::BeginProperties("IrradianceVolumeBounds")) {
+ UIElements::PropertyLabel("Scrolling");
+ ImGui::Checkbox("##Scrolling", &volume->scroll);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Scrolls the volume based on a set position (by default the camera). "
+ "This should be used for large scenes where the volume can't cover the whole scene");
+ }
+
+ if (volume->scroll) {
+ auto volumeSize = volume->aabb.GetSize();
+ UIElements::PropertyLabel("Size");
+ ImGui::DragFloat3("##Size", (float*)&volumeSize, 0.5f, 1.0f, 2000.0f);
+ volume->aabb = volume->aabb.Scale(volumeSize / volume->aabb.GetSize());
+ }
+ else {
+ UIElements::PropertyLabel("Min");
+ ImGui::DragFloat3("##Min", (float*)&volume->aabb.min, 0.5f, -2000.0f, 2000.0f);
+ UIElements::PropertyLabel("Max");
+ ImGui::DragFloat3("##Max", (float*)&volume->aabb.max, 0.5f, -2000.0f, 2000.0f);
+ }
+ UIElements::EndProperties();
}
- else {
- ImGui::DragFloat3("Min", (float*)&volume->aabb.min, 0.5f, -2000.0f, 2000.0f);
- ImGui::DragFloat3("Max", (float*)&volume->aabb.max, 0.5f, -2000.0f, 2000.0f);
+ if (!volume->scroll) {
if (ImGui::Button("Adjust to scene size", ImVec2(-FLT_MIN, 0.0f))) {
volume->aabb = CalculateSceneSize(scene);
}
}
volume->SetAABB(volume->aabb);
- ImGui::SeparatorText("Filtering");
- ImGui::SliderFloat("Hysteresis", &volume->hysteresis, 0.0f, 1.0f, "%.3f");
- ImGui::SliderFloat("Sharpness", &volume->sharpness, 0.01f, 200.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
- ImGui::SliderFloat("Bias", &volume->bias, 0.0f, 1.0f);
- auto prevGamma = volume->gamma;
- ImGui::SliderFloat("Gamma exponent", &volume->gamma, 0.0f, 10.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
- if (prevGamma != volume->gamma) volume->ClearProbes();
- ImGui::DragFloat("Split correction", &volume->splitCorrection, 0.01f, 1.0f, 10.0f);
-
- ImGui::SeparatorText("Probe optimization");
- ImGui::Checkbox("Optimize probes", &volume->optimizeProbes);
+ UIElements::PropertySection("Filtering");
+ if (UIElements::BeginProperties("IrradianceVolumeFiltering")) {
+ UIElements::PropertyLabel("Hysteresis");
+ ImGui::SliderFloat("##Hysteresis", &volume->hysteresis, 0.0f, 1.0f, "%.3f");
+ UIElements::PropertyLabel("Sharpness");
+ ImGui::SliderFloat("##Sharpness", &volume->sharpness, 0.01f, 200.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Bias");
+ ImGui::SliderFloat("##Bias", &volume->bias, 0.0f, 1.0f);
+ auto prevGamma = volume->gamma;
+ UIElements::PropertyLabel("Gamma exponent");
+ ImGui::SliderFloat("##Gamma exponent", &volume->gamma, 0.0f, 10.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ if (prevGamma != volume->gamma) volume->ClearProbes();
+ UIElements::PropertyLabel("Split correction");
+ ImGui::DragFloat("##Split correction", &volume->splitCorrection, 0.01f, 1.0f, 10.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Probe optimization");
+ if (UIElements::BeginProperties("IrradianceVolumeProbeOptimization")) {
+ UIElements::PropertyLabel("Optimize probes");
+ ImGui::Checkbox("##Optimize probes", &volume->optimizeProbes);
+ UIElements::EndProperties();
+ }
if (ImGui::Button("Reset probe offsets", ImVec2(-FLT_MIN, 0.0f))) {
volume->ResetProbeOffsets();
}
@@ -144,8 +194,8 @@ namespace Atlas::ImguiExtension {
Volume::AABB IrradianceVolumePanel::CalculateSceneSize(Ref& scene) const {
- auto min = glm::vec3(std::numeric_limits::max());
- auto max = glm::vec3(-std::numeric_limits::max());
+ auto min = vec3(std::numeric_limits::max());
+ auto max = vec3(-std::numeric_limits::max());
Volume::AABB aabb(min, max);
auto meshSubset = scene->GetSubset();
diff --git a/libs/ImguiExtension/panels/MaterialPanel.cpp b/libs/ImguiExtension/panels/MaterialPanel.cpp
index a56d761fe..c0f5c4341 100644
--- a/libs/ImguiExtension/panels/MaterialPanel.cpp
+++ b/libs/ImguiExtension/panels/MaterialPanel.cpp
@@ -6,87 +6,120 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- auto availableWidth = ImGui::GetContentRegionAvail().x;
- auto padding = 8.0f;
- auto widthAfterImage = availableWidth - padding - ImGui::GetTextLineHeight();
-
- auto renderWithImagePreview = [&](ResourceHandle& texture, std::function element) {
+ auto renderWithImagePreview = [&](ResourceHandle& texture, const char* propertiesId,
+ std::function element) {
// If this will not be loaded it will return 0, so we can still use it
ImGui::PushID(texture.GetID());
- if (texture.IsLoaded()) {
+ // The selector shows its own preview
+ if (textureSelector.has_value()) {
+ texture = textureSelector.value()(texture);
+ }
+ else if (texture.IsLoaded()) {
UIElements::TexturePreview(wrapper, &texture);
- ImGui::SameLine();
- // Calculate next item width and push a width with the image elements width substracted from it
- auto width = ImGui::CalcItemWidth();
- ImGui::PushItemWidth(width - padding - ImGui::GetTextLineHeightWithSpacing());
- if (textureSelector.has_value()) {
- texture = textureSelector.value()(texture);
- ImGui::PopItemWidth();
- }
}
- else {
- if (textureSelector.has_value())
- texture = textureSelector.value()(texture);
+ if (UIElements::BeginProperties(propertiesId)) {
+ element();
+ UIElements::EndProperties();
}
- element();
- if (texture.IsLoaded() && !textureSelector.has_value())
- ImGui::PopItemWidth();
ImGui::PopID();
};
- ImGui::SeparatorText("Base color");
- renderWithImagePreview(material->baseColorMap, [&]() {
- ImGui::ColorEdit3("Base color", glm::value_ptr(material->baseColor));
+ UIElements::PropertySection("Base color");
+ renderWithImagePreview(material->baseColorMap, "MaterialBaseColor", [&]() {
+ UIElements::PropertyLabel("Base color");
+ ImGui::ColorEdit3("##Base color", glm::value_ptr(material->baseColor));
});
- ImGui::SeparatorText("Emission");
- renderWithImagePreview(material->emissiveMap, [&]() {
- ImGui::ColorEdit3("Emissive color", glm::value_ptr(material->emissiveColor));
- ImGui::DragFloat("Emissive intensity", &material->emissiveIntensity, 0.1f, 0.0f, 10000.0f, "%.2f");
+ UIElements::PropertySection("Emission");
+ renderWithImagePreview(material->emissiveMap, "MaterialEmission", [&]() {
+ UIElements::PropertyLabel("Emissive color");
+ ImGui::ColorEdit3("##Emissive color", glm::value_ptr(material->emissiveColor));
+ UIElements::PropertyLabel("Emissive intensity");
+ ImGui::DragFloat("##Emissive intensity", &material->emissiveIntensity, 0.1f, 0.0f, 10000.0f, "%.2f");
});
- ImGui::SeparatorText("Opacity");
- renderWithImagePreview(material->opacityMap, [&]() {
- ImGui::SliderFloat("Opacity factor", &material->opacity, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+ UIElements::PropertySection("Opacity");
+ renderWithImagePreview(material->opacityMap, "MaterialOpacity", [&]() {
+ UIElements::PropertyLabel("Opacity factor");
+ ImGui::SliderFloat("##Opacity factor", &material->opacity, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
});
- ImGui::SeparatorText("Normals");
- renderWithImagePreview(material->normalMap, [&]() {
- ImGui::SliderFloat("Normal factor", &material->normalScale, 0.0f, 1.0f);
+ UIElements::PropertySection("Normals");
+ renderWithImagePreview(material->normalMap, "MaterialNormals", [&]() {
+ UIElements::PropertyLabel("Normal factor");
+ ImGui::SliderFloat("##Normal factor", &material->normalScale, 0.0f, 1.0f);
});
- ImGui::SeparatorText("Roughness");
- renderWithImagePreview(material->roughnessMap, [&]() {
- ImGui::SliderFloat("Roughness factor", &material->roughness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+ UIElements::PropertySection("Roughness");
+ renderWithImagePreview(material->roughnessMap, "MaterialRoughness", [&]() {
+ UIElements::PropertyLabel("Roughness factor");
+ ImGui::SliderFloat("##Roughness factor", &material->roughness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
});
- ImGui::SeparatorText("Metallic");
- renderWithImagePreview(material->metalnessMap, [&]() {
- ImGui::SliderFloat("Metallic factor", &material->metalness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+ UIElements::PropertySection("Metallic");
+ renderWithImagePreview(material->metalnessMap, "MaterialMetallic", [&]() {
+ UIElements::PropertyLabel("Metallic factor");
+ ImGui::SliderFloat("##Metallic factor", &material->metalness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
});
- ImGui::SeparatorText("Ambient occlusion");
- renderWithImagePreview(material->aoMap, [&]() {
- ImGui::SliderFloat("Ao factor", &material->ao, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+ UIElements::PropertySection("Ambient occlusion");
+ renderWithImagePreview(material->aoMap, "MaterialAmbientOcclusion", [&]() {
+ UIElements::PropertyLabel("Ao factor");
+ ImGui::SliderFloat("##Ao factor", &material->ao, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
});
- ImGui::SeparatorText("Displacement");
- renderWithImagePreview(material->displacementMap, [&]() {
- ImGui::SliderFloat("Displacement scale", &material->displacementScale, 0.0f, 1.0f);
+ UIElements::PropertySection("Displacement");
+ renderWithImagePreview(material->displacementMap, "MaterialDisplacement", [&]() {
+ UIElements::PropertyLabel("Displacement scale");
+ ImGui::SliderFloat("##Displacement scale", &material->displacementScale, 0.0f, 1.0f);
});
- ImGui::SeparatorText("Surface");
- ImGui::SliderFloat("Reflectance", &material->reflectance, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
-
- ImGui::ColorEdit3("Transmissive color", glm::value_ptr(material->transmissiveColor));
-
- ImGui::Checkbox("Two sided", &material->twoSided);
-
- ImGui::SeparatorText("UV");
- ImGui::DragFloat2("UV animation", glm::value_ptr(material->uvAnimation), 0.01f, -1.0f, 1.0f);
- ImGui::DragFloat("UV tiling", &material->tiling, 0.01f, 0.01f, 100.0f);
+ UIElements::PropertySection("Surface");
+ if (UIElements::BeginProperties("MaterialSurface")) {
+ UIElements::PropertyLabel("Reflectance");
+ ImGui::SliderFloat("##Reflectance", &material->reflectance, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+
+ UIElements::PropertyLabel("Two sided");
+ ImGui::Checkbox("##Two sided", &material->twoSided);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Transmission");
+ if (UIElements::BeginProperties("MaterialTransmission")) {
+ UIElements::PropertyLabel("Transmitted color", "Light shining through thin surfaces like leaves or cloth, lit from "
+ "the back side and tinted by this color. Black lets no light through");
+ ImGui::ColorEdit3("##Transmitted color", glm::value_ptr(material->transmissiveColor));
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Translucency");
+ if (UIElements::BeginProperties("MaterialTranslucency")) {
+ const char* blendModes[] = { "None", "Alpha", "Additive", "Multiply" };
+ auto blendMode = int32_t(material->blendMode);
+ UIElements::PropertyLabel("Blend mode");
+ if (ImGui::Combo("##Blend mode", &blendMode, blendModes, IM_ARRAYSIZE(blendModes)))
+ material->blendMode = MaterialBlendMode(blendMode);
+
+ if (material->blendMode == MaterialBlendMode::Alpha) {
+ UIElements::PropertyLabel("Refractive index");
+ ImGui::SliderFloat("##Refractive index", &material->refractiveIndex, 1.0f, 2.5f, "%.3f", ImGuiSliderFlags_AlwaysClamp);
+ UIElements::PropertyLabel("Thickness", "Above zero the surface refracts. Closed meshes refract where the rays "
+ "leave them through their back faces, the thickness only applies to open meshes like water planes");
+ ImGui::DragFloat("##Thickness", &material->thickness, 0.001f, 0.0f, 1.0f, "%.3f m", ImGuiSliderFlags_AlwaysClamp);
+ }
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("UV");
+ if (UIElements::BeginProperties("MaterialUV")) {
+ UIElements::PropertyLabel("UV animation");
+ ImGui::DragFloat2("##UV animation", glm::value_ptr(material->uvAnimation), 0.01f, -1.0f, 1.0f);
+ UIElements::PropertyLabel("UV tiling");
+ ImGui::DragFloat("##UV tiling", &material->tiling, 0.01f, 0.01f, 100.0f);
+ UIElements::EndProperties();
+ }
ImGui::PopID();
diff --git a/libs/ImguiExtension/panels/MaterialsPanel.cpp b/libs/ImguiExtension/panels/MaterialsPanel.cpp
index e7a4b8483..7d793345d 100644
--- a/libs/ImguiExtension/panels/MaterialsPanel.cpp
+++ b/libs/ImguiExtension/panels/MaterialsPanel.cpp
@@ -8,11 +8,13 @@
namespace Atlas::ImguiExtension {
void MaterialsPanel::Render(Ref& wrapper, std::vector>& materials,
- MaterialSelector materialSelector, MaterialPanel::TextureSelector textureSelector) {
+ MaterialSelector materialSelector, MaterialPanel::TextureSelector textureSelector,
+ GraphMaterialRenderer graphMaterialRenderer) {
ImGui::PushID(GetNameID());
- ImGui::InputTextWithHint("Search", "Type to search material", &materialSearch);
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ ImGui::InputTextWithHint("##Search", "Search materials...", &materialSearch);
auto matches = materials | std::views::filter(
[&](const ResourceHandle& material) {
@@ -41,18 +43,25 @@ namespace Atlas::ImguiExtension {
auto nodeID = GetNameID() + std::to_string(counter);
materialName += "###" + nodeID;
- if (ImGui::TreeNode(materialName.c_str())) {
- if (materialSelector.has_value()) {
- material = materialSelector.value()(material);
- ImGui::Separator();
+ if (UIElements::BeginPropertyGroup(materialName.c_str())) {
+ if (ImGui::TreeNodeEx(materialName.c_str(), UIElements::PropertyGroupHeaderFlags())) {
+ UIElements::BeginPropertyContent();
+ if (materialSelector.has_value()) {
+ material = materialSelector.value()(material);
+ ImGui::Separator();
+ }
+ // Might be deleted above
+ if (material.IsLoaded() && material->HasGraph() && graphMaterialRenderer.has_value()) {
+ graphMaterialRenderer.value()(material.Get());
+ }
+ else if (material.IsLoaded()) {
+ materialPanel.Render(wrapper, material.Get(), textureSelector);
+ }
+ UIElements::EndPropertyContent();
+
+ ImGui::TreePop();
}
- // Might be deleted above
- if (material.IsLoaded()) {
- materialPanel.Render(wrapper, material.Get(), textureSelector);
- }
-
- ImGui::TreePop();
-
+ UIElements::EndPropertyGroup();
}
ImGui::PopID();
@@ -68,7 +77,8 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::InputTextWithHint("Search", "Type to search material", &materialSearch);
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ ImGui::InputTextWithHint("##Search", "Search materials...", &materialSearch);
auto matches = materials | std::views::filter(
[&](const Ref& material) {
@@ -85,12 +95,15 @@ namespace Atlas::ImguiExtension {
auto nodeID = GetNameID() + std::to_string(counter);
materialName += "###" + nodeID;
- if (ImGui::TreeNode(materialName.c_str())) {
-
- materialPanel.Render(wrapper, material, textureSelector);
-
- ImGui::TreePop();
+ if (UIElements::BeginPropertyGroup(materialName.c_str())) {
+ if (ImGui::TreeNodeEx(materialName.c_str(), UIElements::PropertyGroupHeaderFlags())) {
+ UIElements::BeginPropertyContent();
+ materialPanel.Render(wrapper, material, textureSelector);
+ UIElements::EndPropertyContent();
+ ImGui::TreePop();
+ }
+ UIElements::EndPropertyGroup();
}
ImGui::PopID();
diff --git a/libs/ImguiExtension/panels/MaterialsPanel.h b/libs/ImguiExtension/panels/MaterialsPanel.h
index f6c259175..a70f5178c 100644
--- a/libs/ImguiExtension/panels/MaterialsPanel.h
+++ b/libs/ImguiExtension/panels/MaterialsPanel.h
@@ -12,12 +12,15 @@ namespace Atlas::ImguiExtension {
class MaterialsPanel : public Panel {
using MaterialSelector = std::optional(ResourceHandle)>>;
+ // Renders a material with a graph instead of the properties, e.g. with the parameters of the graph
+ using GraphMaterialRenderer = std::optional&)>>;
public:
MaterialsPanel() : Panel("Materials properties") {}
void Render(Ref& wrapper, std::vector>& materials,
- MaterialSelector materialSelector = {}, MaterialPanel::TextureSelector textureSelector = {});
+ MaterialSelector materialSelector = {}, MaterialPanel::TextureSelector textureSelector = {},
+ GraphMaterialRenderer graphMaterialRenderer = {});
void Render(Ref& wrapper, std::vector[>& materials,
MaterialPanel::TextureSelector textureSelector = {});
diff --git a/libs/ImguiExtension/panels/OceanPanel.cpp b/libs/ImguiExtension/panels/OceanPanel.cpp
new file mode 100644
index 000000000..ebc99ca7a
--- /dev/null
+++ b/libs/ImguiExtension/panels/OceanPanel.cpp
@@ -0,0 +1,165 @@
+#include "OceanPanel.h"
+
+#include "ocean/OceanSerializer.h"
+
+namespace Atlas::ImguiExtension {
+
+ void OceanPanel::Render(Ref& ocean, TextureSelector textureSelector) {
+
+ ImGui::PushID(GetNameID());
+
+ auto& simulation = ocean->simulation;
+
+ if (UIElements::BeginProperties("OceanGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &ocean->enable);
+ UIElements::PropertyLabel("Underwater shader");
+ ImGui::Checkbox("##Underwater shader", &ocean->underwaterShader);
+ UIElements::PropertyLabel("Wireframe");
+ ImGui::Checkbox("##Wireframe", &ocean->wireframe);
+ UIElements::PropertyLabel("Translation");
+ ImGui::DragFloat3("##Translation", glm::value_ptr(ocean->translation), 0.1f);
+ UIElements::EndProperties();
+ }
+
+ // Changing these recreates the ocean, the other settings are kept
+ UIElements::PropertySection("Resolution");
+ int32_t LoDCount = ocean->GetLoDCount();
+ float size = ocean->sideLength;
+ int32_t N = simulation.N;
+
+ bool recreate = false;
+ if (UIElements::BeginProperties("OceanResolution")) {
+ const char* resolutions[] = { "128", "256", "512", "1024" };
+ int32_t resolutionIdx = glm::clamp(int32_t(log2f(float(N))) - 7, 0, 3);
+ UIElements::PropertyLabel("Simulation resolution");
+ if (ImGui::Combo("##Simulation resolution", &resolutionIdx, resolutions, IM_ARRAYSIZE(resolutions))) {
+ N = 128 << resolutionIdx;
+ recreate = true;
+ }
+ UIElements::PropertyLabel("Size");
+ recreate |= ImGui::DragFloat("##Size", &size, 16.0f, 64.0f, 65536.0f, "%.0f m");
+ UIElements::PropertyLabel("LoD count");
+ recreate |= ImGui::DragInt("##LoD count", &LoDCount, 0.1f, 1, 12);
+ UIElements::EndProperties();
+ }
+
+ if (recreate) {
+ json j = *ocean;
+ j["LoDCount"] = LoDCount;
+ j["size"] = size;
+ j["N"] = N;
+ ocean = CreateRef(j.get());
+ }
+
+ UIElements::PropertySection("Waves");
+ if (UIElements::BeginProperties("OceanWaves")) {
+ bool spectrumChanged = false;
+ UIElements::PropertyLabel("Wave amplitude");
+ spectrumChanged |= ImGui::DragFloat("##Wave amplitude", &simulation.waveAmplitude, 0.00001f,
+ 0.0f, 0.01f, "%.6f");
+ UIElements::PropertyLabel("Small wave surpression");
+ spectrumChanged |= ImGui::DragFloat("##Small wave surpression", &simulation.waveSurpression, 0.0001f,
+ 0.0f, 1.0f, "%.4f");
+ UIElements::PropertyLabel("Wind direction");
+ spectrumChanged |= ImGui::DragFloat2("##Wind direction", glm::value_ptr(simulation.windDirection),
+ 0.01f, -1.0f, 1.0f);
+ UIElements::PropertyLabel("Wind speed");
+ spectrumChanged |= ImGui::DragFloat("##Wind speed", &simulation.windSpeed, 0.1f, 0.5f, 40.0f, "%.1f m/s");
+ UIElements::PropertyLabel("Wind dependency", "Strength of the waves running against the wind");
+ spectrumChanged |= ImGui::SliderFloat("##Wind dependency", &simulation.windDependency, 0.0f, 1.0f);
+ if (spectrumChanged)
+ simulation.UpdateSpectrum();
+
+ UIElements::PropertyLabel("Displacement scale");
+ ImGui::DragFloat("##Displacement scale", &ocean->displacementScale, 0.01f, 0.0f, 4.0f);
+ UIElements::PropertyLabel("Choppyness scale");
+ ImGui::DragFloat("##Choppyness scale", &ocean->choppynessScale, 0.01f, 0.0f, 2.0f);
+ UIElements::PropertyLabel("Patch size", "Size of the smallest cascade, the others are scaled by their tiling factors");
+ ImGui::DragFloat("##Patch size", &ocean->tiling, 0.1f, 1.0f, 1024.0f, "%.1f m");
+ UIElements::PropertyLabel("Simulation speed");
+ ImGui::DragFloat("##Simulation speed", &simulation.simulationSpeed, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Update simulation");
+ ImGui::Checkbox("##Update simulation", &simulation.update);
+ UIElements::PropertyLabel("Normals from FFT");
+ ImGui::Checkbox("##Normals from FFT", &simulation.fftNormals);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Spectrum cascades");
+ if (UIElements::BeginProperties("OceanSpectrumCascades")) {
+ UIElements::PropertyLabel("Tiling factors");
+ ImGui::DragFloat4("##Tiling factors", glm::value_ptr(simulation.spectrumTilingFactors), 0.1f, 0.1f, 100.0f);
+ UIElements::PropertyLabel("Weights");
+ ImGui::DragFloat4("##Weights", glm::value_ptr(simulation.spectrumWeights), 0.01f, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Fadeout distances");
+ ImGui::DragFloat4("##Fadeout distances", glm::value_ptr(simulation.spectrumFadeoutDistances),
+ 10.0f, 0.0f, 100000.0f, "%.0f");
+ UIElements::EndProperties();
+ }
+
+ if (textureSelector.has_value()) {
+ UIElements::PropertySection("Ripple normal map");
+ ImGui::PushID("Ripple");
+ ocean->rippleTexture = textureSelector.value()(ocean->rippleTexture);
+ ImGui::PopID();
+ }
+
+ UIElements::PropertySection("Foam");
+ if (textureSelector.has_value()) {
+ ImGui::PushID("Foam");
+ ocean->foamTexture = textureSelector.value()(ocean->foamTexture);
+ ImGui::PopID();
+ }
+ if (UIElements::BeginProperties("OceanFoam")) {
+ UIElements::PropertyLabel("Foam offset");
+ ImGui::DragFloat("##Foam offset", &simulation.foamOffset, 0.01f, -1.0f, 1.0f);
+ UIElements::PropertyLabel("Foam scale");
+ ImGui::DragFloat("##Foam scale", &simulation.foamScale, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Foam size");
+ ImGui::DragFloat("##Foam size", &simulation.foamSize, 0.01f, 0.0f, 20.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Water color");
+ if (UIElements::BeginProperties("OceanWaterColor")) {
+ UIElements::PropertyLabel("Water body color");
+ ImGui::ColorEdit3("##Water body color", glm::value_ptr(ocean->waterBodyColor));
+ UIElements::PropertyLabel("Scatter color");
+ ImGui::ColorEdit3("##Scatter color", glm::value_ptr(ocean->scatterColor));
+ UIElements::PropertyLabel("Water color intensity");
+ ImGui::DragFloat2("##Water color intensity", glm::value_ptr(ocean->waterColorIntensity), 0.01f, 0.0f, 10.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Shore waves");
+ if (UIElements::BeginProperties("OceanShoreWaves")) {
+ UIElements::PropertyLabel("Distance offset");
+ ImGui::DragFloat("##Distance offset", &ocean->shoreWaveDistanceOffset, 0.5f, 0.0f, 1000.0f);
+ UIElements::PropertyLabel("Distance scale");
+ ImGui::DragFloat("##Distance scale", &ocean->shoreWaveDistanceScale, 0.5f, 0.0f, 1000.0f);
+ UIElements::PropertyLabel("Amplitude");
+ ImGui::DragFloat("##Amplitude", &ocean->shoreWaveAmplitude, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Steepness");
+ ImGui::DragFloat("##Steepness", &ocean->shoreWaveSteepness, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Power");
+ ImGui::DragFloat("##Power", &ocean->shoreWavePower, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Speed");
+ ImGui::DragFloat("##Speed", &ocean->shoreWaveSpeed, 0.01f, 0.0f, 50.0f);
+ UIElements::PropertyLabel("Length");
+ ImGui::DragFloat("##Length", &ocean->shoreWaveLength, 0.01f, 0.0f, 50.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Physics");
+ if (UIElements::BeginProperties("OceanPhysics")) {
+ UIElements::PropertyLabel("Enable physics", "Bodies with buoyancy float on the waves and scripts can query the surface");
+ ImGui::Checkbox("##Enable physics", &ocean->physics);
+ UIElements::EndProperties();
+ }
+
+ ImGui::PopID();
+
+ }
+
+}
diff --git a/libs/ImguiExtension/panels/OceanPanel.h b/libs/ImguiExtension/panels/OceanPanel.h
new file mode 100644
index 000000000..abbbc0ff1
--- /dev/null
+++ b/libs/ImguiExtension/panels/OceanPanel.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include "Panel.h"
+
+#include "ocean/Ocean.h"
+
+#include
+#include
+
+namespace Atlas::ImguiExtension {
+
+ class OceanPanel : public Panel {
+
+ public:
+ OceanPanel() : Panel("Ocean properties") {}
+
+ using TextureSelector = std::optional(ResourceHandle)>>;
+
+ void Render(Ref& ocean, TextureSelector textureSelector = {});
+
+ };
+
+}
diff --git a/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp b/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp
index 5353b058e..b8e306698 100644
--- a/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp
+++ b/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp
@@ -1,6 +1,6 @@
#include "PerformanceGraphPanel.h"
-#include "graphics/Profiler.h"
+#include "profiler/GPUProfiler.h"
#include "Clock.h"
namespace Atlas::ImguiExtension {
@@ -57,14 +57,14 @@ namespace Atlas::ImguiExtension {
void PerformanceGraphPanel::UpdateGraphData() {
- auto gpuProfilerData = Graphics::Profiler::GetQueries(Graphics::Profiler::OrderBy::MAX_TIME);
+ auto gpuProfilerData = GPUProfiler::GetQueries(GPUProfiler::OrderBy::MAX_TIME);
double slowestTime = 0.0;
for (int32_t i = 0; i < int32_t(gpuProfilerData.size()); i++) {
const auto& threadData = gpuProfilerData[i];
double threadTime = 0.0;
for (const auto& query : threadData.queries) {
- threadTime += query.timer.elapsedTime;
+ threadTime += query.elapsedTime;
}
if (threadTime > slowestTime) {
slowestTime = threadTime;
diff --git a/libs/ImguiExtension/panels/PostProcessingPanel.cpp b/libs/ImguiExtension/panels/PostProcessingPanel.cpp
index e538cbdfa..acc61d1be 100644
--- a/libs/ImguiExtension/panels/PostProcessingPanel.cpp
+++ b/libs/ImguiExtension/panels/PostProcessingPanel.cpp
@@ -7,75 +7,148 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
// Settings of disabled effects are shown, but greyed out
- ImGui::SeparatorText("Anti-aliasing and upscaling");
- ImGui::Checkbox("Temporal anti-aliasing##TAA", &postProcessing.taa.enable);
- ImGui::BeginDisabled(!postProcessing.taa.enable);
- ImGui::SliderFloat("Jitter range", &postProcessing.taa.jitterRange, 0.001f, 0.999f);
- ImGui::EndDisabled();
- ImGui::Checkbox("FSR2##FSR2", &postProcessing.fsr2);
+ UIElements::PropertySection("Anti-aliasing and upscaling");
+ if (UIElements::BeginProperties("PostProcessingUpscaling")) {
+ if (showUpscaler)
+ RenderUpscalerSelection(postProcessing.upscaler, isUpscalerSupported, true);
+ ImGui::BeginDisabled(postProcessing.upscaler == PostProcessing::Upscaler::None);
+ UIElements::PropertyLabel("Jitter range");
+ ImGui::SliderFloat("##Jitter range", &postProcessing.taa.jitterRange, 0.001f, 0.999f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
- ImGui::SeparatorText("Sharpen filter");
- ImGui::Checkbox("Enable##Sharpen", &postProcessing.sharpen.enable);
- ImGui::BeginDisabled(!postProcessing.sharpen.enable);
- ImGui::SliderFloat("Sharpness", &postProcessing.sharpen.factor, 0.0f, 1.0f);
- ImGui::EndDisabled();
+ UIElements::PropertySection("Sharpen filter");
+ if (UIElements::BeginProperties("PostProcessingSharpen")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.sharpen.enable);
+ ImGui::BeginDisabled(!postProcessing.sharpen.enable);
+ UIElements::PropertyLabel("Sharpness");
+ ImGui::SliderFloat("##Sharpness", &postProcessing.sharpen.factor, 0.0f, 1.0f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
- ImGui::SeparatorText("Image effects");
- ImGui::SliderFloat("Exposure compensation (EV)", &postProcessing.exposureCompensation, -10.0f, 10.0f);
- ImGui::Checkbox("Filmic tonemapping", &postProcessing.filmicTonemapping);
- ImGui::ColorEdit3("Tint", glm::value_ptr(postProcessing.tint));
- ImGui::SliderFloat("Saturation", &postProcessing.saturation, 0.0f, 2.0f);
- ImGui::SliderFloat("Contrast", &postProcessing.contrast, 0.0f, 2.0f);
- ImGui::SliderFloat("Paper white luminance", &postProcessing.paperWhiteLuminance, 0.0f, 300.0f);
- ImGui::SliderFloat("Maximum screen luminance", &postProcessing.screenMaxLuminance, 0.0f, 2000.0f);
-
- ImGui::SeparatorText("Chromatic aberration");
- ImGui::Checkbox("Enable##Chromatic aberration", &postProcessing.chromaticAberration.enable);
- ImGui::BeginDisabled(!postProcessing.chromaticAberration.enable);
- ImGui::Checkbox("Colors reversed", &postProcessing.chromaticAberration.colorsReversed);
- ImGui::SliderFloat("Strength##Chromatic abberation", &postProcessing.chromaticAberration.strength, 0.0f, 4.0f);
- ImGui::EndDisabled();
+ UIElements::PropertySection("Image effects");
+ if (UIElements::BeginProperties("PostProcessingImageEffects")) {
+ UIElements::PropertyLabel("Exposure compensation (EV)");
+ ImGui::SliderFloat("##Exposure compensation (EV)", &postProcessing.exposureCompensation, -10.0f, 10.0f);
+ UIElements::PropertyLabel("Filmic tonemapping");
+ ImGui::Checkbox("##Filmic tonemapping", &postProcessing.filmicTonemapping);
+ UIElements::PropertyLabel("Tint", "Multiplies the linear colors before tone mapping, bright surfaces stay white");
+ ImGui::ColorEdit3("##Tint", glm::value_ptr(postProcessing.tint));
+ UIElements::PropertyLabel("Saturation");
+ ImGui::SliderFloat("##Saturation", &postProcessing.saturation, 0.0f, 2.0f);
+ UIElements::PropertyLabel("Contrast");
+ ImGui::SliderFloat("##Contrast", &postProcessing.contrast, 0.0f, 2.0f);
+ UIElements::PropertyLabel("Paper white luminance");
+ ImGui::SliderFloat("##Paper white luminance", &postProcessing.paperWhiteLuminance, 0.0f, 300.0f);
+ UIElements::PropertyLabel("Maximum screen luminance");
+ ImGui::SliderFloat("##Maximum screen luminance", &postProcessing.screenMaxLuminance, 0.0f, 2000.0f);
+ UIElements::EndProperties();
+ }
- ImGui::SeparatorText("Film grain");
- ImGui::Checkbox("Enable##Film grain", &postProcessing.filmGrain.enable);
- ImGui::BeginDisabled(!postProcessing.filmGrain.enable);
- ImGui::SliderFloat("Strength##Film grain", &postProcessing.filmGrain.strength, 0.0f, 1.0f);
- ImGui::EndDisabled();
+ UIElements::PropertySection("Chromatic aberration");
+ if (UIElements::BeginProperties("PostProcessingChromaticAberration")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.chromaticAberration.enable);
+ ImGui::BeginDisabled(!postProcessing.chromaticAberration.enable);
+ UIElements::PropertyLabel("Colors reversed");
+ ImGui::Checkbox("##Colors reversed", &postProcessing.chromaticAberration.colorsReversed);
+ UIElements::PropertyLabel("Strength");
+ ImGui::SliderFloat("##Strength", &postProcessing.chromaticAberration.strength, 0.0f, 4.0f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
- ImGui::SeparatorText("Vignette");
- ImGui::Checkbox("Enable##Vignette", &postProcessing.vignette.enable);
- ImGui::BeginDisabled(!postProcessing.vignette.enable);
- ImGui::ColorEdit3("Color##Vignette", glm::value_ptr(postProcessing.vignette.color));
- ImGui::SliderFloat("Strength##Vignette", &postProcessing.vignette.strength, 0.0f, 1.0f);
- ImGui::SliderFloat("Power##Vignette", &postProcessing.vignette.power, 0.0f, 10.0f);
- ImGui::SliderFloat("Offset##Vignette", &postProcessing.vignette.offset, -1.0f, 1.0f);
- ImGui::EndDisabled();
+ UIElements::PropertySection("Film grain");
+ if (UIElements::BeginProperties("PostProcessingFilmGrain")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.filmGrain.enable);
+ ImGui::BeginDisabled(!postProcessing.filmGrain.enable);
+ UIElements::PropertyLabel("Strength");
+ ImGui::SliderFloat("##Strength", &postProcessing.filmGrain.strength, 0.0f, 1.0f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Vignette");
+ if (UIElements::BeginProperties("PostProcessingVignette")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.vignette.enable);
+ ImGui::BeginDisabled(!postProcessing.vignette.enable);
+ UIElements::PropertyLabel("Color");
+ ImGui::ColorEdit3("##Color", glm::value_ptr(postProcessing.vignette.color));
+ UIElements::PropertyLabel("Strength");
+ ImGui::SliderFloat("##Strength", &postProcessing.vignette.strength, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Power");
+ ImGui::SliderFloat("##Power", &postProcessing.vignette.power, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Offset");
+ ImGui::SliderFloat("##Offset", &postProcessing.vignette.offset, -1.0f, 1.0f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
- ImGui::SeparatorText("Bloom");
- ImGui::Checkbox("Enable##Bloom", &postProcessing.bloom.enable);
+ UIElements::PropertySection("Bloom");
+ if (UIElements::BeginProperties("PostProcessingBloomEnable")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.bloom.enable);
+ UIElements::EndProperties();
+ }
ImGui::BeginDisabled(!postProcessing.bloom.enable);
if (textureSelector.has_value())
postProcessing.bloom.dirtMap = textureSelector.value()(postProcessing.bloom.dirtMap);
- ImGui::DragFloat("Strength##Bloom", &postProcessing.bloom.strength, 0.001f, 0.0f, 1.0f);
- ImGui::DragFloat("Dirt strength##Bloom", &postProcessing.bloom.dirtStrength, 0.01f, 0.0f, 10.0f);
- ImGui::DragFloat("Threshold##Bloom", &postProcessing.bloom.threshold, 0.01f, 0.0f, 10.0f);
- ImGui::DragFloat("Filter size##Bloom", &postProcessing.bloom.filterSize, 0.001f, 0.0f, 1.0f);
- auto mipLevels = int32_t(postProcessing.bloom.mipLevels);
- ImGui::DragInt("Mip levels##Bloom", &mipLevels, 1, 2, 12);
- postProcessing.bloom.mipLevels = mipLevels;
+ if (UIElements::BeginProperties("PostProcessingBloom")) {
+ UIElements::PropertyLabel("Strength");
+ ImGui::DragFloat("##Strength", &postProcessing.bloom.strength, 0.001f, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Dirt strength");
+ ImGui::DragFloat("##Dirt strength", &postProcessing.bloom.dirtStrength, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Threshold");
+ ImGui::DragFloat("##Threshold", &postProcessing.bloom.threshold, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Filter size");
+ ImGui::DragFloat("##Filter size", &postProcessing.bloom.filterSize, 0.001f, 0.0f, 1.0f);
+ auto mipLevels = int32_t(postProcessing.bloom.mipLevels);
+ UIElements::PropertyLabel("Mip levels");
+ ImGui::DragInt("##Mip levels", &mipLevels, 1, 2, 12);
+ postProcessing.bloom.mipLevels = mipLevels;
+ UIElements::EndProperties();
+ }
ImGui::EndDisabled();
- ImGui::SeparatorText("Auto-exposure");
- ImGui::Checkbox("Enable##Exposure", &postProcessing.autoExposure.enable);
- ImGui::BeginDisabled(!postProcessing.autoExposure.enable);
- ImGui::DragFloat("Min luminance##Exposure", &postProcessing.autoExposure.luminanceMin, 0.0005f, 0.00001f, 1000.0f, "%.4f");
- ImGui::DragFloat("Max luminance##Exposure", &postProcessing.autoExposure.luminanceMax, 0.1f, 0.0f, 1000.0f, "%.4f");
- ImGui::DragFloat("Black level##Exposure", &postProcessing.autoExposure.blackLevel, 0.000001f, 0.0f, 1.0f, "%.6f");
- ImGui::DragFloat("Time coefficient##Exposure", &postProcessing.autoExposure.timeCoefficient, 0.01f, 0.0f, 10.0f);
- ImGui::EndDisabled();
+ UIElements::PropertySection("Auto-exposure");
+ if (UIElements::BeginProperties("PostProcessingAutoExposure")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &postProcessing.autoExposure.enable);
+ ImGui::BeginDisabled(!postProcessing.autoExposure.enable);
+ UIElements::PropertyLabel("Min luminance");
+ ImGui::DragFloat("##Min luminance", &postProcessing.autoExposure.luminanceMin, 0.0005f, 0.00001f, 1000.0f, "%.4f");
+ UIElements::PropertyLabel("Max luminance");
+ ImGui::DragFloat("##Max luminance", &postProcessing.autoExposure.luminanceMax, 10.0f,
+ postProcessing.autoExposure.luminanceMin, 1000000.0f, "%.1f", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Black level");
+ ImGui::DragFloat("##Black level", &postProcessing.autoExposure.blackLevel, 0.000001f, 0.0f, 1.0f, "%.6f");
+ UIElements::PropertyLabel("Time coefficient");
+ ImGui::DragFloat("##Time coefficient", &postProcessing.autoExposure.timeCoefficient, 0.01f, 0.0f, 10.0f);
+ ImGui::EndDisabled();
+ UIElements::EndProperties();
+ }
ImGui::PopID();
}
+ void PostProcessingPanel::RenderUpscalerSelection(PostProcessing::Upscaler& upscaler,
+ const std::function& isSupported, bool inProperties) {
+
+ const auto& names = PostProcessing::PostProcessing::upscalerNames;
+ auto selected = static_cast(upscaler);
+ if (inProperties)
+ UIElements::PropertyLabel("Upscaler");
+ if (ImGui::Combo(inProperties ? "##Upscaler" : "Upscaler", &selected, names, IM_ARRAYSIZE(names)))
+ upscaler = static_cast(selected);
+ if (isSupported && !isSupported(upscaler))
+ ImGui::TextDisabled("Not available on this device, FSR 2 is used instead");
+
+ }
+
}
diff --git a/libs/ImguiExtension/panels/PostProcessingPanel.h b/libs/ImguiExtension/panels/PostProcessingPanel.h
index 1da21855a..099c860d6 100644
--- a/libs/ImguiExtension/panels/PostProcessingPanel.h
+++ b/libs/ImguiExtension/panels/PostProcessingPanel.h
@@ -15,6 +15,15 @@ namespace Atlas::ImguiExtension {
void Render(PostProcessing::PostProcessing& postProcessing, TextureSelector textureSelector = {});
+ // Unsupported upscalers fall back to FSR2, the selection tells this when isSupported is set. Inside a properties
+ // table the label goes into its own column, otherwise ImGui draws it to the right
+ static void RenderUpscalerSelection(PostProcessing::Upscaler& upscaler,
+ const std::function& isSupported, bool inProperties);
+
+ std::function isUpscalerSupported;
+ // Hosts with the upscaler in other settings, e.g. the project settings of the editor, hide it here
+ bool showUpscaler = true;
+
};
}
\ No newline at end of file
diff --git a/libs/ImguiExtension/panels/ProfilerPanel.cpp b/libs/ImguiExtension/panels/ProfilerPanel.cpp
new file mode 100644
index 000000000..f7cf51d68
--- /dev/null
+++ b/libs/ImguiExtension/panels/ProfilerPanel.cpp
@@ -0,0 +1,476 @@
+#include "ProfilerPanel.h"
+#include "common/MathHelper.h"
+
+#include "profiler/CPUProfiler.h"
+#include "profiler/GPUProfiler.h"
+#include "Clock.h"
+
+#include
+#include
+#include
+
+namespace Atlas::ImguiExtension {
+
+ void ProfilerPanel::Refresh() {
+
+ auto order = GetOrder();
+ if (Clock::Get() - lastRefreshTime < 0.25f && order == refreshedOrder && lastRefreshTime >= 0.0f)
+ return;
+ lastRefreshTime = Clock::Get();
+ refreshedOrder = order;
+
+ // The main and the render thread come first and are open, the workers are listed collapsed
+ cpuThreads = CPUProfiler::enable ? CPUProfiler::GetQueriesAverage(64, order) : std::vector();
+ std::stable_partition(cpuThreads.begin(), cpuThreads.end(), [](const auto& thread) {
+ return thread.name == "Main" || thread.name == "Render";
+ });
+ gpuThreads = GPUProfiler::enable ? GPUProfiler::GetQueriesAverage(64, order) : std::vector();
+
+ }
+
+ void ProfilerPanel::Render() {
+
+ Refresh();
+ ImGui::PushID(GetNameID());
+
+ if (ImGui::BeginTabBar("Profilers")) {
+ if (ImGui::BeginTabItem("CPU")) {
+ if (RenderControls(CPUProfiler::enable, false))
+ RenderTable(cpuThreads, false);
+ ImGui::EndTabItem();
+ }
+ if (ImGui::BeginTabItem("GPU")) {
+ if (RenderControls(GPUProfiler::enable, true)) {
+ if (showGraph)
+ perfGraphPanel.Render();
+ else
+ RenderTable(gpuThreads, true);
+ }
+ ImGui::EndTabItem();
+ }
+ if (ImGui::BeginTabItem("Hitches")) {
+ RenderHitches();
+ ImGui::EndTabItem();
+ }
+ ImGui::EndTabBar();
+ }
+
+ ImGui::PopID();
+
+ }
+
+ bool ProfilerPanel::RenderControls(std::atomic_bool& enable, bool graph) {
+
+ bool enabled = enable;
+ ImGui::Checkbox("Enable##Profiler", &enabled);
+ enable = enabled;
+
+ if (graph) {
+ ImGui::SameLine();
+ ImGui::Checkbox("Show graph##Profiler", &showGraph);
+ }
+
+ if (!graph || !showGraph) {
+ const char* items[] = { "Chronologically", "Max time", "Min time", "Alphabetically" };
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(std::min(ImGui::GetContentRegionAvail().x * 0.5f, ImGui::GetFontSize() * 10.0f));
+ ImGui::Combo("Sort##Profiler", &sortItem, items, IM_ARRAYSIZE(items));
+ }
+
+ if (!enabled)
+ ImGui::TextDisabled("The profiler is disabled, enable it to collect timings");
+
+ return enabled;
+
+ }
+
+ void ProfilerPanel::RenderHitches() {
+
+ auto settings = HitchRecorder::GetSettings();
+ auto settingsChanged = false;
+
+ // The revision is read first, a hitch recorded meanwhile is copied in the next frame
+ auto revision = HitchRecorder::GetRevision();
+ if (revision != hitchRevision) {
+ hitchRevision = revision;
+ hitches = HitchRecorder::GetHitches();
+ hitchSummary = HitchRecorder::Evaluate(hitches);
+ }
+
+ settingsChanged |= ImGui::Checkbox("Record##Hitches", &settings.enable);
+ ImGui::SameLine();
+ if (ImGui::Button("Clear##Hitches"))
+ HitchRecorder::Clear();
+ ImGui::SameLine();
+ settingsChanged |= ImGui::Checkbox("Log##Hitches", &settings.log);
+ ImGui::SameLine();
+ ImGui::TextDisabled("%d hitches", int32_t(hitches.size()));
+
+ // Wide panels show the hitches and their causes next to the profile of the selected hitch
+ auto sideBySide = ImGui::GetContentRegionAvail().x >= ImGui::GetFontSize() * 50.0f;
+
+ if (ImGui::CollapsingHeader("Detection##Hitches"))
+ settingsChanged |= RenderHitchSettings(settings, sideBySide);
+
+ if (settingsChanged)
+ HitchRecorder::SetSettings(settings);
+
+ if (!sideBySide) {
+ if (ImGui::CollapsingHeader("Causes##Hitches", ImGuiTreeNodeFlags_DefaultOpen))
+ RenderHitchSummary(0.0f);
+ RenderHitchList(0.0f, settings.enable);
+ RenderHitchDetails();
+ return;
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingStretchProp;
+ if (ImGui::BeginTable("HitchLayout", 2, flags, ImVec2(0.0f, ImGui::GetContentRegionAvail().y))) {
+ ImGui::TableSetupColumn("Hitches", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableSetupColumn("Profile", ImGuiTableColumnFlags_WidthStretch, 1.0f);
+ ImGui::TableNextRow();
+
+ ImGui::TableNextColumn();
+ auto height = ImGui::GetContentRegionAvail().y;
+ ImGui::BeginChild("Hitches", ImVec2(0.0f, height));
+ auto listHeight = std::floor(ImGui::GetContentRegionAvail().y * 0.55f);
+ RenderHitchList(listHeight, settings.enable);
+ ImGui::SeparatorText("Causes");
+ RenderHitchSummary(ImGui::GetContentRegionAvail().y);
+ ImGui::EndChild();
+
+ ImGui::TableNextColumn();
+ ImGui::BeginChild("Profile", ImVec2(0.0f, height));
+ RenderHitchDetails();
+ ImGui::EndChild();
+
+ ImGui::EndTable();
+ }
+
+ }
+
+ bool ProfilerPanel::RenderHitchSettings(HitchRecorder::Settings& settings, bool sideBySide) {
+
+ auto changed = false;
+ // The render thread metric needs a render thread
+ auto hasRenderThread = CPUProfiler::GetThreadTime("Render") > 0.0f;
+
+ const char* triggers[] = { "Above minimum", "Above average", "Above minimum and average" };
+
+ auto renderDetector = [&](const char* label, HitchRecorder::Detector& detector, bool gpu) {
+ ImGui::PushID(label);
+ ImGui::SeparatorText(label);
+
+ changed |= ImGui::Checkbox("Detect", &detector.enable);
+
+ // The CPU detector measures the CPU metrics, the GPU detector the GPU ones
+ auto firstMetric = gpu ? int32_t(HitchRecorder::Metric::GPU_BUSY) : int32_t(HitchRecorder::Metric::FRAME_TIME);
+ auto metricCount = gpu ? 2 : 3;
+ auto metricIdx = std::clamp(int32_t(detector.metric) - firstMetric, 0, metricCount - 1);
+ if (ImGui::BeginCombo("Metric", HitchRecorder::GetMetricName(HitchRecorder::Metric(firstMetric + metricIdx)))) {
+ for (int32_t i = 0; i < metricCount; i++) {
+ auto metric = HitchRecorder::Metric(firstMetric + i);
+ auto selectableFlags = metric == HitchRecorder::Metric::RENDER_THREAD && !hasRenderThread ?
+ ImGuiSelectableFlags_Disabled : ImGuiSelectableFlags_None;
+ if (ImGui::Selectable(HitchRecorder::GetMetricName(metric), i == metricIdx, selectableFlags)) {
+ detector.metric = metric;
+ changed = true;
+ }
+ }
+ ImGui::EndCombo();
+ }
+
+ auto triggerIdx = int32_t(detector.trigger);
+ if (ImGui::Combo("Trigger", &triggerIdx, triggers, IM_ARRAYSIZE(triggers))) {
+ detector.trigger = HitchRecorder::Trigger(triggerIdx);
+ changed = true;
+ }
+
+ if (detector.trigger != HitchRecorder::Trigger::RELATIVE)
+ changed |= ImGui::DragFloat("Minimum time", &detector.minimumTime, 0.1f, 0.1f, 1000.0f, "%.1f ms",
+ ImGuiSliderFlags_AlwaysClamp);
+ if (detector.trigger != HitchRecorder::Trigger::ABSOLUTE)
+ changed |= ImGui::DragFloat("Relative to average", &detector.relativeThreshold, 0.01f, 1.1f, 20.0f, "%.2fx",
+ ImGuiSliderFlags_AlwaysClamp);
+ if (detector.metric == HitchRecorder::Metric::RENDER_THREAD && !hasRenderThread)
+ ImGui::TextDisabled("There is no render thread");
+
+ auto profilerEnabled = gpu ? GPUProfiler::enable.load() : CPUProfiler::enable.load();
+ if (detector.enable && !profilerEnabled) {
+ if (gpu || detector.metric != HitchRecorder::Metric::FRAME_TIME)
+ ImGui::TextDisabled("Needs the %s profiler, which is disabled", gpu ? "GPU" : "CPU");
+ else
+ ImGui::TextDisabled("The CPU profiler is disabled, hitches are recorded without a profile");
+ }
+
+ ImGui::PopID();
+ };
+
+ // The labels are on the right of the widgets and keep their room
+ if (sideBySide && ImGui::BeginTable("HitchDetectors", 2, ImGuiTableFlags_SizingStretchSame)) {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::PushItemWidth(-ImGui::GetFontSize() * 9.0f);
+ renderDetector("CPU", settings.cpu, false);
+ ImGui::PopItemWidth();
+ ImGui::TableNextColumn();
+ ImGui::PushItemWidth(-ImGui::GetFontSize() * 9.0f);
+ renderDetector("GPU", settings.gpu, true);
+ ImGui::PopItemWidth();
+ ImGui::EndTable();
+ }
+ else {
+ renderDetector("CPU", settings.cpu, false);
+ renderDetector("GPU", settings.gpu, true);
+ }
+
+ ImGui::Separator();
+ uint32_t minHitches = 1, maxHitches = 4096;
+ changed |= ImGui::DragScalar("Kept hitches", ImGuiDataType_U32, &settings.maxHitches, 1.0f, &minHitches, &maxHitches,
+ nullptr, ImGuiSliderFlags_AlwaysClamp);
+
+ return changed;
+
+ }
+
+ void ProfilerPanel::RenderHitchSummary(float height) {
+
+ if (hitchSummary.empty()) {
+ ImGui::TextWrapped("No causes yet, a cause is a query which took much longer than on average");
+ return;
+ }
+
+ if (height <= 0.0f) {
+ auto rows = std::min(int32_t(hitchSummary.size()), 8) + 1;
+ height = ImGui::GetTextLineHeightWithSpacing() * float(rows) + ImGui::GetStyle().CellPadding.y * 2.0f * float(rows);
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable |
+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY;
+ if (ImGui::BeginTable("HitchCauses", 5, flags, ImVec2(0.0f, height))) {
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::TableSetupColumn("Thread", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 8.0f);
+ ImGui::TableSetupColumn("Query", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableSetupColumn("Hitches", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f);
+ ImGui::TableSetupColumn("Excess (ms)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 6.0f);
+ ImGui::TableSetupColumn("Max (ms)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 5.0f);
+ ImGui::TableHeadersRow();
+
+ for (const auto& summary : hitchSummary) {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ ImGui::TextUnformatted(summary.thread.c_str());
+ ImGui::TableNextColumn();
+ ImGui::TextUnformatted(summary.path.c_str());
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("%s", summary.path.c_str());
+ ImGui::TableNextColumn();
+ ImGui::Text("%d", int32_t(summary.hitches));
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f", summary.totalExcess);
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f", summary.maxExcess);
+ }
+
+ ImGui::EndTable();
+ }
+
+ }
+
+ void ProfilerPanel::RenderHitchList(float height, bool recording) {
+
+ if (hitches.empty()) {
+ ImGui::TextDisabled(recording ? "No hitches recorded" : "Recording is disabled");
+ return;
+ }
+
+ auto selected = GetSelectedHitch();
+
+ if (height <= 0.0f) {
+ auto rows = std::min(int32_t(hitches.size()), 8) + 1;
+ height = ImGui::GetTextLineHeightWithSpacing() * float(rows) + ImGui::GetStyle().CellPadding.y * 2.0f * float(rows);
+ }
+
+ ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable |
+ ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY;
+ if (ImGui::BeginTable("HitchList", 6, flags, ImVec2(0.0f, height))) {
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::TableSetupColumn("Time (s)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 5.0f);
+ ImGui::TableSetupColumn("Metric", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 9.0f);
+ ImGui::TableSetupColumn("ms", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f);
+ ImGui::TableSetupColumn("Average", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f);
+ ImGui::TableSetupColumn("Factor", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f);
+ ImGui::TableSetupColumn("Main cause", ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableHeadersRow();
+
+ // The latest first, only the visible rows are drawn
+ ImGuiListClipper clipper;
+ clipper.Begin(int32_t(hitches.size()));
+ while (clipper.Step()) {
+ for (auto row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) {
+ const auto& hitch = *hitches[hitches.size() - 1 - size_t(row)];
+
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ char label[48];
+ std::snprintf(label, sizeof(label), "%.1f##%llu", hitch.time, static_cast(hitch.id));
+ if (ImGui::Selectable(label, hitch.id == selected->id, ImGuiSelectableFlags_SpanAllColumns))
+ selectedHitchId = hitch.id;
+ ImGui::TableNextColumn();
+ ImGui::Text("%s %s", hitch.source == HitchRecorder::Source::GPU ? "GPU" : "CPU",
+ HitchRecorder::GetMetricName(hitch.metric));
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f", hitch.frameTime);
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f", hitch.averageFrameTime);
+ ImGui::TableNextColumn();
+ if (hitch.averageFrameTime > 0.0f)
+ ImGui::Text("%.1fx", hitch.frameTime / hitch.averageFrameTime);
+ ImGui::TableNextColumn();
+ if (!hitch.causes.empty())
+ ImGui::Text("%s: %s", hitch.causes.front().thread.c_str(), hitch.causes.front().path.c_str());
+ else
+ ImGui::TextDisabled("-");
+ }
+ }
+
+ ImGui::EndTable();
+ }
+
+ }
+
+ void ProfilerPanel::RenderHitchDetails() {
+
+ auto selected = GetSelectedHitch();
+ if (!selected)
+ return;
+
+ const auto& hitch = *selected;
+ auto sourceName = hitch.source == HitchRecorder::Source::GPU ? "GPU" : "CPU";
+ ImGui::TextWrapped("%s hitch at %.1f s: %.1f ms %s, average %.1f ms", sourceName, hitch.time, hitch.frameTime,
+ HitchRecorder::GetMetricName(hitch.metric), hitch.averageFrameTime);
+ for (const auto& cause : hitch.causes)
+ ImGui::BulletText("%s: %s %.1f ms (average %.1f ms)", cause.thread.c_str(), cause.path.c_str(),
+ cause.time, cause.averageTime);
+
+ if (hitch.threads.empty())
+ ImGui::TextDisabled("No profile, the %s profiler was disabled", sourceName);
+ else
+ RenderTable(hitch.threads, hitch.source == HitchRecorder::Source::GPU);
+
+ }
+
+ const HitchRecorder::Hitch* ProfilerPanel::GetSelectedHitch() const {
+
+ if (hitches.empty())
+ return nullptr;
+
+ // Shows the latest hitch until another one is selected
+ auto selected = std::find_if(hitches.begin(), hitches.end(),
+ [&](const Ref& hitch) { return hitch->id == selectedHitchId; });
+ return selected != hitches.end() ? selected->get() : hitches.back().get();
+
+ }
+
+ void ProfilerPanel::RenderTable(const std::vector& threadData, bool openAllThreads) {
+
+ // Fraction of the thread time is drawn as a bar behind the time, such that expensive queries stand out
+ auto barColor = ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogram);
+ barColor.w *= 0.35f;
+ auto barColorU32 = ImGui::GetColorU32(barColor);
+
+ auto renderRightAligned = [](const char* text) {
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(text).x);
+ ImGui::TextUnformatted(text);
+ };
+
+ auto renderTime = [&](double elapsedNs, double totalNs) {
+ auto fraction = totalNs > 0.0 ? float(Helper::Math::Saturate(elapsedNs / totalNs)) : 0.0f;
+
+ auto cellMin = ImGui::GetCursorScreenPos();
+ auto cellWidth = ImGui::GetContentRegionAvail().x;
+ auto lineHeight = ImGui::GetTextLineHeight();
+ ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(cellMin.x, cellMin.y + lineHeight - 3.0f),
+ ImVec2(cellMin.x + cellWidth * fraction, cellMin.y + lineHeight), barColorU32, 1.5f);
+
+ char text[32];
+ std::snprintf(text, sizeof(text), "%.3f", elapsedNs / 1000000.0);
+ renderRightAligned(text);
+ };
+
+ std::function displayQuery;
+ displayQuery = [&](const Profiler::Query& query, double totalNs) {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+
+ ImGuiTreeNodeFlags expandable = 0;
+ if (!query.children.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen |
+ ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet;
+
+ bool open = ImGui::TreeNodeEx(query.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth);
+ ImGui::TableNextColumn();
+ renderRightAligned(std::to_string(query.calls).c_str());
+ ImGui::TableNextColumn();
+ renderTime(double(query.elapsedTime), totalNs);
+
+ if (open && query.children.size()) {
+ for (const auto& child : query.children)
+ displayQuery(child, totalNs);
+ ImGui::TreePop();
+ }
+ };
+
+ ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH |
+ ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody |
+ ImGuiTableFlags_ScrollY;
+
+ if (ImGui::BeginTable("PerfTable", 3, flags)) {
+ ImGui::TableSetupScrollFreeze(0, 1);
+ ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthStretch);
+ ImGui::TableSetupColumn("Calls", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed,
+ ImGui::GetFontSize() * 4.0f);
+ ImGui::TableSetupColumn("Time (ms)", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed,
+ ImGui::GetFontSize() * 10.0f);
+ ImGui::TableHeadersRow();
+
+ for (const auto& thread : threadData) {
+ double threadTime = 0.0;
+ for (const auto& query : thread.queries)
+ threadTime += double(query.elapsedTime);
+
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+
+ auto open = openAllThreads || thread.name == "Main" || thread.name == "Render";
+ ImGuiTreeNodeFlags expandable = open ? ImGuiTreeNodeFlags_DefaultOpen : 0;
+ if (!thread.queries.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen |
+ ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet;
+
+ bool isOpen = ImGui::TreeNodeEx(thread.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth);
+ ImGui::TableNextColumn();
+ ImGui::TableNextColumn();
+ renderTime(threadTime, 0.0);
+
+ if (isOpen && thread.queries.size()) {
+ for (const auto& query : thread.queries)
+ displayQuery(query, threadTime);
+ ImGui::TreePop();
+ }
+ }
+
+ ImGui::EndTable();
+ }
+
+ }
+
+ Profiler::OrderBy ProfilerPanel::GetOrder() const {
+
+ switch (sortItem) {
+ case 1: return Profiler::OrderBy::MAX_TIME;
+ case 2: return Profiler::OrderBy::MIN_TIME;
+ case 3: return Profiler::OrderBy::NAME;
+ default: return Profiler::OrderBy::CHRONO;
+ }
+
+ }
+
+}
diff --git a/libs/ImguiExtension/panels/ProfilerPanel.h b/libs/ImguiExtension/panels/ProfilerPanel.h
new file mode 100644
index 000000000..1a36555e9
--- /dev/null
+++ b/libs/ImguiExtension/panels/ProfilerPanel.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include "Panel.h"
+#include "PerformanceGraphPanel.h"
+
+#include "profiler/Profiler.h"
+#include "profiler/HitchRecorder.h"
+
+#include
+#include
+
+namespace Atlas::ImguiExtension {
+
+ class ProfilerPanel : public Panel {
+
+ public:
+ ProfilerPanel() : Panel("Profiler") {}
+
+ void Render();
+
+ // Averages of the queries over the history, refreshed a few times per second: merging the history of all
+ // threads every frame costs more than most of the work it measures
+ void Refresh();
+
+ std::vector cpuThreads;
+ std::vector gpuThreads;
+
+ bool showGraph = false;
+
+ int32_t sortItem = 0;
+
+ PerformanceGraphPanel perfGraphPanel;
+
+ private:
+ bool RenderControls(std::atomic_bool& enable, bool graph);
+
+ void RenderHitches();
+
+ // Returns whether the settings changed
+ bool RenderHitchSettings(HitchRecorder::Settings& settings, bool sideBySide);
+
+ // A height of 0 fits the table to its rows, at most a few
+ void RenderHitchSummary(float height);
+
+ void RenderHitchList(float height, bool recording);
+
+ void RenderHitchDetails();
+
+ // The selected hitch or the latest one
+ const HitchRecorder::Hitch* GetSelectedHitch() const;
+
+ void RenderTable(const std::vector& threadData, bool openAllThreads);
+
+ Profiler::OrderBy GetOrder() const;
+
+ // The recorded hitches, updated when the recorder changes
+ std::vector][> hitches;
+ std::vector hitchSummary;
+ uint64_t hitchRevision = std::numeric_limits::max();
+ uint64_t selectedHitchId = std::numeric_limits::max();
+
+ float lastRefreshTime = -1.0f;
+ Profiler::OrderBy refreshedOrder = Profiler::OrderBy::MAX_TIME;
+
+ };
+
+}
diff --git a/libs/ImguiExtension/panels/RTGIPanel.cpp b/libs/ImguiExtension/panels/RTGIPanel.cpp
index 5c82be13d..afc1d7708 100644
--- a/libs/ImguiExtension/panels/RTGIPanel.cpp
+++ b/libs/ImguiExtension/panels/RTGIPanel.cpp
@@ -1,42 +1,69 @@
#include "RTGIPanel.h"
+#include "graphics/GraphicsDevice.h"
+
namespace Atlas::ImguiExtension {
void RTGIPanel::Render(Ref& rtgi, Ref& target) {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &rtgi->enable);
- ImGui::Checkbox("Half resolution", &rtgi->halfResolution);
+ if (UIElements::BeginProperties("RTGIGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &rtgi->enable);
+ UIElements::PropertyLabel("Half resolution");
+ ImGui::Checkbox("##Half resolution", &rtgi->halfResolution);
- ImGui::Checkbox("Use shadow map", &rtgi->useShadowMap);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Uses the shadow map to calculate shadows in GI. "
- "This is only possible when cascaded shadow maps are not used.");
- }
- ImGui::Checkbox("Use normal maps", &rtgi->useNormalMaps);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Uses the normal maps to cast GI rays.");
+ UIElements::PropertyLabel("Use normal maps");
+ ImGui::Checkbox("##Use normal maps", &rtgi->useNormalMaps);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Uses the normal maps to cast GI rays.");
+ }
+ UIElements::PropertyLabel("Use DDGI as secondary bounce");
+ ImGui::Checkbox("##Use DDGI as secondary bounce", &rtgi->ddgi);
+ UIElements::PropertyLabel("Opacity check");
+ ImGui::Checkbox("##Opacity check", &rtgi->opacityCheck);
+ auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering;
+ UIElements::PropertyLabel("Shader execution reordering");
+ ImGui::BeginDisabled(!reorderSupported);
+ ImGui::Checkbox("##Shader execution reordering", &rtgi->shaderExecutionReordering);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, "
+ "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support");
+ }
+ ImGui::EndDisabled();
+ // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32);
+ UIElements::PropertyLabel("Radiance limit");
+ ImGui::DragFloat("##Radiance limit", &rtgi->radianceLimit, 0.1f, 0.0f, 1000.0f);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Limits the amount of incoming radiance. Is internally scale by the camera exposure.");
+ }
+ UIElements::PropertyLabel("Bias");
+ ImGui::SliderFloat("##Bias", &rtgi->bias, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Texture level");
+ ImGui::SliderInt("##Texture level", &rtgi->textureLevel, 0, 10);
+ UIElements::PropertyLabel("Sample count");
+ ImGui::SliderInt("##Sample count", &rtgi->sampleCount, 1, 10);
+ UIElements::PropertyLabel("Light sample count");
+ ImGui::SliderInt("##Light sample count", &rtgi->lightSampleCount, 1, 10);
+ UIElements::EndProperties();
}
- ImGui::Checkbox("Use DDGI as secondary bounce", &rtgi->ddgi);
- ImGui::Checkbox("Opacity check", &rtgi->opacityCheck);
- // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32);
- ImGui::DragFloat("Radiance limit", &rtgi->radianceLimit, 0.1f, 0.0f, 1000.0f);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Limits the amount of incoming radiance. Is internally scale by the camera exposure.");
+
+ UIElements::PropertySection("Denoiser");
+ if (UIElements::BeginProperties("RTGIDenoiser")) {
+ UIElements::PropertyLabel("Spatial filter strength");
+ ImGui::SliderFloat("##Spatial filter strength", &rtgi->spatialFilterStrength, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Temporal weight");
+ ImGui::SliderFloat("##Temporal weight", &rtgi->temporalWeight, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Maximum history clip factor");
+ ImGui::SliderFloat("##Maximum history clip factor", &rtgi->historyClipMax, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Current clip factor");
+ ImGui::SliderFloat("##Current clip factor", &rtgi->currentClipFactor, 0.0f, 10.0f);
+ UIElements::EndProperties();
}
- ImGui::SliderFloat("Bias", &rtgi->bias, 0.0f, 1.0f);
- ImGui::SliderInt("Texture level##RTGI", &rtgi->textureLevel, 0, 10);
- ImGui::SliderInt("Sample count##RTGI", &rtgi->sampleCount, 1, 10);
- ImGui::SliderInt("Light sample count##RTGI", &rtgi->lightSampleCount, 1, 10);
- ImGui::SeparatorText("Denoiser");
- ImGui::SliderFloat("Spatial filter strength", &rtgi->spatialFilterStrength, 0.0f, 10.0f);
- ImGui::SliderFloat("Temporal weight", &rtgi->temporalWeight, 0.0f, 1.0f);
- ImGui::SliderFloat("Maximum history clip factor", &rtgi->historyClipMax, 0.0f, 1.0f);
- ImGui::SliderFloat("Current clip factor", &rtgi->currentClipFactor, 0.0f, 10.0f);
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/ImguiExtension/panels/ReflectionPanel.cpp b/libs/ImguiExtension/panels/ReflectionPanel.cpp
index 3737eeddb..732c36bb5 100644
--- a/libs/ImguiExtension/panels/ReflectionPanel.cpp
+++ b/libs/ImguiExtension/panels/ReflectionPanel.cpp
@@ -1,44 +1,75 @@
#include "ReflectionPanel.h"
+#include "graphics/GraphicsDevice.h"
+
namespace Atlas::ImguiExtension {
void ReflectionPanel::Render(Ref &reflection, Ref& target) {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &reflection->enable);
- ImGui::Checkbox("Enable RT", &reflection->rt);
- ImGui::Checkbox("Enable SSR", &reflection->ssr);
- ImGui::Checkbox("Half resolution", &reflection->halfResolution);
- ImGui::Checkbox("Upsample before filtering", &reflection->upsampleBeforeFiltering);
-
- //ImGui::Checkbox("Enable raytracing##Reflection", &reflection->rt);
- ImGui::Checkbox("Use shadow map", &reflection->useShadowMap);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Uses the shadow map to calculate shadows in reflections. "
- "This is only possible when cascaded shadow maps are not used.");
+ if (UIElements::BeginProperties("ReflectionGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &reflection->enable);
+ UIElements::PropertyLabel("Enable RT");
+ ImGui::Checkbox("##Enable RT", &reflection->rt);
+ UIElements::PropertyLabel("Enable SSR");
+ ImGui::Checkbox("##Enable SSR", &reflection->ssr);
+ UIElements::PropertyLabel("Half resolution");
+ ImGui::Checkbox("##Half resolution", &reflection->halfResolution);
+ UIElements::PropertyLabel("Upsample before filtering");
+ ImGui::Checkbox("##Upsample before filtering", &reflection->upsampleBeforeFiltering);
+
+ //ImGui::Checkbox("Enable raytracing##Reflection", &reflection->rt);
+ UIElements::PropertyLabel("Use normal maps");
+ ImGui::Checkbox("##Use normal maps", &reflection->useNormalMaps);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Uses the normal maps to cast reflection rays.");
+ }
+ UIElements::PropertyLabel("Use DDGI in reflection");
+ ImGui::Checkbox("##Use DDGI in reflection", &reflection->ddgi);
+ UIElements::PropertyLabel("Opacity check");
+ ImGui::Checkbox("##Opacity check", &reflection->opacityCheck);
+ auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering;
+ UIElements::PropertyLabel("Shader execution reordering");
+ ImGui::BeginDisabled(!reorderSupported);
+ ImGui::Checkbox("##Shader execution reordering", &reflection->shaderExecutionReordering);
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
+ ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, "
+ "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support");
+ }
+ ImGui::EndDisabled();
+ // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32);
+ UIElements::PropertyLabel("Radiance limit");
+ ImGui::DragFloat("##Radiance limit", &reflection->radianceLimit, 0.1f, 0.0f, 1000.0f);
+ UIElements::PropertyLabel("Bias");
+ ImGui::SliderFloat("##Bias", &reflection->bias, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Roughness cuttoff");
+ ImGui::SliderFloat("##Roughness cuttoff", &reflection->roughnessCutoff, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Texture level");
+ ImGui::SliderInt("##Texture level", &reflection->textureLevel, 0, 10);
+ UIElements::PropertyLabel("Sample count");
+ ImGui::SliderInt("##Sample count", &reflection->sampleCount, 1, 10);
+ UIElements::PropertyLabel("Light sample count");
+ ImGui::SliderInt("##Light sample count", &reflection->lightSampleCount, 1, 10);
+ UIElements::EndProperties();
}
- ImGui::Checkbox("Use normal maps", &reflection->useNormalMaps);
- if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
- ImGui::SetTooltip("Uses the normal maps to cast reflection rays.");
+
+ UIElements::PropertySection("Denoiser");
+ if (UIElements::BeginProperties("ReflectionDenoiser")) {
+ UIElements::PropertyLabel("Spatial filter strength");
+ ImGui::SliderFloat("##Spatial filter strength", &reflection->spatialFilterStrength, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Temporal weight");
+ ImGui::SliderFloat("##Temporal weight", &reflection->temporalWeight, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Maximum history clip factor");
+ ImGui::SliderFloat("##Maximum history clip factor", &reflection->historyClipMax, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Current clip factor");
+ ImGui::SliderFloat("##Current clip factor", &reflection->currentClipFactor, 0.0f, 10.0f);
+ UIElements::EndProperties();
}
- ImGui::Checkbox("Use DDGI in reflection", &reflection->ddgi);
- ImGui::Checkbox("Opacity check", &reflection->opacityCheck);
- // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32);
- ImGui::DragFloat("Radiance limit", &reflection->radianceLimit, 0.1f, 0.0f, 1000.0f);
- ImGui::SliderFloat("Bias", &reflection->bias, 0.0f, 1.0f);
- ImGui::SliderFloat("Roughness cuttoff", &reflection->roughnessCutoff, 0.0f, 1.0f);
- ImGui::SliderInt("Texture level##Reflection", &reflection->textureLevel, 0, 10);
- ImGui::SliderInt("Sample count##Reflection", &reflection->sampleCount, 1, 10);
- ImGui::SliderInt("Light sample count##Reflection", &reflection->lightSampleCount, 1, 10);
- ImGui::SeparatorText("Denoiser");
- ImGui::SliderFloat("Spatial filter strength", &reflection->spatialFilterStrength, 0.0f, 10.0f);
- ImGui::SliderFloat("Temporal weight", &reflection->temporalWeight, 0.0f, 1.0f);
- ImGui::SliderFloat("Maximum history clip factor", &reflection->historyClipMax, 0.0f, 1.0f);
- ImGui::SliderFloat("Current clip factor", &reflection->currentClipFactor, 0.0f, 10.0f);
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/ImguiExtension/panels/SSGIPanel.cpp b/libs/ImguiExtension/panels/SSGIPanel.cpp
index 6a13c8014..314a69a62 100644
--- a/libs/ImguiExtension/panels/SSGIPanel.cpp
+++ b/libs/ImguiExtension/panels/SSGIPanel.cpp
@@ -6,18 +6,31 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &ssgi->enable);
- ImGui::Checkbox("Half resolution", &ssgi->halfResolution);
-
- ImGui::Checkbox("Enable ambient occlusion", &ssgi->enableAo);
- ImGui::SliderInt("Ray count", &ssgi->rayCount, 1, 8);
- ImGui::SliderInt("Sample count", &ssgi->sampleCount, 1, 16);
- ImGui::SliderFloat("Radius", &ssgi->radius, 0.0f, 10.0f);
- ImGui::SliderFloat("Ao strength", &ssgi->aoStrength, 0.0f, 10.0f);
- ImGui::DragFloat("Irradiance limit", &ssgi->irradianceLimit, 0.1f, 0.0f, 1000.0f);
+ if (UIElements::BeginProperties("SSGIGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &ssgi->enable);
+ UIElements::PropertyLabel("Half resolution");
+ ImGui::Checkbox("##Half resolution", &ssgi->halfResolution);
+
+ UIElements::PropertyLabel("Enable ambient occlusion");
+ ImGui::Checkbox("##Enable ambient occlusion", &ssgi->enableAo);
+ UIElements::PropertyLabel("Ray count");
+ ImGui::DragInt("##Ray count", &ssgi->rayCount, 0.1f, 1, 8);
+ UIElements::PropertyLabel("Sample count");
+ ImGui::DragInt("##Sample count", &ssgi->sampleCount, 0.1f, 1, 16);
+ UIElements::PropertyLabel("Radius");
+ ImGui::DragFloat("##Radius", &ssgi->radius, 1.0f, 0.0f, 2000.0f);
+ UIElements::PropertyLabel("Thickness");
+ ImGui::DragFloat("##Thickness", &ssgi->thickness, 0.001f, 0.0f, 0.2f, "%.3f");
+ UIElements::PropertyLabel("Ao strength");
+ ImGui::DragFloat("##Ao strength", &ssgi->aoStrength, 0.01f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Irradiance limit");
+ ImGui::DragFloat("##Irradiance limit", &ssgi->irradianceLimit, 0.1f, 0.0f, 1000.0f);
+ UIElements::EndProperties();
+ }
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/ImguiExtension/panels/SSSPanel.cpp b/libs/ImguiExtension/panels/SSSPanel.cpp
index 5454b21b6..522b22601 100644
--- a/libs/ImguiExtension/panels/SSSPanel.cpp
+++ b/libs/ImguiExtension/panels/SSSPanel.cpp
@@ -6,15 +6,24 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &sss->enable);
- ImGui::Checkbox("Trace in world space", &sss->traceWorldSpace);
- ImGui::DragInt("Sample count", &sss->sampleCount, 1.f, 2, 64);
- ImGui::SliderFloat("Max length", &sss->maxLength, 0.01f, 1.0f);
- ImGui::SliderFloat("Min length world space", &sss->minLengthWorldSpace, 0.01f, 1.0f);
- ImGui::SliderFloat("Thickness", &sss->thickness, 0.001f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ if (UIElements::BeginProperties("SSSGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &sss->enable);
+ UIElements::PropertyLabel("Trace in world space");
+ ImGui::Checkbox("##Trace in world space", &sss->traceWorldSpace);
+ UIElements::PropertyLabel("Sample count");
+ ImGui::DragInt("##Sample count", &sss->sampleCount, 1.f, 2, 64);
+ UIElements::PropertyLabel("Max length");
+ ImGui::SliderFloat("##Max length", &sss->maxLength, 0.01f, 1.0f);
+ UIElements::PropertyLabel("Min length world space");
+ ImGui::SliderFloat("##Min length world space", &sss->minLengthWorldSpace, 0.01f, 1.0f);
+ UIElements::PropertyLabel("Thickness");
+ ImGui::SliderFloat("##Thickness", &sss->thickness, 0.001f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ UIElements::EndProperties();
+ }
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/ImguiExtension/panels/SkyPanel.cpp b/libs/ImguiExtension/panels/SkyPanel.cpp
index f381e7b0c..3326f0cf8 100644
--- a/libs/ImguiExtension/panels/SkyPanel.cpp
+++ b/libs/ImguiExtension/panels/SkyPanel.cpp
@@ -10,11 +10,11 @@ namespace Atlas::ImguiExtension {
if (sky.probe)
cubemap = sky.probe->cubemap;
- ImGui::SeparatorText("Environment map");
+ UIElements::PropertySection("Environment map");
if (cubemapSelector.has_value()) {
cubemap = cubemapSelector.value()(cubemap);
}
-
+
if (cubemap.IsValid() && !sky.probe)
sky.probe = CreateRef(cubemap);
else if (!cubemap.IsValid() && sky.probe)
@@ -26,14 +26,28 @@ namespace Atlas::ImguiExtension {
atmosphere->rayleighScatteringCoeff *= 1e6f;
atmosphere->mieScatteringCoeff *= 1e6f;
- ImGui::SeparatorText("Atmosphere");
- bool atmosphereChanged = false;
- atmosphereChanged |= ImGui::DragFloat3("Rayleigh scattering coefficient", glm::value_ptr(atmosphere->rayleighScatteringCoeff), 0.1f, 0.0f, 10e10f);
- atmosphereChanged |= ImGui::ColorEdit3("Ground albedo", glm::value_ptr(atmosphere->groundAlbedo));
- atmosphereChanged |= ImGui::DragFloat("Mie scattering coefficient", &atmosphere->mieScatteringCoeff, 1.0f, 0.0f, 10e10f);
- atmosphereChanged |= ImGui::DragFloat("Rayleigh height scale", &atmosphere->rayleighHeightScale, 100.0f, 0.0f, 10e10f);
- atmosphereChanged |= ImGui::DragFloat("Mie height scale", &atmosphere->mieHeightScale, 100.0f, 0.0f, 10e10f);
- atmosphere->needsUpdate |= atmosphereChanged;
+ UIElements::PropertySection("Atmosphere");
+ if (UIElements::BeginProperties("SkyAtmosphere")) {
+ bool atmosphereChanged = false;
+ UIElements::PropertyLabel("Rayleigh scattering coefficient");
+ atmosphereChanged |= ImGui::DragFloat3("##Rayleigh scattering coefficient", glm::value_ptr(atmosphere->rayleighScatteringCoeff), 0.1f, 0.0f, 10e10f);
+ UIElements::PropertyLabel("Ground albedo");
+ atmosphereChanged |= ImGui::ColorEdit3("##Ground albedo", glm::value_ptr(atmosphere->groundAlbedo));
+ UIElements::PropertyLabel("Mie scattering coefficient");
+ atmosphereChanged |= ImGui::DragFloat("##Mie scattering coefficient", &atmosphere->mieScatteringCoeff, 1.0f, 0.0f, 10e10f);
+ UIElements::PropertyLabel("Rayleigh height scale");
+ atmosphereChanged |= ImGui::DragFloat("##Rayleigh height scale", &atmosphere->rayleighHeightScale, 100.0f, 0.0f, 10e10f);
+ UIElements::PropertyLabel("Mie height scale");
+ atmosphereChanged |= ImGui::DragFloat("##Mie height scale", &atmosphere->mieHeightScale, 100.0f, 0.0f, 10e10f);
+ atmosphere->needsUpdate |= atmosphereChanged;
+ UIElements::PropertyLabel("Sun disk size", "Angular diameter of the sun, the real sun has about 0.53 degrees");
+ ImGui::DragFloat("##Sun disk size", &atmosphere->sunDiskSize, 0.01f, 0.01f, 20.0f, "%.2f deg");
+ UIElements::PropertyLabel("Direct light", "How much the air colors and dims the sun's light, red and weak near the horizon at 1");
+ ImGui::SliderFloat("##Direct light", &atmosphere->directLight, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Indirect light", "How much the sky lights the scene: ambient light, global illumination and sky reflections");
+ ImGui::SliderFloat("##Indirect light", &atmosphere->indirectLight, 0.0f, 2.0f);
+ UIElements::EndProperties();
+ }
atmosphere->rayleighScatteringCoeff /= 1e6f;
atmosphere->mieScatteringCoeff /= 1e6f;
diff --git a/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp b/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp
index 7c3fde73e..f0c81cf4c 100644
--- a/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp
+++ b/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp
@@ -6,33 +6,89 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::Checkbox("Enable", &clouds->enable);
+ if (UIElements::BeginProperties("CloudsGeneral")) {
+ UIElements::PropertyLabel("Enable");
+ ImGui::Checkbox("##Enable", &clouds->enable);
+ UIElements::EndProperties();
+ }
// Settings of disabled clouds are shown, but greyed out
ImGui::BeginDisabled(!clouds->enable);
- ImGui::Checkbox("Cast shadow", &clouds->castShadow);
-
- ImGui::SeparatorText("Shape");
- ImGui::SliderFloat("Coverage", &clouds->coverage, 0.0f, 1.0f);
- ImGui::SliderFloat("Cloud type", &clouds->cloudType, 0.0f, 1.0f);
- ImGui::SetItemTooltip("Continuous blend: stratus (0), stratocumulus (0.5), cumulus (1)");
- ImGui::SliderFloat("Cloud size", &clouds->cloudSize, 100.0f, 10000.0f, "%.0f m", ImGuiSliderFlags_Logarithmic);
- ImGui::SliderFloat("Vertical development", &clouds->verticalDevelopment, 0.0f, 1.0f);
- ImGui::SetItemTooltip("Controls billow proportions and height variation within the cloud layer");
- ImGui::SliderFloat("Detail", &clouds->detail, 0.0f, 1.0f);
- ImGui::SliderFloat("Density", &clouds->densityMultiplier, 0.0f, 2.0f);
-
- ImGui::SeparatorText("Layer");
- ImGui::DragFloat("Base altitude", &clouds->baseAltitude, 10.0f, 0.0f, 20000.0f, "%.0f m");
- ImGui::DragFloat("Layer thickness", &clouds->layerThickness, 10.0f, 1.0f, 10000.0f, "%.0f m");
- ImGui::SliderFloat("Distance limit", &clouds->distanceLimit, 1000.0f, 40000.0f, "%.0f m");
- if (ImGui::SliderFloat("Variation seed", &clouds->variationSeed, 0.0f, 100.0f))
- clouds->needsNoiseUpdate = true;
-
- ImGui::SeparatorText("Quality");
- ImGui::Combo("Quality", &clouds->quality, "Low\0Medium\0High\0Ultra\0");
- ImGui::SetItemTooltip("Controls ray samples, lighting samples and volumetric resolution (shared with fog)");
- ImGui::Checkbox("Debug", &debug);
+ if (UIElements::BeginProperties("CloudsShadow")) {
+ UIElements::PropertyLabel("Cast shadow");
+ ImGui::Checkbox("##Cast shadow", &clouds->castShadow);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Shape");
+ if (UIElements::BeginProperties("CloudsShape")) {
+ UIElements::PropertyLabel("Coverage");
+ ImGui::SliderFloat("##Coverage", &clouds->coverage, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Cloud type", "Continuous blend: stratus (0), stratocumulus (0.5), cumulus (1)");
+ ImGui::SliderFloat("##Cloud type", &clouds->cloudType, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Cloud size");
+ ImGui::SliderFloat("##Cloud size", &clouds->cloudSize, 100.0f, 10000.0f, "%.0f m", ImGuiSliderFlags_Logarithmic);
+ UIElements::PropertyLabel("Vertical development", "Controls billow proportions and height variation within the cloud layer");
+ ImGui::SliderFloat("##Vertical development", &clouds->verticalDevelopment, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Detail");
+ ImGui::SliderFloat("##Detail", &clouds->detail, 0.0f, 1.0f);
+ UIElements::PropertyLabel("Density");
+ ImGui::SliderFloat("##Density", &clouds->densityMultiplier, 0.0f, 2.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Layer");
+ if (UIElements::BeginProperties("CloudsLayer")) {
+ UIElements::PropertyLabel("Base altitude");
+ ImGui::DragFloat("##Base altitude", &clouds->baseAltitude, 10.0f, 0.0f, 20000.0f, "%.0f m");
+ UIElements::PropertyLabel("Layer thickness");
+ ImGui::DragFloat("##Layer thickness", &clouds->layerThickness, 10.0f, 1.0f, 10000.0f, "%.0f m");
+ UIElements::PropertyLabel("Distance limit");
+ ImGui::SliderFloat("##Distance limit", &clouds->distanceLimit, 1000.0f, 40000.0f, "%.0f m");
+ UIElements::PropertyLabel("Variation seed");
+ if (ImGui::SliderFloat("##Variation seed", &clouds->variationSeed, 0.0f, 100.0f))
+ clouds->needsNoiseUpdate = true;
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Scattering");
+ auto& scattering = clouds->scattering;
+ if (UIElements::BeginProperties("CloudsScattering")) {
+ UIElements::PropertyLabel("Extinction", "How much light the cloud medium absorbs and scatters per density, higher values make clouds more opaque");
+ ImGui::DragFloat("##Extinction", &scattering.extinctionFactor, 0.001f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Extinction color", "Relative extinction per channel, lower values let more of that color pass through");
+ ImGui::ColorEdit3("##Extinction color", &scattering.extinctionCoefficients[0]);
+ UIElements::PropertyLabel("Scattering", "Brightness of the light scattered towards the viewer");
+ ImGui::DragFloat("##Scattering", &scattering.scatteringFactor, 0.001f, 0.0f, 10.0f);
+ UIElements::PropertyLabel("Eccentricity first phase");
+ ImGui::SliderFloat("##Eccentricity first phase", &scattering.eccentricityFirstPhase, -0.99f, 0.99f);
+ UIElements::PropertyLabel("Eccentricity second phase", "Positive values scatter forward (silver lining towards the sun), negative values backward");
+ ImGui::SliderFloat("##Eccentricity second phase", &scattering.eccentricitySecondPhase, -0.99f, 0.99f);
+ UIElements::PropertyLabel("Phase blend", "Blend from the first (0) to the second (1) phase function");
+ ImGui::SliderFloat("##Phase blend", &scattering.phaseAlpha, 0.0f, 1.0f);
+ UIElements::EndProperties();
+ }
+
+ UIElements::PropertySection("Quality");
+ if (UIElements::BeginProperties("CloudsQuality")) {
+ UIElements::PropertyLabel("Quality", "Controls ray samples, lighting samples and volumetric resolution (shared with fog)");
+ ImGui::Combo("##Quality", &clouds->quality, "Low\0Medium\0High\0Ultra\0");
+
+ const int32_t shadowResolutions[] = { 512, 1024, 2048, 4096 };
+ auto shadowResolutionItem = 0;
+ for (int32_t i = 0; i < IM_ARRAYSIZE(shadowResolutions); i++)
+ if (clouds->shadowTexture.width == shadowResolutions[i])
+ shadowResolutionItem = i;
+ ImGui::BeginDisabled(!clouds->castShadow);
+ UIElements::PropertyLabel("Shadow resolution");
+ if (ImGui::Combo("##Shadow resolution", &shadowResolutionItem, "512x512\0" "1024x1024\0" "2048x2048\0" "4096x4096\0"))
+ clouds->SetShadowResolution(shadowResolutions[shadowResolutionItem]);
+ ImGui::EndDisabled();
+
+ UIElements::PropertyLabel("Debug");
+ ImGui::Checkbox("##Debug", &debug);
+ UIElements::EndProperties();
+ }
ImGui::EndDisabled();
diff --git a/libs/ImguiExtension/panels/WindPanel.cpp b/libs/ImguiExtension/panels/WindPanel.cpp
index 63b760de9..187dbbd02 100644
--- a/libs/ImguiExtension/panels/WindPanel.cpp
+++ b/libs/ImguiExtension/panels/WindPanel.cpp
@@ -6,17 +6,22 @@ namespace Atlas::ImguiExtension {
ImGui::PushID(GetNameID());
- ImGui::SeparatorText("Noise texture");
+ UIElements::PropertySection("Noise texture");
UIElements::TextureView(wrapper, &wind.noiseMap, 255.0f);
ImGui::Separator();
- ImGui::DragFloat2("Wind direction", glm::value_ptr(wind.direction), 0.01f, -1.0f, 1.0f);
- ImGui::DragFloat("Wind speed", &wind.speed, 0.5f, 0.0f, 100.0f);
+ if (UIElements::BeginProperties("WindGeneral")) {
+ UIElements::PropertyLabel("Wind direction");
+ ImGui::DragFloat2("##Wind direction", glm::value_ptr(wind.direction), 0.01f, -1.0f, 1.0f);
+ UIElements::PropertyLabel("Wind speed");
+ ImGui::DragFloat("##Wind speed", &wind.speed, 0.5f, 0.0f, 100.0f);
+ UIElements::EndProperties();
+ }
ImGui::PopID();
}
-}
\ No newline at end of file
+}
diff --git a/libs/upscalers/README.md b/libs/upscalers/README.md
new file mode 100644
index 000000000..4dc1c0bf5
--- /dev/null
+++ b/libs/upscalers/README.md
@@ -0,0 +1,40 @@
+# Vendor upscalers
+
+Optional upscalers selected with `PostProcessing::upscaler`. Each one lives in its own folder and is compiled
+into the engine only when its SDK is found. Without the SDK, or on a GPU it doesn't support, the engine uses
+FSR2 instead (`MainRenderer::IsUpscalerSupported`). The SDKs aren't part of the repository.
+
+| Upscaler | SDK folder | Platforms | Runtime library |
+|----------|------------|-----------|-----------------|
+| DLSS | `dlss/sdk` or `ATLAS_DLSS_SDK` | Windows, Linux | `nvngx_dlss.dll` / `libnvidia-ngx-dlss.so.*` |
+| FSR 4 | `fsr4/sdk` or `ATLAS_FSR4_SDK` | Windows | `amd_fidelityfx_upscaler_vk.dll` |
+
+Set `ATLAS_DLSS=OFF` or `ATLAS_FSR4=OFF` to build without an SDK that is present.
+
+## DLSS
+
+From the [DLSS SDK](https://github.com/NVIDIA/DLSS) copy into `dlss/sdk`:
+
+- `include/`
+- `lib/Windows_x86_64/x64/` (`nvsdk_ngx_d.lib`, `nvsdk_ngx_d_dbg.lib`) and `lib/Windows_x86_64/rel/nvngx_dlss.dll`
+- `lib/Linux_x86_64/libnvsdk_ngx.a` and `lib/Linux_x86_64/rel/libnvidia-ngx-dlss.so.*`
+- `LICENSE.txt`
+
+`lib/Windows_x86_64/dev` contains a DLSS library with debug overlays and hotkeys for checking jitter, motion
+vectors and exposure. NGX needs an NVIDIA RTX GPU and loads the DLSS library from the executable folder or the SDK.
+
+## FSR 4
+
+From the [AMD FSR SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK) (2.4 or newer) copy into `fsr4/sdk`:
+
+- `Kits/FidelityFX/api/include/` to `api/include/`
+- `Kits/FidelityFX/upscalers/include/` to `upscalers/include/`
+- `Kits/FidelityFX/signedbin/amd_fidelityfx_upscaler_vk.dll` to `bin/`
+- `Kits/FidelityFX/docs/license.md`
+
+The signed library selects the upscaler version for the GPU: the machine learning FSR 4 on supported AMD GPUs with a
+recent driver, FSR 3 otherwise. The log names the version in use.
+
+## Packaging
+
+Ship the runtime library next to the executable together with the SDK license.
diff --git a/libs/upscalers/Upscalers.cmake b/libs/upscalers/Upscalers.cmake
new file mode 100644
index 000000000..ab6b30913
--- /dev/null
+++ b/libs/upscalers/Upscalers.cmake
@@ -0,0 +1,5 @@
+# Optional upscalers of vendor SDKs, compiled into the AtlasEngine target. An upscaler is only built when its SDK
+# was found, without it or on GPUs it doesn't support the engine falls back to FSR2 (see README.md)
+get_filename_component(ATLAS_UPSCALER_ADDONS_SOURCE ${CMAKE_CURRENT_LIST_DIR}/../../src/engine/renderer/UpscalerAddons.cpp ABSOLUTE)
+include(${CMAKE_CURRENT_LIST_DIR}/dlss/DLSS.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/fsr4/FSR4.cmake)
diff --git a/libs/upscalers/dlss/DLSS.cmake b/libs/upscalers/dlss/DLSS.cmake
new file mode 100644
index 000000000..f1cefbb65
--- /dev/null
+++ b/libs/upscalers/dlss/DLSS.cmake
@@ -0,0 +1,23 @@
+option(ATLAS_DLSS "Build the DLSS upscaler when its SDK is found" ON)
+set(ATLAS_DLSS_SDK "${CMAKE_CURRENT_LIST_DIR}/sdk" CACHE PATH "DLSS SDK with the include and lib folders of github.com/NVIDIA/DLSS")
+
+if (ATLAS_DLSS AND EXISTS "${ATLAS_DLSS_SDK}/include/nvsdk_ngx_vk.h" AND (WIN32 OR (UNIX AND NOT APPLE AND NOT ANDROID)))
+ message(STATUS "Building the DLSS upscaler with ${ATLAS_DLSS_SDK}")
+
+ target_sources(AtlasEngine PRIVATE ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.cpp ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.h)
+ target_include_directories(AtlasEngine PRIVATE ${ATLAS_DLSS_SDK}/include)
+
+ # NGX loads the DLSS library from the executable folder, other than in release builds also from this one
+ if (WIN32)
+ target_link_libraries(AtlasEngine LINK_PRIVATE
+ "${ATLAS_DLSS_SDK}/lib/Windows_x86_64/x64/nvsdk_ngx_d$<$:_dbg>.lib")
+ set(ATLAS_DLSS_RUNTIME_DIR "${ATLAS_DLSS_SDK}/lib/Windows_x86_64/rel")
+ else()
+ target_link_libraries(AtlasEngine LINK_PRIVATE "${ATLAS_DLSS_SDK}/lib/Linux_x86_64/libnvsdk_ngx.a" dl)
+ set(ATLAS_DLSS_RUNTIME_DIR "${ATLAS_DLSS_SDK}/lib/Linux_x86_64/rel")
+ endif()
+
+ # Only for the files which use it, the precompiled header of the engine is shared with the applications
+ set_property(SOURCE ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.cpp ${ATLAS_UPSCALER_ADDONS_SOURCE} APPEND PROPERTY
+ COMPILE_DEFINITIONS AE_UPSCALER_DLSS "$<$>:AE_DLSS_RUNTIME_DIR=\"${ATLAS_DLSS_RUNTIME_DIR}\">")
+endif()
diff --git a/libs/upscalers/dlss/DLSSRenderer.cpp b/libs/upscalers/dlss/DLSSRenderer.cpp
new file mode 100644
index 000000000..a28f45504
--- /dev/null
+++ b/libs/upscalers/dlss/DLSSRenderer.cpp
@@ -0,0 +1,237 @@
+#include "DLSSRenderer.h"
+#include "graphics/Instance.h"
+
+#include
+
+#include
+
+namespace Atlas::Renderer {
+
+ struct DLSSRenderer::Helpers {
+ static constexpr const char* projectId = "e71a5590-902c-44c5-a774-a3323a389902";
+ static constexpr const char* engineVersion = "0.2.1";
+
+ static const wchar_t* GetDataPath() {
+
+ // NGX writes its logs there
+ static const std::wstring path = std::filesystem::temp_directory_path().wstring();
+ return path.c_str();
+
+ }
+
+ static const NVSDK_NGX_FeatureCommonInfo* GetFeatureInfo() {
+
+ // The DLSS library is searched next to the executable first, other than in release builds then in the SDK
+#ifdef AE_DLSS_RUNTIME_DIR
+ static const std::wstring runtimeDir = std::filesystem::path(AE_DLSS_RUNTIME_DIR).wstring();
+ static const wchar_t* paths[] = { runtimeDir.c_str() };
+ static NVSDK_NGX_FeatureCommonInfo info = { .PathListInfo = { .Path = paths, .Length = 1 } };
+#else
+ static NVSDK_NGX_FeatureCommonInfo info = {};
+#endif
+ return &info;
+
+ }
+
+ static NVSDK_NGX_FeatureDiscoveryInfo GetDiscoveryInfo() {
+
+ NVSDK_NGX_FeatureDiscoveryInfo info = {};
+ info.SDKVersion = NVSDK_NGX_Version_API;
+ info.FeatureID = NVSDK_NGX_Feature_SuperSampling;
+ info.Identifier.IdentifierType = NVSDK_NGX_Application_Identifier_Type_Project_Id;
+ info.Identifier.v.ProjectDesc = { projectId, NVSDK_NGX_ENGINE_TYPE_CUSTOM, engineVersion };
+ info.ApplicationDataPath = GetDataPath();
+ info.FeatureInfo = GetFeatureInfo();
+ return info;
+
+ }
+
+ static std::vector GetExtensionNames(NVSDK_NGX_Result result, uint32_t count, const VkExtensionProperties* properties) {
+
+ std::vector names;
+ if (NVSDK_NGX_FAILED(result))
+ return names;
+
+ for (uint32_t i = 0; i < count; i++)
+ names.emplace_back(properties[i].extensionName);
+ return names;
+
+ }
+
+ static NVSDK_NGX_PerfQuality_Value GetPerfQuality(float scale) {
+
+ // Only selects the default preset, the render size comes from the render target
+ if (scale >= 0.99f) return NVSDK_NGX_PerfQuality_Value_DLAA;
+ if (scale >= 0.62f) return NVSDK_NGX_PerfQuality_Value_MaxQuality;
+ if (scale >= 0.54f) return NVSDK_NGX_PerfQuality_Value_Balanced;
+ if (scale >= 0.42f) return NVSDK_NGX_PerfQuality_Value_MaxPerf;
+ return NVSDK_NGX_PerfQuality_Value_UltraPerformance;
+
+ }
+ };
+
+ DLSSRenderer::DLSSRenderer(Graphics::GraphicsDevice* device) {
+
+ this->device = device;
+
+ auto result = NVSDK_NGX_VULKAN_Init_with_ProjectID(Helpers::projectId, NVSDK_NGX_ENGINE_TYPE_CUSTOM, Helpers::engineVersion,
+ Helpers::GetDataPath(), device->instance->GetNativeInstance(), device->physicalDevice, device->device,
+ vkGetInstanceProcAddr, vkGetDeviceProcAddr, Helpers::GetFeatureInfo());
+ if (NVSDK_NGX_FAILED(result)) {
+ Log::Message("DLSS isn't available on this device (NGX result " + std::to_string(int32_t(result)) + ")");
+ return;
+ }
+ initialized = true;
+
+ int32_t available = 0, needsUpdatedDriver = 0;
+ result = NVSDK_NGX_VULKAN_GetCapabilityParameters(¶meters);
+ if (NVSDK_NGX_SUCCEED(result)) {
+ NVSDK_NGX_Parameter_GetI(parameters, NVSDK_NGX_Parameter_SuperSampling_Available, &available);
+ NVSDK_NGX_Parameter_GetI(parameters, NVSDK_NGX_Parameter_SuperSampling_NeedsUpdatedDriver, &needsUpdatedDriver);
+ }
+
+ supported = available != 0;
+ if (supported)
+ Log::Message("DLSS is available");
+ else if (needsUpdatedDriver)
+ Log::Warning("DLSS needs a newer driver");
+ else
+ Log::Message("DLSS isn't available on this device");
+
+ }
+
+ DLSSRenderer::~DLSSRenderer() {
+
+ if (!initialized)
+ return;
+
+ DLSSRenderer::DestroyContext();
+ if (parameters)
+ NVSDK_NGX_VULKAN_DestroyParameters(parameters);
+ NVSDK_NGX_VULKAN_Shutdown1(device->device);
+
+ }
+
+ void DLSSRenderer::Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) {
+
+ GPUProfiler::Scope gpuScope("DLSS");
+
+ auto renderSize = ivec2(target->GetScaledWidth(), target->GetScaledHeight());
+
+ auto& camera = scene->renderState.camera;
+ auto targetData = target->GetData(FULL_RES);
+
+ auto colorImage = target->lightingTexture.image;
+ auto depthImage = targetData->depthTexture->image;
+ auto velocityImage = target->GetVelocity()->image;
+ auto outputImage = target->hdrTexture.image;
+
+ // NGX writes the output with compute and transfer commands (it clears it on a reset)
+ Graphics::ImageBarrier imageBarriers[] = {
+ {colorImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {depthImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {velocityImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {outputImage, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT},
+ };
+ commandList->PipelineBarrier(imageBarriers, {}, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
+
+ auto getResource = [](const Ref& image, bool readWrite) {
+ VkImageSubresourceRange range = { image->aspectFlags, 0, 1, 0, 1 };
+ return NVSDK_NGX_Create_ImageView_Resource_VK(image->view, image->image, range, image->format,
+ image->width, image->height, readWrite);
+ };
+
+ auto color = getResource(colorImage, false);
+ auto depth = getResource(depthImage, false);
+ auto velocity = getResource(velocityImage, false);
+ auto output = getResource(outputImage, true);
+
+ NVSDK_NGX_VK_DLSS_Eval_Params evalParams = {};
+ evalParams.Feature.pInColor = &color;
+ evalParams.Feature.pInOutput = &output;
+ evalParams.pInDepth = &depth;
+ evalParams.pInMotionVectors = &velocity;
+ // Same conventions as for FSR2: jitter in render pixels, motion vectors in UV space towards the last frame
+ evalParams.InJitterOffsetX = camera.GetJitter().x * float(renderSize.x) * 0.5f;
+ evalParams.InJitterOffsetY = camera.GetJitter().y * float(renderSize.y) * 0.5f;
+ evalParams.InMVScaleX = float(renderSize.x);
+ evalParams.InMVScaleY = float(renderSize.y);
+ evalParams.InRenderSubrectDimensions = { uint32_t(renderSize.x), uint32_t(renderSize.y) };
+ evalParams.InReset = target->HasHistory() ? 0 : 1;
+ evalParams.InFrameTimeDeltaInMsec = scene->renderState.deltaTime * 1000.0f;
+ evalParams.InPreExposure = scene->renderState.preExposure;
+
+ auto result = NGX_VULKAN_EVALUATE_DLSS_EXT(commandList->commandBuffer, feature, parameters, &evalParams);
+ commandList->InvalidateBoundState();
+ if (NVSDK_NGX_FAILED(result)) {
+ Log::Warning("DLSS evaluation failed (NGX result " + std::to_string(int32_t(result)) + "), using FSR 2 instead");
+ MarkContextFailed();
+ }
+
+ commandList->ImageMemoryBarrier(outputImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
+ VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
+ VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
+
+ }
+
+ std::vector DLSSRenderer::GetInstanceExtensions() {
+
+ auto discoveryInfo = Helpers::GetDiscoveryInfo();
+ uint32_t count = 0;
+ VkExtensionProperties* properties = nullptr;
+ auto result = NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements(&discoveryInfo, &count, &properties);
+ return Helpers::GetExtensionNames(result, count, properties);
+
+ }
+
+ std::vector DLSSRenderer::GetDeviceExtensions(VkInstance instance, VkPhysicalDevice physicalDevice) {
+
+ auto discoveryInfo = Helpers::GetDiscoveryInfo();
+ uint32_t count = 0;
+ VkExtensionProperties* properties = nullptr;
+ auto result = NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements(instance, physicalDevice,
+ &discoveryInfo, &count, &properties);
+ return Helpers::GetExtensionNames(result, count, properties);
+
+ }
+
+ bool DLSSRenderer::CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) {
+
+ NVSDK_NGX_DLSS_Create_Params createParams = {};
+ createParams.Feature.InWidth = uint32_t(renderSize.x);
+ createParams.Feature.InHeight = uint32_t(renderSize.y);
+ createParams.Feature.InTargetWidth = uint32_t(displaySize.x);
+ createParams.Feature.InTargetHeight = uint32_t(displaySize.y);
+ createParams.Feature.InPerfQualityValue = Helpers::GetPerfQuality(float(renderSize.x) / float(displaySize.x));
+ // The lighting is linear HDR, the exposure is only known after the upscaling
+ createParams.InFeatureCreateFlags = NVSDK_NGX_DLSS_Feature_Flags_IsHDR | NVSDK_NGX_DLSS_Feature_Flags_MVLowRes |
+ NVSDK_NGX_DLSS_Feature_Flags_AutoExposure;
+
+ auto result = NGX_VULKAN_CREATE_DLSS_EXT1(device->device, commandList->commandBuffer, 1, 1,
+ &feature, parameters, &createParams);
+ commandList->InvalidateBoundState();
+
+ if (NVSDK_NGX_FAILED(result)) {
+ Log::Warning("Couldn't create the DLSS feature for " + std::to_string(renderSize.x) + "x" + std::to_string(renderSize.y) +
+ " (NGX result " + std::to_string(int32_t(result)) + "), using FSR 2 instead");
+ feature = nullptr;
+ return false;
+ }
+
+ return true;
+
+ }
+
+ void DLSSRenderer::DestroyContext() {
+
+ if (!feature)
+ return;
+
+ // The feature may still be used by command lists in flight
+ device->WaitForIdle();
+ NVSDK_NGX_VULKAN_ReleaseFeature(feature);
+ feature = nullptr;
+
+ }
+
+}
diff --git a/libs/upscalers/dlss/DLSSRenderer.h b/libs/upscalers/dlss/DLSSRenderer.h
new file mode 100644
index 000000000..a322797be
--- /dev/null
+++ b/libs/upscalers/dlss/DLSSRenderer.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include "renderer/UpscalingRenderer.h"
+
+struct NVSDK_NGX_Handle;
+struct NVSDK_NGX_Parameter;
+
+namespace Atlas::Renderer {
+
+ // NVIDIA DLSS super resolution through NGX, which loads the DLSS library of the SDK
+ class DLSSRenderer : public VendorUpscalingRenderer {
+
+ public:
+ explicit DLSSRenderer(Graphics::GraphicsDevice* device);
+
+ ~DLSSRenderer();
+
+ bool IsSupported() const override { return supported; }
+
+ void Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) override;
+
+ static std::vector GetInstanceExtensions();
+
+ static std::vector GetDeviceExtensions(VkInstance instance, VkPhysicalDevice physicalDevice);
+
+ protected:
+ bool HasContext() const override { return feature != nullptr; }
+
+ bool CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) override;
+
+ void DestroyContext() override;
+
+ private:
+ // Defined with the source file, their types stay out of this header
+ struct Helpers;
+
+ bool initialized = false;
+ bool supported = false;
+
+ NVSDK_NGX_Parameter* parameters = nullptr;
+ NVSDK_NGX_Handle* feature = nullptr;
+
+ };
+
+}
diff --git a/libs/upscalers/fsr4/FSR4.cmake b/libs/upscalers/fsr4/FSR4.cmake
new file mode 100644
index 000000000..274c0527e
--- /dev/null
+++ b/libs/upscalers/fsr4/FSR4.cmake
@@ -0,0 +1,14 @@
+option(ATLAS_FSR4 "Build the FSR 4 upscaler when its SDK is found" ON)
+set(ATLAS_FSR4_SDK "${CMAKE_CURRENT_LIST_DIR}/sdk" CACHE PATH "Headers and the signed Vulkan upscaler library of the AMD FSR SDK")
+
+# The SDK only has signed libraries for Windows
+if (ATLAS_FSR4 AND EXISTS "${ATLAS_FSR4_SDK}/upscalers/include/ffx_upscale.h" AND WIN32)
+ message(STATUS "Building the FSR 4 upscaler with ${ATLAS_FSR4_SDK}")
+
+ target_sources(AtlasEngine PRIVATE ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.cpp ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.h)
+ target_include_directories(AtlasEngine PRIVATE ${ATLAS_FSR4_SDK})
+
+ # The upscaler library is loaded at runtime from the executable folder, other than in release builds also from this one
+ set_property(SOURCE ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.cpp ${ATLAS_UPSCALER_ADDONS_SOURCE} APPEND PROPERTY
+ COMPILE_DEFINITIONS AE_UPSCALER_FSR4 "$<$>:AE_FSR4_RUNTIME_DIR=\"${ATLAS_FSR4_SDK}/bin\">")
+endif()
diff --git a/libs/upscalers/fsr4/FSR4Renderer.cpp b/libs/upscalers/fsr4/FSR4Renderer.cpp
new file mode 100644
index 000000000..b51d184c5
--- /dev/null
+++ b/libs/upscalers/fsr4/FSR4Renderer.cpp
@@ -0,0 +1,237 @@
+#include "FSR4Renderer.h"
+
+#include
+#include
+
+#include
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include
+
+namespace Atlas::Renderer {
+
+ struct FSR4Renderer::Functions {
+ PfnFfxCreateContext createContext = nullptr;
+ PfnFfxDestroyContext destroyContext = nullptr;
+ PfnFfxQuery query = nullptr;
+ PfnFfxDispatch dispatch = nullptr;
+ };
+
+ struct FSR4Renderer::Helpers {
+ static constexpr const wchar_t* libraryName = L"amd_fidelityfx_upscaler_vk.dll";
+
+ static HMODULE LoadUpscalerLibrary() {
+
+ // The library is searched next to the executable first, other than in release builds then in the SDK
+ wchar_t executablePath[MAX_PATH];
+ GetModuleFileNameW(nullptr, executablePath, MAX_PATH);
+ auto path = std::filesystem::path(executablePath).parent_path() / libraryName;
+#ifdef AE_FSR4_RUNTIME_DIR
+ if (!std::filesystem::exists(path))
+ path = std::filesystem::path(AE_FSR4_RUNTIME_DIR) / libraryName;
+#endif
+
+ return LoadLibraryW(path.c_str());
+
+ }
+
+ static void LogMessage(uint32_t type, const wchar_t* message) {
+
+ auto text = "FSR: " + std::filesystem::path(message).string();
+ if (type == FFX_API_MESSAGE_TYPE_ERROR)
+ Log::Error(text);
+ else
+ Log::Warning(text);
+
+ }
+
+ static FfxApiResource GetResource(const Ref& image, uint32_t usage, uint32_t state) {
+
+ FfxApiResourceDescription description = {};
+ description.type = FFX_API_RESOURCE_TYPE_TEXTURE2D;
+ description.format = ffxApiGetSurfaceFormatVK(image->format);
+ description.width = image->width;
+ description.height = image->height;
+ description.depth = 1;
+ description.mipCount = 1;
+ description.usage = usage;
+
+ return ffxApiGetResourceVK(reinterpret_cast(image->image), description, state);
+
+ }
+ };
+
+ FSR4Renderer::FSR4Renderer(Graphics::GraphicsDevice* device) : functions(std::make_unique()) {
+
+ this->device = device;
+
+ auto module = Helpers::LoadUpscalerLibrary();
+ if (!module) {
+ Log::Message("FSR 4 isn't available, " + std::filesystem::path(Helpers::libraryName).string() + " wasn't found");
+ return;
+ }
+ library = module;
+
+ functions->createContext = reinterpret_cast(GetProcAddress(module, "ffxCreateContext"));
+ functions->destroyContext = reinterpret_cast(GetProcAddress(module, "ffxDestroyContext"));
+ functions->query = reinterpret_cast(GetProcAddress(module, "ffxQuery"));
+ functions->dispatch = reinterpret_cast(GetProcAddress(module, "ffxDispatch"));
+
+ VkDeviceContext deviceContext = { device->device, device->physicalDevice, vkGetDeviceProcAddr };
+
+ uint64_t versionCount = 0;
+ ffxQueryDescGetVersions versionQuery = {};
+ versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;
+ versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE;
+ versionQuery.device = &deviceContext;
+ versionQuery.outputCount = &versionCount;
+ functions->query(nullptr, &versionQuery.header);
+
+ std::vector versionNames(versionCount);
+ versionQuery.versionNames = versionNames.data();
+ functions->query(nullptr, &versionQuery.header);
+
+ std::string versions;
+ for (auto name : versionNames)
+ versions += (versions.empty() ? "" : ", ") + std::string(name);
+
+ supported = versionCount > 0;
+ if (supported)
+ Log::Message("FSR upscaler versions available on this device: " + versions);
+ else
+ Log::Message("The FSR upscaler isn't available on this device");
+
+ }
+
+ FSR4Renderer::~FSR4Renderer() {
+
+ FSR4Renderer::DestroyContext();
+ if (library)
+ FreeLibrary(static_cast(library));
+
+ }
+
+ void FSR4Renderer::Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) {
+
+ GPUProfiler::Scope gpuScope("FSR4");
+
+ auto renderSize = ivec2(target->GetScaledWidth(), target->GetScaledHeight());
+ auto displaySize = ivec2(target->GetWidth(), target->GetHeight());
+
+ auto& postProcessing = scene->renderState.postProcessing;
+ auto& camera = scene->renderState.camera;
+ auto targetData = target->GetData(FULL_RES);
+
+ auto colorImage = target->lightingTexture.image;
+ auto depthImage = targetData->depthTexture->image;
+ auto velocityImage = target->GetVelocity()->image;
+ auto reactiveMaskImage = target->reactiveMaskTexture.image;
+ auto outputImage = target->hdrTexture.image;
+
+ bool reactiveMask = !target->IsUsedForPathTracing();
+
+ std::vector imageBarriers = {
+ {colorImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {depthImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {velocityImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT},
+ {outputImage, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_SHADER_WRITE_BIT},
+ };
+ if (reactiveMask)
+ imageBarriers.push_back({reactiveMaskImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT});
+ commandList->PipelineBarrier(imageBarriers, {}, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
+
+ ffxDispatchDescUpscale dispatch = {};
+ dispatch.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE;
+ dispatch.commandList = commandList->commandBuffer;
+ dispatch.color = Helpers::GetResource(colorImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ);
+ dispatch.depth = Helpers::GetResource(depthImage, FFX_API_RESOURCE_USAGE_DEPTHTARGET, FFX_API_RESOURCE_STATE_COMPUTE_READ);
+ dispatch.motionVectors = Helpers::GetResource(velocityImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ);
+ if (reactiveMask)
+ dispatch.reactive = Helpers::GetResource(reactiveMaskImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ);
+ dispatch.output = Helpers::GetResource(outputImage, FFX_API_RESOURCE_USAGE_UAV, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS);
+ // Same conventions as for FSR2: jitter in render pixels, motion vectors in UV space towards the last frame
+ dispatch.jitterOffset = { camera.GetJitter().x * float(renderSize.x) * 0.5f, camera.GetJitter().y * float(renderSize.y) * 0.5f };
+ dispatch.motionVectorScale = { float(renderSize.x), float(renderSize.y) };
+ dispatch.renderSize = { uint32_t(renderSize.x), uint32_t(renderSize.y) };
+ dispatch.upscaleSize = { uint32_t(displaySize.x), uint32_t(displaySize.y) };
+ dispatch.enableSharpening = postProcessing.sharpen.enable;
+ dispatch.sharpness = postProcessing.sharpen.factor;
+ dispatch.frameTimeDelta = scene->renderState.deltaTime * 1000.0f;
+ dispatch.preExposure = scene->renderState.preExposure;
+ dispatch.reset = !target->HasHistory();
+ dispatch.cameraNear = camera.nearPlane;
+ dispatch.cameraFar = camera.farPlane;
+ dispatch.cameraFovAngleVertical = glm::radians(camera.fieldOfView);
+ dispatch.viewSpaceToMetersFactor = 1.0f;
+
+ auto result = functions->dispatch(&context, &dispatch.header);
+ commandList->InvalidateBoundState();
+ if (result != FFX_API_RETURN_OK) {
+ Log::Warning("The FSR dispatch failed (result " + std::to_string(result) + "), using FSR 2 instead");
+ MarkContextFailed();
+ }
+
+ commandList->ImageMemoryBarrier(outputImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
+ VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
+ VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
+
+ }
+
+ std::vector FSR4Renderer::GetDeviceExtensions() {
+
+ // The machine learning upscaler runs with cooperative matrices, on RDNA 4 with 8 bit floats
+ return { VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME, VK_EXT_SHADER_FLOAT8_EXTENSION_NAME };
+
+ }
+
+ bool FSR4Renderer::CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) {
+
+ ffxCreateBackendVKDesc backendDesc = {};
+ backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK;
+ backendDesc.deviceContext = { device->device, device->physicalDevice, vkGetDeviceProcAddr };
+
+ ffxCreateContextDescUpscale createDesc = {};
+ createDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE;
+ createDesc.header.pNext = &backendDesc.header;
+ // The lighting is linear HDR, the exposure is only known after the upscaling
+ createDesc.flags = FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE;
+ createDesc.maxRenderSize = { uint32_t(renderSize.x), uint32_t(renderSize.y) };
+ createDesc.maxUpscaleSize = { uint32_t(displaySize.x), uint32_t(displaySize.y) };
+ createDesc.fpMessage = Helpers::LogMessage;
+
+ auto result = functions->createContext(&context, &createDesc.header, nullptr);
+ if (result != FFX_API_RETURN_OK) {
+ Log::Warning("Couldn't create the FSR upscaler context for " + std::to_string(renderSize.x) + "x" + std::to_string(renderSize.y) +
+ " (result " + std::to_string(result) + "), using FSR 2 instead");
+ context = nullptr;
+ return false;
+ }
+
+ ffxQueryGetProviderVersion versionQuery = {};
+ versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION;
+ functions->query(&context, &versionQuery.header);
+ if (versionQuery.versionName)
+ Log::Message("Upscaling with FSR " + std::string(versionQuery.versionName));
+
+ return true;
+
+ }
+
+ void FSR4Renderer::DestroyContext() {
+
+ if (!context)
+ return;
+
+ // The context may still be used by command lists in flight
+ device->WaitForIdle();
+ functions->destroyContext(&context, nullptr);
+ context = nullptr;
+
+ }
+
+}
diff --git a/libs/upscalers/fsr4/FSR4Renderer.h b/libs/upscalers/fsr4/FSR4Renderer.h
new file mode 100644
index 000000000..d1d105ebd
--- /dev/null
+++ b/libs/upscalers/fsr4/FSR4Renderer.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include "renderer/UpscalingRenderer.h"
+
+namespace Atlas::Renderer {
+
+ // AMD FSR upscaler of the FSR SDK, whose signed library selects FSR 4 on supported GPUs and FSR 3 otherwise
+ class FSR4Renderer : public VendorUpscalingRenderer {
+
+ public:
+ explicit FSR4Renderer(Graphics::GraphicsDevice* device);
+
+ ~FSR4Renderer();
+
+ bool IsSupported() const override { return supported; }
+
+ bool UsesReactiveMask() const override { return true; }
+
+ bool Sharpens() const override { return true; }
+
+ void Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) override;
+
+ static std::vector GetDeviceExtensions();
+
+ protected:
+ bool HasContext() const override { return context != nullptr; }
+
+ bool CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) override;
+
+ void DestroyContext() override;
+
+ private:
+ struct Functions;
+ // Defined with the source file, their types stay out of this header
+ struct Helpers;
+
+ void* library = nullptr;
+ std::unique_ptr functions;
+ void* context = nullptr;
+
+ bool supported = false;
+
+ };
+
+}
diff --git a/src/bridge/App.cpp b/src/bridge/App.cpp
new file mode 100644
index 000000000..285fdb862
--- /dev/null
+++ b/src/bridge/App.cpp
@@ -0,0 +1,2084 @@
+#include "App.h"
+#include "TerrainTools.h"
+#include "SceneEditor.h"
+#include "Check.h"
+#include "Summary.h"
+#include "Tools.h"
+#include "InstanceRegistry.h"
+#include "Processes.h"
+
+#include "Serializer.h"
+#include "loader/ImageLoader.h"
+#include "resource/ResourceManager.h"
+#include "scripting/Script.h"
+#include "scene/components/LuaScriptComponent.h"
+#include "graphics/GraphicsDevice.h"
+#include "profiler/CPUProfiler.h"
+#include "profiler/GPUProfiler.h"
+#include "profiler/HitchRecorder.h"
+#include "streaming/StreamingManager.h"
+#include "materialgraph/PipelineCache.h"
+#include "Clock.h"
+#include "audio/AudioManager.h"
+
+#include
+
+#include
+#include
+
+const Atlas::EngineConfig Atlas::EngineInstance::engineConfig = {
+ .assetDirectory = "../../data",
+ .shaderDirectory = "shader",
+ .commandLineTool = [](const std::vector& args) { return Atlas::Bridge::RunCommandLineTool(args, "../../data"); }
+};
+
+namespace Atlas::Bridge {
+
+ using namespace Scene::Components;
+
+ struct ViewAngles {
+
+ float azimuth;
+ float elevation;
+
+ };
+
+ static ViewAngles GetViewAngles(const std::string& view) {
+
+ // Azimuth 0 places the camera on the +Z side looking towards -Z
+ static const std::map views = {
+ { "front", { 0.0f, 15.0f } },
+ { "right", { 90.0f, 15.0f } },
+ { "back", { 180.0f, 15.0f } },
+ { "left", { 270.0f, 15.0f } },
+ { "top", { 0.0f, 89.0f } },
+ { "iso", { 45.0f, 35.0f } },
+ // Almost at ground level, best to see whether something floats
+ { "low", { 0.0f, 2.0f } },
+ { "lowSide", { 90.0f, 2.0f } },
+ };
+
+ auto it = views.find(view);
+ if (it == views.end())
+ throw std::runtime_error("Unknown view '" + view + "' (front, right, back, left, top, iso, low, lowSide)");
+
+ return it->second;
+
+ }
+
+ // Keep scripts active with a minimal time step while waiting for real-time playback
+ static constexpr float freezeDeltaTime = 1e-5f;
+
+ void App::LoadContent() {
+
+ startTime = std::chrono::steady_clock::now();
+ report.InstallCrashHandlers();
+ InstanceRegistry::Register(args);
+
+ // Pictures never show the fallback of a material graph
+ MaterialGraph::PipelineCache::asynchronous = false;
+
+ // Jobs edit, save and bake resources and take pictures right away, --streaming measures the streaming instead.
+ // A pipeline without shots never takes pictures: it streams, so a world build doesn't fill the GPU memory
+ auto hasArg = [&](const char* arg) { return std::find(args.begin(), args.end(), arg) != args.end(); };
+ if (hasArg("--pipeline") && hasArg("--no-shots")) {
+ // Edits need little of the GPU: what the pipeline window shows stays small, impostors are baked at full size
+ Streaming::StreamingManager::settings.textures.budget = 512;
+ Streaming::StreamingManager::settings.impostors.budget = 512;
+ Streaming::StreamingManager::settings.meshes.budget = 1024;
+ }
+ else if (!hasArg("--streaming")) {
+ Streaming::StreamingManager::settings.textures.enable = false;
+ Streaming::StreamingManager::settings.impostors.enable = false;
+ Streaming::StreamingManager::settings.meshes.enable = false;
+ }
+
+ // A server or a pipeline runs several jobs, the other options of the command line apply to each of them
+ std::string serve, pipelineFile, from;
+ bool force = false;
+ for (size_t i = 1; i < args.size(); i++) {
+ if (args[i] == "--serve" && i + 1 < args.size())
+ serve = args[++i];
+ else if (args[i] == "--pipeline" && i + 1 < args.size())
+ pipelineFile = args[++i];
+ else if (args[i] == "--from" && i + 1 < args.size())
+ from = args[++i];
+ else if (args[i] == "--force")
+ force = true;
+ else
+ jobArguments.push_back(args[i]);
+ }
+
+ // Muted until a job asks for the sound
+ Audio::AudioManager::Mute();
+
+ try {
+ if (!serve.empty()) {
+ mode = Mode::Server;
+ std::vector serverOptions;
+ for (const auto& option : { "--streaming", "--validation" })
+ if (std::find(args.begin(), args.end(), option) != args.end())
+ serverOptions.push_back(option);
+ server.emplace(ResolveUserPath(serve), serverOptions);
+
+ // Scenes can be loaded before the first job, which sets up the renderer for its resolution
+ captureRenderer.Init(mainRenderer, job.resolution);
+ defaultRenderScale = captureRenderer.GetRenderScale();
+ rendererInitialized = true;
+ overlay = std::make_unique();
+
+ if (std::find(jobArguments.begin(), jobArguments.end(), "--hidden") == jobArguments.end()) {
+ font = CreateRef("font/roboto.ttf", 16.0f, 5);
+ auto panelHeight = CaptureRenderer::GetPanelHeight(font, outputLineCount + 1);
+ window.SetSize(job.resolution.x, job.resolution.y + int32_t(panelHeight));
+ ShowWindow(std::find(jobArguments.begin(), jobArguments.end(), "--foreground") != jobArguments.end());
+ }
+
+ report.Print("Serving commands from " + server->directory.string());
+ SetIdle();
+ return;
+ }
+ if (!pipelineFile.empty()) {
+ mode = Mode::Pipeline;
+ pipeline = Pipeline::Load(ResolveUserPath(pipelineFile), from, force);
+ report.Print("Pipeline '" + pipeline->name + "' with " + std::to_string(pipeline->steps.size()) + " steps, snapshots in " +
+ pipeline->snapshotDirectory.string());
+ pipeline->Prepare([&](const std::string& message) { report.Print(message); });
+ StartPipelineStep();
+ return;
+ }
+ job = ParseCommandLine(args);
+ }
+ catch (const std::exception& e) {
+ std::string message = e.what();
+ std::printf("%s\n", message.c_str());
+ phase = Phase::Done;
+ Exit(message.starts_with("Usage:") ? 0 : 2);
+ return;
+ }
+
+ StartJob(job);
+
+ }
+
+ Job App::ParseJobFile(const fs::path& path, const std::vector& extraArguments) const {
+
+ // Options before the job file are kept, the job file can't override them
+ std::vector jobArgs = { args.front() };
+ jobArgs.insert(jobArgs.end(), jobArguments.begin(), jobArguments.end());
+ jobArgs.insert(jobArgs.end(), extraArguments.begin(), extraArguments.end());
+ jobArgs.push_back(path.string());
+ return ParseCommandLine(jobArgs);
+
+ }
+
+ void App::ResetJobState() {
+
+ fatal = false;
+ activeCamera.reset();
+ captureRequests.clear();
+ pendingReadbacks.clear();
+ sheets.clear();
+ sheetOrder.clear();
+ jobSheetImages.clear();
+ jobSheetLabels.clear();
+ shotState = {};
+ stillState = {};
+ baseSettings = json();
+ editFrames = 0;
+ RevertUnsavedEdits(editState);
+ editState = EditState();
+ UpdatePipelinesOfMaterials(ReloadMaterials(settingsMaterials));
+ settingsMaterials.clear();
+ variantCaptures.clear();
+ stripCameras.clear();
+
+ player.Reset(job);
+ nextCheckTime = 0.0f;
+ nextTrackTime = 0.0f;
+
+ queryResults = json::array();
+ checkRunner.reset();
+ tracker.reset();
+
+ report.Reset(job);
+
+ frameCount = 0;
+ readyFrame = -1;
+ rtWaitFrames = 0;
+ loadSeconds = 0.0f;
+ phaseBeforeFinish = Phase::Prepare;
+
+ }
+
+ void App::StartJob(const Job& nextJob) {
+
+ job = nextJob;
+ ResetJobState();
+ startTime = std::chrono::steady_clock::now();
+
+ if (auto error = report.Begin(); !error.empty()) {
+ report.Error(error);
+ report.Print("Status: error (" + error + ")");
+ report.exitCode = 2;
+ report.data = { { "job", job.name }, { "status", "error" }, { "exitCode", 2 }, { "reason", error } };
+ FinishJob();
+ return;
+ }
+
+ if (job.showWindow) {
+ if (!font)
+ font = CreateRef("font/roboto.ttf", 16.0f, 5);
+
+ // The frame keeps its aspect ratio above the output panel, large captures are shown smaller
+ auto panelHeight = CaptureRenderer::GetPanelHeight(font, outputLineCount + 1);
+ auto scale = std::min({ 1.0f, 1600.0f / float(job.resolution.x), 900.0f / float(job.resolution.y) });
+ window.SetSize(int32_t(float(job.resolution.x) * scale), int32_t(float(job.resolution.y) * scale + panelHeight));
+ ShowWindow(job.foreground);
+ }
+ else if (mode != Mode::Job) {
+ window.Hide();
+ }
+
+ // The profilers are disabled by default in release builds, hitches need the CPU profile. The GPU queries write the
+ // checkpoints of the crash diagnostics
+ CPUProfiler::enable = job.profileFrames > 0 || job.hitches.has_value();
+ GPUProfiler::enable = job.profileFrames > 0 || (job.hitches && job.hitches->gpu) ||
+ Graphics::GraphicsDevice::DefaultDevice->support.diagnosticCheckpoints;
+ outputFrame = false;
+ if (job.hitches) {
+ auto hitchSettings = HitchRecorder::GetSettings();
+ hitchSettings.cpu.minimumTime = job.hitches->minimumFrameTime;
+ hitchSettings.cpu.relativeThreshold = job.hitches->relativeThreshold;
+ hitchSettings.gpu.enable = job.hitches->gpu;
+ HitchRecorder::SetSettings(hitchSettings);
+ }
+
+ if (job.sound)
+ Audio::AudioManager::Unmute();
+ else
+ Audio::AudioManager::Mute();
+
+ report.Print("Job '" + job.name + "' with scene " + job.scene + " (run " + report.runId + ")" +
+ (report.previousSeconds > 0.0f ? ", the previous run took " + FormatFloat(report.previousSeconds, 0) + " s" : ""));
+ SetBusyActivity();
+ if (server)
+ server->WriteStatus("running", job.scene, job.name);
+
+ if (job.validation && !report.EnableValidation()) {
+ Fail("Validation layers aren't available, they are part of the Vulkan SDK");
+ return;
+ }
+ report.Print("Output directory: " + job.outputDirectory.string());
+
+ // A direct run was checked before the engine started, servers and pipelines check their jobs here without the preflight
+ if (mode != Mode::Job) {
+ for (const auto& issue : CheckJob(job, false)) {
+ if (issue.starts_with("ERROR")) {
+ Fail(issue.substr(7));
+ return;
+ }
+ report.Print(issue);
+ }
+ }
+
+ if (!rendererInitialized) {
+ captureRenderer.Init(mainRenderer, job.resolution);
+ defaultRenderScale = captureRenderer.GetRenderScale();
+ rendererInitialized = true;
+ }
+ else if (captureRenderer.resolution != job.resolution) {
+ // Resources of the previous resolution may still be in use by frames in flight
+ graphicsDevice->WaitForIdle();
+ captureRenderer.Resize(job.resolution);
+ }
+ captureRenderer.SetRenderScale(job.renderScale.value_or(defaultRenderScale));
+ baseRenderScale = captureRenderer.GetRenderScale();
+ overlay = std::make_unique();
+
+ // The mouse over a shown window must not turn the players of a running job
+ playerInput.useMouse = false;
+
+ checkRunner = std::make_unique(job.checks);
+ if (job.track)
+ tracker = std::make_unique(*job.track);
+
+ // Load with the camera of the first shot such that streaming and probes start in the right area. Entities an
+ // edit adds don't exist yet, such shots are framed once the edit is done
+ if (!job.shots.empty() && !(job.edit && job.shots.front().camera.mode == "focus"))
+ activeCamera = job.shots.front().camera;
+ else if (job.edit && !job.shots.empty())
+ activeCamera = CameraSpec { .mode = "overview" };
+ else
+ activeCamera = job.observer.value_or(CameraSpec {});
+
+ // Capture errors that happen while loading
+ report.SkipLog();
+
+ if (scene && scenePath == job.scene && !sceneDirty) {
+ // The scene starts each job with the settings it was loaded with, out of play mode
+ ApplySettings(*scene, sceneSettings, settingsMaterials);
+ scene->physicsWorld->pauseSimulation = true;
+ scene->paused = false;
+ captureRenderer.InvalidateHistory();
+ report.Print("Using the loaded scene");
+ phase = Phase::Prepare;
+ return;
+ }
+ if (scene && mode == Mode::Server) {
+ // A played or edited scene is loaded again, its meshes with their materials and textures stay loaded
+ if (scenePath == job.scene) {
+ retainedMeshes = scene->GetMeshes();
+ report.Print("Loading the scene again, the last job played or edited it");
+ }
+ UnloadScene();
+ }
+ else if (scene) {
+ Fail("The job uses " + job.scene + ", but " + scenePath + " is loaded, unload it first");
+ return;
+ }
+
+ keepScene = false;
+ LoadScene(job.scene);
+
+ }
+
+ void App::LoadScene(const std::string& path) {
+
+ scenePath = path;
+ if (!job.waitGpu) {
+ SetBusyActivity();
+ BeginLoading();
+ return;
+ }
+
+ // Scenes of other engine applications fill the GPU memory, a second one on top of them runs out of it
+ phase = Phase::WaitingForGpu;
+ gpuWaitStart = std::chrono::steady_clock::now();
+ nextGpuCheck = gpuWaitStart;
+ nextGpuWaitPrint = gpuWaitStart;
+ gpuWaitReason.clear();
+ InstanceRegistry::QueueForGpu("waiting for the GPU to load " + path);
+ if (server)
+ server->WriteStatus("waiting for the GPU", path, job.name);
+
+ }
+
+ void App::UpdateGpuWait() {
+
+ auto now = std::chrono::steady_clock::now();
+ if (now < nextGpuCheck)
+ return;
+ nextGpuCheck = now + std::chrono::milliseconds(500);
+
+ std::vector ahead;
+ auto seconds = SecondsSince(gpuWaitStart);
+ if (InstanceRegistry::PollGpu(ahead)) {
+ // The wait doesn't count into the duration of the job, the next run expects its end from that
+ startTime += now - gpuWaitStart;
+ report.data["gpuWaitSeconds"] = Round(seconds, 1);
+ if (!gpuWaitReason.empty())
+ report.Print("The GPU is free after " + FormatFloat(seconds, 0) + " s, loading " + scenePath);
+ if (server)
+ server->WriteStatus(loadingForCommand ? "loading" : "running", scenePath, loadingForCommand ? "" : job.name);
+ SetBusyActivity();
+ BeginLoading();
+ return;
+ }
+
+ if (seconds > job.gpuWaitTimeout) {
+ Fail("The GPU is still busy after " + FormatFloat(seconds, 0) + " s (gpuWaitTimeout), waiting for " + gpuWaitReason);
+ return;
+ }
+
+ // Nobody ahead: this process claimed the GPU and gets it in the next step
+ if (ahead.empty())
+ return;
+
+ auto reason = InstanceRegistry::Describe(ahead);
+ if (reason != gpuWaitReason || now >= nextGpuWaitPrint) {
+ report.Print("Waiting for the GPU before loading " + scenePath + " (" + FormatFloat(seconds, 0) + " s): " + reason);
+ nextGpuWaitPrint = now + std::chrono::seconds(60);
+ }
+ gpuWaitReason = reason;
+
+ }
+
+ void App::BeginLoading() {
+
+ loadStartTime = std::chrono::steady_clock::now();
+ frameCount = 0;
+ rtWaitFrames = 0;
+ phase = Phase::Loading;
+ const auto& path = scenePath;
+
+ try {
+ auto binary = fs::path(path).extension() != ".json";
+ scene = Serializer::DeserializeScene(path, binary);
+ }
+ catch (const std::exception& e) {
+ scene.reset();
+ Fail("Couldn't load scene " + path + ": " + e.what());
+ return;
+ }
+
+ if (!scene) {
+ Fail("Couldn't load scene " + path);
+ return;
+ }
+
+ CreateCaptureCamera();
+
+ }
+
+ void App::UnloadScene() {
+
+ if (!scene)
+ return;
+
+ graphicsDevice->WaitForIdle();
+ // The Lua environment of the player references the script state of the scene
+ player.Stop();
+ scene.reset();
+ scenePath.clear();
+ sceneSettings = json();
+ captureCameraEntity = Scene::Entity();
+ keepScene = false;
+ sceneDirty = false;
+
+ }
+
+ void App::UnloadContent() {
+
+ if (phase != Phase::Done && phase != Phase::Idle) {
+ // A lost device ends the main loop like a closed window, e.g. when the scene exceeds the GPU memory
+ Fail(graphicsDevice->isDeviceLost ? "The GPU device was lost before the job finished (out of GPU memory?)" :
+ "The window was closed before the job finished");
+ Finish();
+ }
+ report.End();
+
+ graphicsDevice->WaitForIdle();
+ report.DestroyValidation();
+ player.Stop();
+ scene.reset();
+ InstanceRegistry::Unregister();
+
+ }
+
+ void App::Update(float deltaTime) {
+
+ if (phase == Phase::Done)
+ return;
+
+ if (outputFrame) {
+ // The profiler dropped the frame which wrote the images, its frame time arrives now
+ outputFrame = false;
+ CPUProfiler::enable = true;
+ }
+ else {
+ report.BeginFrame(job.profileFrames);
+ }
+ {
+ CPUProfiler::Scope profilerScope("Wait for previous frame");
+ graphicsDevice->WaitForPreviousFrameSubmission();
+ }
+
+ auto waiting = phase == Phase::Idle || phase == Phase::WaitingForGpu;
+ if (vsync != waiting) {
+ vsync = waiting;
+ graphicsDevice->CreateSwapChain(vsync ? VK_PRESENT_MODE_FIFO_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR,
+ graphicsDevice->swapChain->colorSpace);
+ // A new swap chain and its first presents can bring the window to the front
+ if (job.showWindow && !job.foreground && !window.IsFocused())
+ backgroundUntil = Clock::Get() + 3.0f;
+ }
+
+ if (backgroundUntil > Clock::Get()) {
+ if (window.IsFocused())
+ backgroundUntil = 0.0f;
+ else
+ MoveWindowToBack(window.GetSDLWindow());
+ }
+
+ try {
+ // Writing the images takes much longer than a frame
+ if (job.profileFrames > 0 && !pendingReadbacks.empty()) {
+ CPUProfiler::enable = false;
+ outputFrame = true;
+ }
+
+ CPUProfiler::Scope sectionScope("Readback");
+ ProcessReadback();
+ sectionScope.Next("Collect log");
+ CollectLog();
+
+ frameCount++;
+
+ if (server && phase != Phase::Idle && phase != Phase::Done && phase != Phase::Finish && server->IsCancelled())
+ Fail("Cancelled by the client");
+
+ switch (phase) {
+ case Phase::Idle:
+ sectionScope.Next("Commands");
+ ProcessNextCommand();
+ break;
+ case Phase::WaitingForGpu:
+ sectionScope.Next("Wait for the GPU");
+ UpdateGpuWait();
+ // Leaves the GPU to the others, also without vsync in a hidden window
+ std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ break;
+ case Phase::Loading: {
+ sectionScope.Next("Loading");
+ UpdateSceneWithCaptureCamera(*activeCamera);
+ auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - loadStartTime).count();
+ if (IsSceneReady()) {
+ for (const auto& mesh : scene->GetMeshes())
+ if (mesh.IsValid() && !mesh.IsLoaded())
+ report.Warn("Mesh " + mesh.GetResource()->path + " failed to load");
+
+ loadSeconds = elapsed;
+ sceneSettings = ExportSettings(*scene);
+ report.Print("Scene ready after " + FormatFloat(loadSeconds, 1) + "s (" + std::to_string(frameCount) +
+ " frames, " + std::to_string(scene->GetEntityCount() - 1) + " entities)");
+ retainedMeshes.clear();
+ if (loadingForCommand) {
+ loadingForCommand = false;
+ SetIdle();
+ CompleteCommand({ { "status", "ok" }, { "loadSeconds", loadSeconds },
+ { "entities", scene->GetEntityCount() - 1 }, { "warnings", report.warnings } });
+ }
+ else {
+ phase = Phase::Prepare;
+ }
+ }
+ else if (elapsed > job.loadTimeout) {
+ Fail("Scene didn't finish loading within " + FormatFloat(job.loadTimeout, 0) + "s");
+ }
+ break;
+ }
+ case Phase::Prepare:
+ sectionScope.Next("Prepare");
+ Prepare();
+ break;
+ case Phase::EditSave:
+ sectionScope.Next("Edit save");
+ FinishEdit();
+ break;
+ case Phase::Shots:
+ sectionScope.Next("Shots");
+ UpdateShots();
+ break;
+ case Phase::Play:
+ sectionScope.Next("Play");
+ UpdatePlay();
+ break;
+ case Phase::Finish:
+ sectionScope.Next("Finish");
+ // The scene isn't updated anymore, captures of a frame which wasn't rendered (e.g. an event threw) never will be
+ captureRequests.clear();
+ if (!HasPendingCaptures())
+ Finish();
+ break;
+ default:
+ break;
+ }
+ }
+ catch (const std::exception& e) {
+ Fail(e.what());
+ }
+
+ }
+
+ void App::Render(float deltaTime) {
+
+ // Only a scene updated in this frame is rendered, e.g. not while finishing, waiting for commands or in the frame a
+ // job starts on a loaded scene. The renderer would use the per frame data of an older update, like an
+ // acceleration structure that was never built because its frame wasn't rendered
+ auto updated = sceneUpdated;
+ sceneUpdated = false;
+ if (!scene || !updated) {
+ // Scene updates can enqueue GPU work even when no scene frame is rendered
+ if (scene)
+ scene->WaitForAsyncWorkCompletion();
+ PresentWindow();
+ return;
+ }
+
+ std::vector passes;
+ for (const auto& request : captureRequests)
+ for (const auto& pass : request.passes)
+ if (std::find(passes.begin(), passes.end(), pass) == passes.end())
+ passes.push_back(pass);
+
+ try {
+ CPUProfiler::Scope profilerScope("Capture render");
+ BuildOverlay();
+ // Loading frames aren't captured, path tracing them stalled the GPU for more than 30 s
+ captureRenderer.Render(scene, passes, overlay->GetBatches(), job.pathTrace && phase != Phase::Loading);
+ }
+ catch (const std::exception& e) {
+ // E.g. validation errors, which the engine throws in non-release builds
+ Fail(std::string("Rendering failed: ") + e.what());
+ captureRequests.clear();
+ PresentWindow();
+ return;
+ }
+
+ pendingReadbacks = std::move(captureRequests);
+ captureRequests.clear();
+
+ PresentWindow();
+
+ }
+
+ void App::PresentWindow() {
+
+ if (!job.showWindow || !font) {
+ captureRenderer.Present();
+ return;
+ }
+
+ std::vector lines = { { GetStatusLine(), vec4(0.55f, 0.8f, 1.0f, 1.0f) } };
+ const auto& outputLines = report.outputLines;
+ auto first = outputLines.size() > outputLineCount ? outputLines.size() - outputLineCount : 0;
+ lines.insert(lines.end(), outputLines.begin() + first, outputLines.end());
+
+ captureRenderer.Present(font, lines);
+
+ }
+
+ std::string App::GetStatusLine() const {
+
+ if (phase == Phase::Idle)
+ return "waiting for commands | " + (scene ? scenePath + " loaded" : std::string("no scene loaded"));
+
+ std::string line = job.name + " | ";
+ switch (phase) {
+ case Phase::Idle:
+ break;
+ case Phase::WaitingForGpu:
+ line += "waiting for the GPU" + (gpuWaitReason.empty() ? std::string() : ": " + gpuWaitReason);
+ break;
+ case Phase::Loading:
+ line += "loading " + job.scene;
+ break;
+ case Phase::Prepare:
+ case Phase::EditSave:
+ line += "preparing";
+ break;
+ case Phase::Shots:
+ line += "shots";
+ break;
+ case Phase::Play:
+ line += "playing " + FormatFloat(player.timeline.time, 2) + " / " + FormatFloat(job.duration, 2) + " s";
+ if (scene && scene->paused)
+ line += " (paused)";
+ break;
+ case Phase::Finish:
+ line += "writing outputs";
+ break;
+ case Phase::Done:
+ line += report.exitCode == 0 ? "passed" : report.exitCode == 1 ? "failed" : "error";
+ break;
+ }
+
+ return line + " | frame " + std::to_string(frameCount);
+
+ }
+
+ void App::Fail(const std::string& message) {
+
+ report.Error(message);
+ fatal = true;
+
+ // A scene loaded by a command has no job and no report
+ if (loadingForCommand) {
+ loadingForCommand = false;
+ retainedMeshes.clear();
+ UnloadScene();
+ SetIdle();
+ CompleteCommand({ { "status", "error" }, { "reason", message } });
+ return;
+ }
+
+ if (phase != Phase::Done && phase != Phase::Finish) {
+ phaseBeforeFinish = phase;
+ phase = Phase::Finish;
+ }
+
+ }
+
+ void App::RunJobLua(const LuaEvent& lua, const std::string& name) {
+
+ // Pixel picking uses the same camera setup as shots
+ EditHooks hooks;
+ hooks.pickRay = [this](const json& cameraJson, vec2 pixel) {
+ // The scene update computes the camera matrices, the simulation is paused at this point
+ UpdateSceneWithCaptureCamera(ParseCamera(cameraJson));
+ const auto& camera = captureCameraEntity.GetComponent();
+ return Volume::Ray(captureRenderer.GetViewport(), camera, pixel + vec2(0.5f));
+ };
+
+ auto start = std::chrono::steady_clock::now();
+ LuaJob luaJob;
+ luaJob.Start(scene->GetLuaState(), scene.get(), report, [start]() { return SecondsSince(start); }, hooks, &editState);
+ // Stopped also when the Lua fails
+ std::unique_ptr stop(&luaJob, [](LuaJob* job) { job->Stop(); });
+ luaJob.Run(lua.code, lua.file.empty() ? name : lua.file);
+
+ }
+
+ void App::CollectLog() {
+
+ for (const auto& entry : report.CollectLog()) {
+ player.timeline.MatchLog(entry.message);
+ if (entry.type != Log::TYPE_ERROR || !checkRunner || !job.checks.logErrors || MatchAnyPattern(job.checks.logIgnore, entry.message))
+ continue;
+
+ checkRunner->AddFailure({ "log", entry.message.substr(0, 160), player.timeline.time, entry.message });
+ // Nothing after the first error is worth the wait, e.g. a script that would have logged the condition of an event
+ if (job.checks.failFast && phase != Phase::Finish && phase != Phase::Done && phase != Phase::Idle) {
+ report.Print("Stopping at the first error, checks.failFast = false runs to the end");
+ phaseBeforeFinish = phase;
+ phase = Phase::Finish;
+ }
+ }
+
+ }
+
+ bool App::IsSceneReady() {
+
+ // A few frames are needed to kick off the asynchronous work
+ if (frameCount < 3)
+ return false;
+
+ // Meshes that failed to load count as loaded, they're reported once the scene is ready
+ if (!scene->IsFullyLoaded())
+ return false;
+
+ // Ray tracing structures are built asynchronously, but not every device/scene builds them
+ if (scene->IsRtDataNeeded() && !scene->IsRtDataValid() && rtWaitFrames++ < 300)
+ return false;
+
+ return true;
+
+ }
+
+ void App::Prepare() {
+
+ // The settings come first, the scene update extracts what the next frame renders
+ if (!job.settings.empty())
+ ApplySettings(*scene, job.settings, settingsMaterials);
+ baseSettings = ExportSettings(*scene);
+ if (job.settings.contains("materials"))
+ baseSettings["materials"] = job.settings["materials"];
+
+ // The renderer expects a scene update in every frame
+ UpdateSceneWithCaptureCamera(*activeCamera);
+ report.Print("Rendering at " + std::to_string(job.resolution.x) + "x" + std::to_string(job.resolution.y) + GetRenderDescription());
+
+ EntitySet excluded = { captureCameraEntity };
+
+ if (job.inspect) {
+ auto inspection = InspectScene(*scene, job.inspect->filter, job.inspect->detail, excluded);
+ report.WriteJson(job.inspect->file, inspection);
+ report.Print("Inspection: " + std::to_string(inspection["entities"].size()) + " entities written to " + job.inspect->file);
+ }
+
+ if (!job.queries.empty()) {
+ auto results = RunQueries(*scene, job.queries, job.outputDirectory);
+ report.WriteJson("queries.json", results);
+ queryResults = results;
+ for (const auto& result : results) {
+ auto text = result.contains("error") ? "error: " + result["error"].get() : result["result"].dump();
+ if (text.size() > 400)
+ text = text.substr(0, 400) + "... (see queries.json)";
+ report.Print("Query " + result["query"].dump() + " -> " + text);
+ }
+ }
+
+ if (job.lua && !job.edit)
+ RunJobLua(*job.lua, "lua");
+
+ if (job.edit) {
+ auto inspectStart = std::chrono::steady_clock::now();
+ editBefore = CaptureSceneState(*scene, excluded);
+ report.data["edit"]["seconds"]["inspectBefore"] = SecondsSince(inspectStart);
+ editState.loadedTerrain = scene->terrain.IsValid() ? scene->terrain.GetResource()->path : "";
+ editState.dryRun = job.edit->dryRun;
+ editState.textureFormat = job.edit->textureFormat == "ktx2" ? Loader::ImportTextureFormat::KTX2 :
+ Loader::ImportTextureFormat::Original;
+ // After the snapshot, changes of the Lua are part of the edit
+ if (job.lua)
+ RunJobLua(*job.lua, "lua");
+ scene->WaitForAsyncWorkCompletion();
+ auto operationsStart = std::chrono::steady_clock::now();
+ report.data["edit"]["operations"] = ApplyEditOperations(scene, job.edit->operations, editState);
+ report.data["edit"]["seconds"]["operations"] = SecondsSince(operationsStart);
+ report.Print("Applied " + std::to_string(job.edit->operations.size()) + " edit operations in " +
+ FormatFloat(report.data["edit"]["seconds"]["operations"].get(), 1) + "s");
+ // Waiting cleared the render list of this frame's update, rendering it would draw host culled shadow
+ // instances without their meshes
+ sceneUpdated = false;
+ phase = Phase::EditSave;
+ return;
+ }
+
+ // Checks of a static scene run once, while playing they run continuously
+ if (!job.play)
+ checkRunner->Run(*scene, 0.0f);
+
+ // Hitches of loading and editing aren't reported, only those of frames from here on
+ hitchesStartTime = Clock::Get();
+
+ if (!job.shots.empty())
+ phase = Phase::Shots;
+ else if (job.play)
+ StartPlay();
+ else
+ phase = Phase::Finish;
+
+ }
+
+ void App::FinishEdit() {
+
+ // Propagate transforms and bounds before inspection
+ UpdateSceneWithCaptureCamera(*activeCamera);
+ if (++editFrames < 3)
+ return;
+
+ EntitySet excluded = { captureCameraEntity };
+ auto& edit = report.data["edit"];
+
+ auto& seconds = edit["seconds"];
+ // Its changes are part of the diff and saved with the scene
+ if (job.edit->lua) {
+ RunJobLua(*job.edit->lua, "edit.lua");
+ scene->UpdateTransforms();
+ }
+ auto phaseStart = std::chrono::steady_clock::now();
+ auto after = CaptureSceneState(*scene, excluded);
+ seconds["inspectAfter"] = SecondsSince(phaseStart);
+ phaseStart = std::chrono::steady_clock::now();
+ auto diff = DiffSceneStates(editBefore, after);
+ editBefore.clear();
+ for (const auto& list : { "changed", "added", "removed" })
+ diff[list] = CapList(diff[list], 2000);
+ report.WriteJson("edit_diff.json", diff);
+ seconds["diff"] = SecondsSince(phaseStart);
+ edit["diff"] = diff["summary"];
+ report.Print("Edit diff: " + diff["summary"].get() + " (see edit_diff.json)");
+
+ // Queries of the edited scene, e.g. to verify placements
+ if (!job.edit->queries.empty()) {
+ auto results = RunQueries(*scene, job.edit->queries, job.outputDirectory);
+ report.WriteJson("edit_queries.json", results);
+ for (const auto& result : results) {
+ auto text = result.contains("error") ? "error: " + result["error"].get() : result["result"].dump();
+ if (text.size() > 400)
+ text = text.substr(0, 400) + "... (see edit_queries.json)";
+ report.Print("Edit query " + result["query"].value("type", "") + " -> " + text);
+ }
+ }
+ phaseStart = std::chrono::steady_clock::now();
+ checkRunner->Run(*scene, 0.0f);
+ seconds["checks"] = SecondsSince(phaseStart);
+ if (checkRunner->HasFailures()) {
+ edit["saved"] = false;
+ Fail("Checks failed after the edit, neither the scene nor materials were saved");
+ return;
+ }
+
+ if (job.edit->dryRun) {
+ edit["saved"] = false;
+ report.Print("Dry run, neither the scene nor materials are saved");
+ phase = job.shots.empty() ? Phase::Finish : Phase::Shots;
+ return;
+ }
+
+ // Edits which only changed materials leave the scene untouched, no need to rewrite it
+ bool sceneChanged = !diff["changed"].empty() || !diff["added"].empty() || !diff["removed"].empty() || job.edit->saveUnchanged ||
+ editState.terrainChanged;
+
+ auto output = job.edit->output;
+ if (output.empty()) {
+ auto scenePath = fs::path(job.scene);
+ auto fileName = scenePath.stem().string() + ".edit" + scenePath.extension().string();
+ output = (scenePath.parent_path() / fileName).generic_string();
+ }
+
+ // Validate the output first, materials are only written together with the scene
+ auto absoluteOutput = GetAssetDirectory() / output;
+ if (sceneChanged && output == job.scene && !job.edit->overwrite) {
+ Fail("Refusing to overwrite the input scene " + output + ", set edit.overwrite = true or choose another output");
+ return;
+ }
+ if (sceneChanged && fs::exists(absoluteOutput) && output != job.scene && !job.edit->overwrite) {
+ Fail("Output scene " + output + " already exists, set edit.overwrite = true to replace it");
+ return;
+ }
+ // The patches of the settings are for the running scene only, saving would write them into the file
+ for (const auto& path : editState.changedMaterials) {
+ if (settingsMaterials.contains(path)) {
+ Fail("Material " + path + " is patched by the settings and edited, edit it in a job without the patch");
+ return;
+ }
+ }
+
+ if (!editState.graphEdits.changed.empty()) {
+ edit["graphs"] = SaveMaterialGraphs(editState.graphEdits);
+ report.Print("Saved " + std::to_string(edit["graphs"].size()) + " edited material graphs");
+ }
+ if (!editState.changedMaterials.empty()) {
+ edit["materials"] = SaveMaterials(editState.changedMaterials);
+ report.Print("Saved " + std::to_string(editState.changedMaterials.size()) + " edited materials");
+ editState.changedMaterials.clear();
+ }
+
+ if (!sceneChanged) {
+ edit["saved"] = false;
+ report.Print("The scene itself didn't change, it is not saved");
+ phase = job.shots.empty() ? Phase::Finish : Phase::Shots;
+ return;
+ }
+
+ // The snapshots of a pipeline keep the previous states
+ if (fs::exists(absoluteOutput) && mode != Mode::Pipeline) {
+ auto timestamp = std::chrono::system_clock::now().time_since_epoch() / std::chrono::seconds(1);
+ auto backup = absoluteOutput;
+ backup += ".backup-" + std::to_string(timestamp);
+ fs::copy_file(absoluteOutput, backup);
+ edit["backup"] = backup.string();
+ report.Print("Backup of the previous scene: " + backup.string());
+ }
+
+ // The capture camera must not end up in the scene, the editor does the same with its camera
+ auto entityCount = scene->GetEntityCount() - 1;
+ scene->DestroyEntity(captureCameraEntity);
+
+ if (editState.terrainChanged) {
+ SaveSceneTerrain(*scene);
+ edit["terrain"] = scene->terrain.GetResource()->path;
+ report.Print("Saved terrain to data/" + scene->terrain.GetResource()->path);
+ }
+
+ auto binary = fs::path(output).extension() != ".json";
+ phaseStart = std::chrono::steady_clock::now();
+ Serializer::SerializeScene(scene, output, false, binary);
+ seconds["save"] = SecondsSince(phaseStart);
+
+ CreateCaptureCamera();
+
+ // A pipeline step that continues with the scene saves it again, only the last saved state is loaded again
+ if (mode != Mode::Pipeline || !StepReadsScene(pipeline->currentStep + 1, output)) {
+ phaseStart = std::chrono::steady_clock::now();
+ try {
+ auto reloaded = Serializer::DeserializeScene(output, binary);
+ auto reloadedCount = reloaded->GetEntityCount();
+ edit["verified"] = reloadedCount == entityCount;
+ if (reloadedCount != entityCount)
+ Fail("Saved scene has " + std::to_string(reloadedCount) + " entities, expected " + std::to_string(entityCount));
+ seconds["verify"] = SecondsSince(phaseStart);
+ }
+ catch (const std::exception& e) {
+ Fail("Saved scene " + output + " couldn't be loaded again: " + e.what());
+ return;
+ }
+ }
+
+ edit["saved"] = true;
+ edit["output"] = output;
+ report.Print("Saved edited scene to data/" + output);
+
+ // A scene that stays loaded starts the next job with the settings it was saved with
+ sceneSettings = ExportSettings(*scene);
+
+ if (phase == Phase::Finish)
+ return;
+
+ phase = job.shots.empty() ? Phase::Finish : Phase::Shots;
+
+ }
+
+ void App::UpdateShots() {
+
+ auto variantCount = std::max(job.variants.size(), size_t(1));
+ const auto& shot = job.shots[shotState.shot];
+ auto views = shot.views.empty() ? std::vector { "" } : shot.views;
+ const auto& view = views[shotState.view];
+
+ bool firstFrameOfShot = shotState.settledFrames == 0 && !shotState.requested;
+ if (firstFrameOfShot && !job.variants.empty() && shotState.shot == 0 && shotState.view == 0) {
+ const auto& variant = job.variants[shotState.variant];
+ ApplyBaseSettings();
+ ApplySettings(*scene, variant.settings, settingsMaterials);
+ captureRenderer.SetRenderScale(variant.renderScale.value_or(baseRenderScale));
+ report.Print("Variant '" + variant.name + "'" + GetRenderDescription());
+ }
+
+ auto camera = shot.camera;
+ if (!view.empty()) {
+ camera.view = view;
+ camera.azimuth.reset();
+ camera.elevation.reset();
+ if (camera.mode == "scene" || camera.mode == "manual")
+ throw std::runtime_error("Shot '" + shot.name + "' has views, which require a focus or overview camera");
+ }
+ activeCamera = camera;
+
+ UpdateSceneWithCaptureCamera(camera);
+
+ auto settleFrames = shot.settleFrames >= 0 ? shot.settleFrames : job.settleFrames;
+ if (!shotState.requested) {
+ if (shotState.settledFrames++ < settleFrames)
+ return;
+
+ auto variantName = job.variants.empty() ? std::string() : job.variants[shotState.variant].name;
+ auto prefix = job.variants.empty() ? std::string() : SanitizeFileName(variantName) + "/";
+ auto baseName = SanitizeFileName(shot.name) + (view.empty() ? "" : "_" + view);
+
+ CaptureRequest request;
+ request.path = job.outputDirectory / (prefix + baseName + ".png");
+ request.passes = shot.passes;
+ request.label = view.empty() ? shot.name : view;
+ request.crop = GetCropRectangle(shot.crop);
+
+ if (views.size() > 1) {
+ request.group = prefix + SanitizeFileName(shot.name) + "_views";
+ if (!sheets.contains(request.group)) {
+ auto title = shot.name + (job.variants.empty() ? "" : " (" + variantName + ")");
+ sheets[request.group] = { .title = title, .path = job.outputDirectory / (request.group + ".png") };
+ sheetOrder.push_back(request.group);
+ }
+ }
+
+ RequestCapture(request);
+
+ // Variants of the same shot/view are compared in an additional sheet
+ if (!job.variants.empty()) {
+ auto group = baseName + "_variants";
+ if (!sheets.contains(group)) {
+ sheets[group] = { .title = baseName + " variants", .path = job.outputDirectory / (group + ".png") };
+ sheetOrder.push_back(group);
+ }
+ variantCaptures[request.path.string()] = { group, variantName };
+ }
+
+ shotState.requested = true;
+ return;
+ }
+
+ if (HasPendingCaptures())
+ return;
+
+ shotState.requested = false;
+ shotState.settledFrames = 0;
+
+ if (++shotState.view < views.size())
+ return;
+ shotState.view = 0;
+
+ if (++shotState.shot < job.shots.size())
+ return;
+ shotState.shot = 0;
+
+ if (++shotState.variant < variantCount)
+ return;
+
+ if (job.play) {
+ if (!job.variants.empty())
+ ApplyBaseSettings();
+ StartPlay();
+ }
+ else {
+ phase = Phase::Finish;
+ }
+
+ }
+
+ void App::ApplyBaseSettings() {
+
+ // Material patches aren't part of the exported settings, the files restore them
+ UpdatePipelinesOfMaterials(ReloadMaterials(settingsMaterials));
+ settingsMaterials.clear();
+ ApplySettings(*scene, baseSettings, settingsMaterials);
+ captureRenderer.SetRenderScale(baseRenderScale);
+
+ }
+
+ void App::StartPlay() {
+
+ // The scripts get new entities, the asynchronous work of the last scene update (e.g. the ray tracing world)
+ // still reads the entity storage. Waiting clears the render list of the update, so its frame isn't rendered
+ scene->WaitForAsyncWorkCompletion();
+ sceneUpdated = false;
+
+ playStartTime = std::chrono::steady_clock::now();
+ auto events = job.timeline;
+
+ // Strips are expanded into capture events
+ for (const auto& strip : job.strips) {
+ auto group = SanitizeFileName(strip.name);
+ sheets[group] = { .title = strip.name, .columns = strip.columns, .path = job.outputDirectory / (group + ".png") };
+ sheetOrder.push_back(group);
+
+ if (strip.hasCamera)
+ stripCameras[group] = strip.camera;
+
+ // Integer steps avoid accumulating floating point errors
+ auto count = int32_t(std::floor((strip.to - strip.from) / strip.every + 1e-3f));
+ for (int32_t i = 0; i <= count; i++) {
+ auto time = strip.from + float(i) * strip.every;
+
+ CaptureEvent capture;
+ capture.file = group + "/" + FormatFloat(time, 2) + "s.png";
+ capture.group = group;
+ capture.stripCamera = strip.hasCamera;
+ events.push_back({ .time = time, .type = "capture", .action = capture });
+ }
+ }
+
+ activeCamera = job.observer.value_or(CameraSpec {});
+
+ // Focus cameras are framed once, re-framing a moving object every frame makes the camera jump
+ if ((activeCamera->mode == "focus" || activeCamera->mode == "overview") && !activeCamera->dynamic) {
+ ApplyCameraSpec(*activeCamera);
+ const auto& camera = captureCameraEntity.GetComponent]