├── .github └── workflows │ └── cla.yml ├── .gitignore ├── .gitmodules ├── CLA.txt ├── CMakeLists.txt ├── LICENSE.txt ├── README.md ├── examples ├── aftermath │ ├── CMakeLists.txt │ ├── aftermath.cpp │ ├── shaders.cfg │ └── shaders.hlsl ├── basic_triangle │ ├── CMakeLists.txt │ ├── basic_triangle.cpp │ ├── shaders.cfg │ └── shaders.hlsl ├── bindless_rendering │ ├── CMakeLists.txt │ ├── bindless_rendering.cpp │ ├── bindless_rendering.hlsl │ └── shaders.cfg ├── deferred_shading │ ├── CMakeLists.txt │ ├── CubeGeometry.h │ └── deferred_shading.cpp ├── headless │ ├── CMakeLists.txt │ ├── headless.cpp │ ├── shaders.cfg │ └── shaders.hlsl ├── meshlets │ ├── CMakeLists.txt │ ├── meshlets.cpp │ ├── shaders.cfg │ └── shaders.hlsl ├── rt_bindless │ ├── CMakeLists.txt │ ├── lighting_cb.h │ ├── rt_bindless.cpp │ ├── rt_bindless.hlsl │ └── shaders.cfg ├── rt_particles │ ├── CMakeLists.txt │ ├── geometry.hlsli │ ├── mlab.hlsli │ ├── rt_particles.cpp │ ├── rt_particles.hlsl │ ├── rt_particles_cb.h │ ├── shaders.cfg │ └── utils.hlsli ├── rt_reflections │ ├── CMakeLists.txt │ ├── lighting_cb.h │ ├── rt_reflections.cpp │ ├── rt_reflections.hlsl │ └── shaders.cfg ├── rt_shadows │ ├── CMakeLists.txt │ ├── lighting_cb.h │ ├── rt_shadows.cpp │ ├── rt_shadows.hlsl │ └── shaders.cfg ├── rt_triangle │ ├── CMakeLists.txt │ ├── rt_triangle.cpp │ ├── rt_triangle.hlsl │ └── shaders.cfg ├── shader_specializations │ ├── CMakeLists.txt │ ├── shader_specializations.cpp │ ├── shaders.cfg │ └── shaders.hlsl ├── threaded_rendering │ ├── CMakeLists.txt │ └── threaded_rendering.cpp ├── variable_shading │ ├── CMakeLists.txt │ ├── lighting_cb.h │ ├── shaders.cfg │ ├── shaders.hlsl │ └── variable_shading.cpp ├── vertex_buffer │ ├── CMakeLists.txt │ ├── shaders.cfg │ ├── shaders.hlsl │ └── vertex_buffer.cpp └── work_graphs │ ├── AgilitySDK │ ├── d3d12_1.613.0.zip │ └── include │ │ ├── d3d12.h │ │ ├── d3d12compatibility.h │ │ ├── d3d12sdklayers.h │ │ ├── d3d12shader.h │ │ ├── d3d12video.h │ │ ├── d3dcommon.h │ │ ├── d3dx12 │ │ ├── d3dx12.h │ │ ├── d3dx12_barriers.h │ │ ├── d3dx12_check_feature_support.h │ │ ├── d3dx12_core.h │ │ ├── d3dx12_default.h │ │ ├── d3dx12_pipeline_state_stream.h │ │ ├── d3dx12_property_format_table.h │ │ ├── d3dx12_render_pass.h │ │ ├── d3dx12_resource_helpers.h │ │ ├── d3dx12_root_signature.h │ │ └── d3dx12_state_object.h │ │ └── dxgiformat.h │ ├── CMakeLists.txt │ ├── README.md │ ├── animation.hlsl │ ├── deferred_shading.hlsl │ ├── gbuffer_fill.hlsl │ ├── light_culling.hlsl │ ├── lighting.hlsli │ ├── materials.hlsli │ ├── scene.cpp │ ├── scene.h │ ├── scene_data.hlsli │ ├── shaders.cfg │ ├── ver_test.hlsl │ ├── work_graph_broadcasting.hlsl │ ├── work_graphs_d3d12.cpp │ └── work_graphs_d3d12.jpg ├── feature_demo ├── CMakeLists.txt └── FeatureDemo.cpp └── media ├── fonts ├── DroidSans │ ├── Apache License.txt │ └── DroidSans-Mono.ttf └── OpenSans │ ├── Apache License.txt │ └── OpenSans-Regular.ttf ├── nvidia-logo.png ├── rt_particles ├── ParticleScene.bin ├── ParticleScene.gltf ├── environment-map.dds └── smoke-particle.png └── sponza-plus.scene.json /.github/workflows/cla.yml: -------------------------------------------------------------------------------- 1 | name: "CLA Assistant" 2 | on: 3 | issue_comment: 4 | types: [created] 5 | pull_request_target: 6 | types: [opened,closed,synchronize] 7 | 8 | jobs: 9 | CLAssistant: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: "CLA Assistant" 13 | if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target' 14 | uses: contributor-assistant/github-action@ba066dbae3769e2ce93ec8cfc4fdc51b9db628ba 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | PERSONAL_ACCESS_TOKEN : ${{ secrets.CLA_ACCESS_TOKEN }} 18 | with: 19 | path-to-signatures: 'signatures/donut_examples.json' 20 | path-to-document: 'https://github.com/NVIDIA-RTX/Donut-Samples/blob/main/CLA.txt' 21 | branch: 'donut_examples' 22 | allowlist: nobody 23 | lock-pullrequest-aftermerge: true 24 | remote-organization-name: NVIDIA-RTX 25 | remote-repository-name: CLAs 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.vs 2 | /.vscode 3 | /aftermath/ 4 | /bin/ 5 | /build*/ 6 | /donut-* 7 | /nvapi/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "donut"] 2 | path = donut 3 | url = ../Donut.git 4 | [submodule "media/glTF-Sample-Assets"] 5 | path = media/glTF-Sample-Assets 6 | url = https://github.com/KhronosGroup/glTF-Sample-Assets.git 7 | -------------------------------------------------------------------------------- /CLA.txt: -------------------------------------------------------------------------------- 1 | Contribution License Agreement 2 | 3 | This Contribution License Agreement ("Agreement") is agreed to by the party 4 | signing below ("You"), and conveys certain license rights to NVIDIA Corporation 5 | and its affiliates ("NVIDIA") for Your contributions to NVIDIA open source 6 | projects. This Agreement is effective as of the latest signature date below. 7 | 8 | 1. Definitions. 9 | 10 | "Code" means the computer software code, whether in human-readable or 11 | machine-executable form, that is delivered by You to NVIDIA under this 12 | Agreement. 13 | 14 | "Project" means any of the projects owned or managed by NVIDIA in which 15 | software is offered under a license approved by the Open Source Initiative 16 | (OSI) (www.opensource.org) and documentation offered under an OSI or a 17 | Creative Commons license (https://creativecommons.org/licenses). 18 | 19 | "Submit" is the act of uploading, submitting, transmitting, or distributing 20 | code or other content to any Project, including but not limited to 21 | communication on electronic mailing lists, source code control systems, 22 | and issue tracking systems that are managed by, or on behalf of, the 23 | Project for the purpose of discussing and improving that Project, but 24 | excluding communication that is conspicuously marked or otherwise 25 | designated in writing by You as "Not a Submission." 26 | 27 | "Submission" means the Code and any other copyrightable material Submitted 28 | by You, including any associated comments and documentation. 29 | 30 | 2. Your Submission. You must agree to the terms of this Agreement before 31 | making a Submission to any Project. This Agreement covers any and all 32 | Submissions that You, now or in the future (except as described in Section 33 | 4 below), Submit to any Project. 34 | 35 | 3. Originality of Work. You represent that each of Your Submissions is 36 | entirely Your original work. Should You wish to Submit materials that are 37 | not Your original work, You may Submit them separately to the Project if 38 | You (a) retain all copyright and license information that was in the 39 | materials as You received them, (b) in the description accompanying Your 40 | Submission, include the phrase "Submission containing materials of a 41 | third party:" followed by the names of the third party and any licenses 42 | or other restrictions of which You are aware, and (c) follow any other 43 | instructions in the Project’s written guidelines concerning Submissions. 44 | 45 | 4. Your Employer. References to "employer" in this Agreement include Your 46 | employer or anyone else for whom You are acting in making Your Submission, 47 | e.g. as a contractor, vendor, or agent. If Your Submission is made in the 48 | course of Your work for an employer or Your employer has intellectual 49 | property rights in Your Submission by contract or applicable law, You must 50 | secure permission from Your employer to make the Submission before signing 51 | this Agreement. In that case, the term "You" in this Agreement will refer 52 | to You and the employer collectively. If You change employers in the 53 | future and desire to Submit additional Submissions for the new employer, 54 | then You agree to sign a new Agreement and secure permission from the 55 | new employer before Submitting those Submissions. 56 | 57 | 5. Licenses. 58 | 59 | a. Copyright License. You grant NVIDIA, and those who receive the Submission 60 | directly or indirectly from NVIDIA, a perpetual, worldwide, non-exclusive, 61 | royalty-free, irrevocable license in the Submission to reproduce, prepare 62 | derivative works of, publicly display, publicly perform, and distribute the 63 | Submission and such derivative works, and to sublicense any or all of the 64 | foregoing rights to third parties. 65 | 66 | b. Patent License. You grant NVIDIA, and those who receive the Submission 67 | directly or indirectly from NVIDIA, a perpetual, worldwide, non-exclusive, 68 | royalty-free, irrevocable license under Your patent claims that are 69 | necessarily infringed by the Submission or the combination of the Submission 70 | with the Project to which it was Submitted to make, have made, use, offer to 71 | sell, sell and import or otherwise dispose of the Submission alone or with 72 | the Project. 73 | 74 | c. Other Rights Reserved. Each party reserves all rights not expressly 75 | granted in this Agreement. No additional licenses or rights whatsoever 76 | (including, without limitation, any implied licenses) are granted by 77 | implication, exhaustion, estoppel or otherwise. 78 | 79 | 6. Representations and Warranties. You represent that You are legally 80 | entitled to grant the above licenses. You represent that each of Your 81 | Submissions is entirely Your original work (except as You may have 82 | disclosed under Section 3). You represent that You have secured permission 83 | from Your employer to make the Submission in cases where Your Submission 84 | is made in the course of Your work for Your employer or Your employer has 85 | intellectual property rights in Your Submission by contract or applicable 86 | law. If You are signing this Agreement on behalf of Your employer, You 87 | represent and warrant that You have the necessary authority to bind the 88 | listed employer to the obligations contained in this Agreement. You are 89 | not expected to provide support for Your Submission, unless You choose to 90 | do so. UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND 91 | EXCEPT FOR THE WARRANTIES EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE 92 | SUBMISSION PROVIDED UNDER THIS AGREEMENT IS PROVIDED WITHOUT WARRANTY OF 93 | ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF NONINFRINGEMENT, 94 | MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. 95 | 96 | 7. Notice to NVIDIA. You agree to notify NVIDIA in writing of any facts 97 | or circumstances of which You later become aware that would make Your 98 | representations in this Agreement inaccurate in any respect. 99 | 100 | 8. Information about Submissions. You agree that contributions to Projects 101 | and information about contributions may be maintained indefinitely and 102 | disclosed publicly, including Your name and other information that You 103 | submit with Your Submission. 104 | 105 | 9. Governing Law/Jurisdiction. Claims arising under this Agreement shall 106 | be governed by the laws of Delaware, excluding its principles of conflict 107 | of laws and the United Nations Convention on Contracts for the Sale of 108 | Goods. The state and/or federal courts residing in Santa Clara County, 109 | California shall have exclusive jurisdiction over any dispute or claim 110 | arising out of this Agreement. You may not export the Software in 111 | violation of applicable export laws and regulations. 112 | 113 | 10. Entire Agreement/Assignment. This Agreement is the entire agreement 114 | between the parties, and supersedes any and all prior agreements, 115 | understandings or communications, written or oral, between the parties 116 | relating to the subject matter hereof. This Agreement may be assigned by 117 | NVIDIA. 118 | 119 | 120 | 121 | Please select one of the options below and sign as indicated. By signing, 122 | You accept and agree to the terms of this Contribution License Agreement 123 | for Your present and future Submissions to NVIDIA. 124 | 125 | ___ I have sole ownership of intellectual property rights to my Submissions 126 | and I am not making Submissions in the course of work for my employer. 127 | 128 | Name ("You"): _________________________________________ 129 | Signature: _________________________________________ 130 | Date: _________________________________________ 131 | GitHub Login: _________________________________________ 132 | Email: _________________________________________ 133 | Address: _________________________________________ 134 | 135 | 136 | ___ I am making Submissions in the course of work for my employer (or my 137 | employer has intellectual property rights in my Submissions by contract or 138 | applicable law). I have permission from my employer to make Submissions and 139 | enter into this Agreement on behalf of my employer. By signing below, the 140 | defined term "You" includes me and my employer. 141 | 142 | Company Name: _________________________________________ 143 | Signature: _________________________________________ 144 | By: _________________________________________ 145 | Title: _________________________________________ 146 | Date: _________________________________________ 147 | GitHub Login: _________________________________________ 148 | Email: _________________________________________ 149 | Address: _________________________________________ 150 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | cmake_minimum_required(VERSION 3.18) 24 | 25 | project(donut_examples) 26 | 27 | set(CMAKE_CXX_STANDARD 17) 28 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 29 | set(CMAKE_CXX_EXTENSIONS ON) 30 | 31 | if (MSVC) 32 | set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") 33 | 34 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /D_ITERATOR_DEBUG_LEVEL=1") 35 | endif() 36 | 37 | option(DONUT_WITH_ASSIMP "" OFF) 38 | 39 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin") 40 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") 41 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") 42 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") 43 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") 44 | set(DONUT_SHADERS_OUTPUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/framework") 45 | 46 | add_subdirectory(donut) 47 | add_subdirectory(feature_demo) 48 | add_subdirectory(examples/basic_triangle) 49 | add_subdirectory(examples/vertex_buffer) 50 | add_subdirectory(examples/deferred_shading) 51 | add_subdirectory(examples/headless) 52 | 53 | if (NVRHI_WITH_DX12) 54 | execute_process(COMMAND ${DXC_PATH} "-T cs_6_8" "ver_test.hlsl" OUTPUT_QUIET RESULT_VARIABLE DXC_SM_6_8 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/examples/work_graphs") 55 | if (DXC_SM_6_8 EQUAL "0") 56 | add_subdirectory(examples/work_graphs) 57 | else() 58 | message(WARNING "Work Graphs sample requires DirectX Compiler (dxc.exe) with Shader Model 6.8 support (dxcompiler.dll version 1.8.2403.34 or later) - sample will be omitted") 59 | endif() 60 | endif() 61 | 62 | if (NVRHI_WITH_VULKAN OR NVRHI_WITH_DX12) 63 | add_subdirectory(examples/bindless_rendering) 64 | add_subdirectory(examples/variable_shading) 65 | add_subdirectory(examples/rt_triangle) 66 | add_subdirectory(examples/rt_shadows) 67 | add_subdirectory(examples/rt_bindless) 68 | add_subdirectory(examples/rt_particles) 69 | add_subdirectory(examples/meshlets) 70 | 71 | if (DONUT_WITH_TASKFLOW) 72 | add_subdirectory(examples/threaded_rendering) 73 | endif() 74 | endif() 75 | 76 | if (NVRHI_WITH_DX12) 77 | # The RT Reflections example uses local bindings (local root signatures) which are unsupported on Vulkan 78 | add_subdirectory(examples/rt_reflections) 79 | endif() 80 | 81 | if (NVRHI_WITH_VULKAN) 82 | # Shader specializations are a unique Vulkan feature 83 | add_subdirectory(examples/shader_specializations) 84 | endif() 85 | 86 | if (DONUT_WITH_AFTERMATH AND NVRHI_WITH_AFTERMATH) 87 | add_subdirectory(examples/aftermath) 88 | endif() -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a 4 | copy of this software and associated documentation files (the "Software"), 5 | to deal in the Software without restriction, including without limitation 6 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 7 | and/or sell copies of the Software, and to permit persons to whom the 8 | Software is furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Donut Samples 2 | 3 | This repository provides a collection of example applications built using the [Donut framework](https://github.com/NVIDIA-RTX/Donut). 4 | 5 | | Application | DX11 | DX12 | VK | Description | 6 | |-----------------------------------------------------------|:------------------:|:------------------:|:------------------:|-------------| 7 | | [Feature Demo](feature_demo) | :white_check_mark: | :white_check_mark: | :white_check_mark: | A demo application that shows most of the raster-based features and effects available. | 8 | | [Basic Triangle](examples/basic_triangle) | :white_check_mark: | :white_check_mark: | :white_check_mark: | The most basic example that draws a single triangle. | 9 | | [Bindless Ray Tracing](examples/rt_bindless) | | :white_check_mark: | :white_check_mark: | Renders a scene using ray tracing, starting from primary rays, and using bindless resources. Includes skeletal animation. | 10 | | [Bindless Rendering](examples/bindless_rendering) | | :white_check_mark: | :white_check_mark: | Renders a scene using bindless resources for minimal CPU overhead. | 11 | | [Deferred Shading](examples/deferred_shading) | :white_check_mark: | :white_check_mark: | :white_check_mark: | Draws a textured cube into a G-buffer and applies deferred shading to it. | 12 | | [Headless Device](examples/headless) | :white_check_mark: | :white_check_mark: | :white_check_mark: | Tests operation of a graphics device without a window by adding some numbers. | 13 | | [Meshlets](examples/meshlets) | | :white_check_mark: | :white_check_mark: | Renders a triangle using meshlets. | 14 | | [Ray Traced Particles](examples/rt_particles) | | :white_check_mark: | :white_check_mark: | Renders a particle system using ray tracing in an environment with mirrors. | 15 | | [Ray Traced Reflections](examples/rt_reflections) | | :white_check_mark: | | Rasterizes the G-buffer and renders basic ray traced reflections. Materials are accessed using local root signatures. | 16 | | [Ray Traced Shadows](examples/rt_shadows) | | :white_check_mark: | :white_check_mark: | Rasterizes the G-buffer and renders basic ray traced directional shadows. | 17 | | [Ray Traced Triangle](examples/rt_triangle) | | :white_check_mark: | :white_check_mark: | Renders a triangle using ray tracing. | 18 | | [Shader Specializations](examples/shader_specializations) | | | :white_check_mark: | Renders a few triangles using different specializations of the same shader. | 19 | | [Threaded Rendering](examples/threaded_rendering) | | :white_check_mark: | :white_check_mark: | Renders a cube map view of a scene using multiple threads, one per face. | 20 | | [Variable Shading](examples/variable_shading) | | :white_check_mark: | :white_check_mark: | Renders a scene with variable shading rate specified by a texture. | 21 | | [Vertex Buffer](examples/vertex_buffer) | :white_check_mark: | :white_check_mark: | :white_check_mark: | Creates a vertex buffer for a cube and draws the cube. | 22 | | [Work Graphs](examples/work_graphs) | | :white_check_mark: | | Demonstrates the new D3D12 work graphs API via a tiled deferred shading renderer that dynamically chooses shaders for each screen tile. Requires DXC with shader model 6.8 support. | 23 | 24 | ## Requirements 25 | 26 | Same as the [requirements for Donut](https://github.com/NVIDIA-RTX/Donut). 27 | 28 | ## Build 29 | 30 | 1. Clone the repository **with all submodules**: 31 | 32 | `git clone --recursive ` 33 | 34 | 2. Create a build folder. 35 | 36 | `cd donut_examples && mkdir build && cd build` 37 | 38 | * Any name works, but git is configured to ignore folders named 'build\*' 39 | * This folder should be placed under directory created by 'git clone' in step #1 40 | 41 | 3. Use CMake to configure the build and generate the project files. 42 | 43 | * Linux: `cmake ..` 44 | * Windows: use of CMake GUI is recommended. Make sure to select the x64 platform for the generator. 45 | 46 | 4. Build the solution generated by CMake in the build folder. 47 | 48 | * Linux: `make -j8` (example for an 8-core CPU) 49 | * Windows: Open the generated solution with Visual Studio and build it. 50 | 51 | 5. Run the examples. They should be built in the `bin` folder. 52 | 53 | ## Command Line 54 | 55 | Most examples support multiple graphics APIs (on Windows). They are built with all APIs supported in the same executable, 56 | and the API can be switched from the command line. Use these command line arguments: 57 | 58 | - `-dx11` for D3D11 59 | - `-dx12` for D3D12 (default) 60 | - `-vk` for Vulkan 61 | 62 | The Feature Demo supports additional command line arguments: 63 | 64 | - `-debug` to enable the graphics API debug layer or runtime, and the [NVRHI](https://github.com/NVIDIA-RTX/NVRHI) validation layer. 65 | - `-fullscreen` to start in full screen mode. 66 | - `-no-vsync` to start without VSync (can be toggled in the GUI). 67 | - `-print-graph` to print the scene graph into the output log on startup. 68 | - `-width` and `-height` to set the window size. 69 | - `` to load any supported model or scene from the given file. 70 | 71 | 72 | ## License 73 | 74 | Donut Examples are licensed under the [MIT License](LICENSE.txt). -------------------------------------------------------------------------------- /examples/aftermath/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project aftermath_sample) 28 | set(folder "Examples/Aftermath") 29 | 30 | donut_compile_shaders_all_platforms( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Aftermath" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | OUTPUT_BASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project} 36 | # applications using Aftermath need to set the --embedPDB option when compiling shaders 37 | # without it, NSight will not be able to resolve back to original source (only to shader IL) 38 | SHADERMAKE_OPTIONS --embedPDB 39 | ) 40 | 41 | add_executable(${project} WIN32 ${sources}) 42 | target_link_libraries(${project} donut_app donut_engine) 43 | add_dependencies(${project} ${project}_shaders) 44 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 45 | 46 | if (MSVC) 47 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 48 | endif() 49 | 50 | if (WIN32) 51 | add_custom_command( TARGET ${project} POST_BUILD 52 | COMMAND ${CMAKE_COMMAND} -E copy ${AFTERMATH_RUNTIME_LIBRARY} $ 53 | COMMAND_EXPAND_LISTS ) 54 | else() 55 | add_custom_command( TARGET ${project} POST_BUILD 56 | COMMAND ${CMAKE_COMMAND} -E copy ${AFTERMATH_LIBRARY} $ 57 | COMMAND_EXPAND_LISTS ) 58 | endif() 59 | -------------------------------------------------------------------------------- /examples/aftermath/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T vs -E main_vs 2 | shaders.hlsl -T ps -E main_ps 3 | -------------------------------------------------------------------------------- /examples/aftermath/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | static const float2 g_positions[] = { 24 | float2(-0.5, -0.5), 25 | float2(0, 0.5), 26 | float2(0.5, -0.5) 27 | }; 28 | 29 | static const float3 g_colors[] = { 30 | float3(1, 0, 0), 31 | float3(0, 1, 0), 32 | float3(0, 0, 1) 33 | }; 34 | 35 | struct Constants 36 | { 37 | uint crashType; 38 | }; 39 | 40 | #ifdef SPIRV 41 | 42 | [[vk::push_constant]] ConstantBuffer g_constants; 43 | 44 | #else 45 | 46 | cbuffer g_constants : register(b0) 47 | { 48 | Constants g_constants; 49 | }; 50 | #endif 51 | 52 | RWStructuredBuffer g_buffer : register(u0); 53 | 54 | void main_vs( 55 | uint i_vertexId : SV_VertexID, 56 | out float4 o_pos : SV_Position, 57 | out float3 o_color : COLOR 58 | ) 59 | { 60 | o_pos = float4(g_positions[i_vertexId], 0, 1); 61 | o_color = g_colors[i_vertexId]; 62 | 63 | // infinite loop to cause a timeout crash 64 | if (g_constants.crashType == 1) 65 | { 66 | float test = 0.99f; 67 | while (test < 1.f) 68 | { 69 | test *= test; 70 | } 71 | // execution will never reach this line, but it is necessary to keep the compiler from optimizing out the loop 72 | // since otherwise the loop result is never used anywhere 73 | o_color.r *= test; 74 | } 75 | 76 | // for page fault crash, if g_buffer is destroyed while this shader is executing, this load should fail 77 | o_color.r += g_buffer[i_vertexId]; 78 | } 79 | 80 | void main_ps( 81 | in float4 i_pos : SV_Position, 82 | in float3 i_color : COLOR, 83 | out float4 o_color : SV_Target0 84 | ) 85 | { 86 | o_color = float4(i_color, 1); 87 | } 88 | -------------------------------------------------------------------------------- /examples/basic_triangle/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project basic_triangle) 28 | set(folder "Examples/Basic Triangle") 29 | 30 | donut_compile_shaders_all_platforms( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Basic Triangle" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | OUTPUT_BASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project} 36 | ) 37 | 38 | add_executable(${project} WIN32 ${sources}) 39 | target_link_libraries(${project} donut_app donut_engine) 40 | add_dependencies(${project} ${project}_shaders) 41 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 42 | 43 | if (MSVC) 44 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 45 | endif() 46 | -------------------------------------------------------------------------------- /examples/basic_triangle/basic_triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | using namespace donut; 31 | 32 | static const char* g_WindowTitle = "Donut Example: Basic Triangle"; 33 | 34 | class BasicTriangle : public app::IRenderPass 35 | { 36 | private: 37 | nvrhi::ShaderHandle m_VertexShader; 38 | nvrhi::ShaderHandle m_PixelShader; 39 | nvrhi::GraphicsPipelineHandle m_Pipeline; 40 | nvrhi::CommandListHandle m_CommandList; 41 | 42 | public: 43 | using IRenderPass::IRenderPass; 44 | 45 | bool Init() 46 | { 47 | std::filesystem::path appShaderPath = app::GetDirectoryWithExecutable() / "shaders/basic_triangle" / app::GetShaderTypeName(GetDevice()->getGraphicsAPI()); 48 | 49 | auto nativeFS = std::make_shared(); 50 | engine::ShaderFactory shaderFactory(GetDevice(), nativeFS, appShaderPath); 51 | 52 | m_VertexShader = shaderFactory.CreateShader("shaders.hlsl", "main_vs", nullptr, nvrhi::ShaderType::Vertex); 53 | m_PixelShader = shaderFactory.CreateShader("shaders.hlsl", "main_ps", nullptr, nvrhi::ShaderType::Pixel); 54 | 55 | if (!m_VertexShader || !m_PixelShader) 56 | { 57 | return false; 58 | } 59 | 60 | m_CommandList = GetDevice()->createCommandList(); 61 | 62 | return true; 63 | } 64 | 65 | void BackBufferResizing() override 66 | { 67 | m_Pipeline = nullptr; 68 | } 69 | 70 | void Animate(float fElapsedTimeSeconds) override 71 | { 72 | GetDeviceManager()->SetInformativeWindowTitle(g_WindowTitle); 73 | } 74 | 75 | void Render(nvrhi::IFramebuffer* framebuffer) override 76 | { 77 | if (!m_Pipeline) 78 | { 79 | nvrhi::GraphicsPipelineDesc psoDesc; 80 | psoDesc.VS = m_VertexShader; 81 | psoDesc.PS = m_PixelShader; 82 | psoDesc.primType = nvrhi::PrimitiveType::TriangleList; 83 | psoDesc.renderState.depthStencilState.depthTestEnable = false; 84 | 85 | m_Pipeline = GetDevice()->createGraphicsPipeline(psoDesc, framebuffer); 86 | } 87 | 88 | m_CommandList->open(); 89 | 90 | nvrhi::utils::ClearColorAttachment(m_CommandList, framebuffer, 0, nvrhi::Color(0.f)); 91 | 92 | nvrhi::GraphicsState state; 93 | state.pipeline = m_Pipeline; 94 | state.framebuffer = framebuffer; 95 | state.viewport.addViewportAndScissorRect(framebuffer->getFramebufferInfo().getViewport()); 96 | 97 | m_CommandList->setGraphicsState(state); 98 | 99 | nvrhi::DrawArguments args; 100 | args.vertexCount = 3; 101 | m_CommandList->draw(args); 102 | 103 | m_CommandList->close(); 104 | GetDevice()->executeCommandList(m_CommandList); 105 | } 106 | 107 | }; 108 | 109 | #ifdef WIN32 110 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 111 | #else 112 | int main(int __argc, const char** __argv) 113 | #endif 114 | { 115 | nvrhi::GraphicsAPI api = app::GetGraphicsAPIFromCommandLine(__argc, __argv); 116 | app::DeviceManager* deviceManager = app::DeviceManager::Create(api); 117 | 118 | app::DeviceCreationParameters deviceParams; 119 | #ifdef _DEBUG 120 | deviceParams.enableDebugRuntime = true; 121 | deviceParams.enableNvrhiValidationLayer = true; 122 | #endif 123 | 124 | if (!deviceManager->CreateWindowDeviceAndSwapChain(deviceParams, g_WindowTitle)) 125 | { 126 | log::fatal("Cannot initialize a graphics device with the requested parameters"); 127 | return 1; 128 | } 129 | 130 | { 131 | BasicTriangle example(deviceManager); 132 | if (example.Init()) 133 | { 134 | deviceManager->AddRenderPassToBack(&example); 135 | deviceManager->RunMessageLoop(); 136 | deviceManager->RemoveRenderPass(&example); 137 | } 138 | } 139 | 140 | deviceManager->Shutdown(); 141 | 142 | delete deviceManager; 143 | 144 | return 0; 145 | } 146 | -------------------------------------------------------------------------------- /examples/basic_triangle/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T vs -E main_vs 2 | shaders.hlsl -T ps -E main_ps 3 | -------------------------------------------------------------------------------- /examples/basic_triangle/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | static const float2 g_positions[] = { 24 | float2(-0.5, -0.5), 25 | float2(0, 0.5), 26 | float2(0.5, -0.5) 27 | }; 28 | 29 | static const float3 g_colors[] = { 30 | float3(1, 0, 0), 31 | float3(0, 1, 0), 32 | float3(0, 0, 1) 33 | }; 34 | 35 | void main_vs( 36 | uint i_vertexId : SV_VertexID, 37 | out float4 o_pos : SV_Position, 38 | out float3 o_color : COLOR 39 | ) 40 | { 41 | o_pos = float4(g_positions[i_vertexId], 0, 1); 42 | o_color = g_colors[i_vertexId]; 43 | } 44 | 45 | void main_ps( 46 | in float4 i_pos : SV_Position, 47 | in float3 i_color : COLOR, 48 | out float4 o_color : SV_Target0 49 | ) 50 | { 51 | o_color = float4(i_color, 1); 52 | } 53 | -------------------------------------------------------------------------------- /examples/bindless_rendering/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project bindless_rendering) 28 | set(folder "Examples/Bindless Rendering") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Bindless Rendering" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_render donut_app donut_engine) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | -------------------------------------------------------------------------------- /examples/bindless_rendering/bindless_rendering.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #pragma pack_matrix(row_major) 24 | 25 | #include 26 | #include 27 | 28 | #ifdef SPIRV 29 | #define VK_PUSH_CONSTANT [[vk::push_constant]] 30 | #define VK_BINDING(reg,dset) [[vk::binding(reg,dset)]] 31 | #else 32 | #define VK_PUSH_CONSTANT 33 | #define VK_BINDING(reg,dset) 34 | #endif 35 | 36 | struct InstanceConstants 37 | { 38 | uint instance; 39 | uint geometryInMesh; 40 | }; 41 | 42 | ConstantBuffer g_View : register(b0); 43 | VK_PUSH_CONSTANT ConstantBuffer g_Instance : register(b1); 44 | StructuredBuffer t_InstanceData : register(t0); 45 | StructuredBuffer t_GeometryData : register(t1); 46 | StructuredBuffer t_MaterialConstants : register(t2); 47 | SamplerState s_MaterialSampler : register(s0); 48 | 49 | VK_BINDING(0, 1) ByteAddressBuffer t_BindlessBuffers[] : register(t0, space1); 50 | VK_BINDING(1, 1) Texture2D t_BindlessTextures[] : register(t0, space2); 51 | 52 | void vs_main( 53 | in uint i_vertexID : SV_VertexID, 54 | out float4 o_position : SV_Position, 55 | out float2 o_uv : TEXCOORD, 56 | out uint o_material : MATERIAL) 57 | { 58 | InstanceData instance = t_InstanceData[g_Instance.instance]; 59 | GeometryData geometry = t_GeometryData[instance.firstGeometryIndex + g_Instance.geometryInMesh]; 60 | 61 | ByteAddressBuffer indexBuffer = t_BindlessBuffers[geometry.indexBufferIndex]; 62 | ByteAddressBuffer vertexBuffer = t_BindlessBuffers[geometry.vertexBufferIndex]; 63 | 64 | uint index = indexBuffer.Load(geometry.indexOffset + i_vertexID * 4); 65 | 66 | float2 texcoord = geometry.texCoord1Offset == ~0u ? 0 : asfloat(vertexBuffer.Load2(geometry.texCoord1Offset + index * 8)); 67 | float3 objectSpacePosition = asfloat(vertexBuffer.Load3(geometry.positionOffset + index * 12));; 68 | 69 | float3 worldSpacePosition = mul(instance.transform, float4(objectSpacePosition, 1.0)).xyz; 70 | float4 clipSpacePosition = mul(float4(worldSpacePosition, 1.0), g_View.matWorldToClip); 71 | 72 | o_uv = texcoord; 73 | o_position = clipSpacePosition; 74 | o_material = geometry.materialIndex; 75 | } 76 | 77 | void ps_main( 78 | in float4 i_position : SV_Position, 79 | in float2 i_uv : TEXCOORD, 80 | nointerpolation in uint i_material : MATERIAL, 81 | out float4 o_color : SV_Target0) 82 | { 83 | MaterialConstants material = t_MaterialConstants[i_material]; 84 | 85 | float3 diffuse = material.baseOrDiffuseColor; 86 | 87 | if (material.baseOrDiffuseTextureIndex >= 0) 88 | { 89 | Texture2D diffuseTexture = t_BindlessTextures[material.baseOrDiffuseTextureIndex]; 90 | 91 | float4 diffuseTextureValue = diffuseTexture.Sample(s_MaterialSampler, i_uv); 92 | 93 | if (material.domain == MaterialDomain_AlphaTested) 94 | clip(diffuseTextureValue.a - material.alphaCutoff); 95 | 96 | diffuse *= diffuseTextureValue.rgb; 97 | } 98 | 99 | o_color = float4(diffuse.rgb, 1); 100 | } -------------------------------------------------------------------------------- /examples/bindless_rendering/shaders.cfg: -------------------------------------------------------------------------------- 1 | bindless_rendering.hlsl -T vs -E vs_main 2 | bindless_rendering.hlsl -T ps -E ps_main 3 | -------------------------------------------------------------------------------- /examples/deferred_shading/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | file(GLOB sources "*.cpp" "*.h") 24 | 25 | add_executable(deferred_shading WIN32 ${sources}) 26 | target_link_libraries(deferred_shading donut_render donut_app donut_engine) 27 | set_target_properties(deferred_shading PROPERTIES FOLDER "Examples/Deferred Shading") 28 | 29 | if (MSVC) 30 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 31 | endif() 32 | -------------------------------------------------------------------------------- /examples/deferred_shading/CubeGeometry.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include 24 | 25 | static const donut::math::float3 g_Positions[] = { 26 | {-0.5f, 0.5f, -0.5f}, // front face 27 | { 0.5f, -0.5f, -0.5f}, 28 | {-0.5f, -0.5f, -0.5f}, 29 | { 0.5f, 0.5f, -0.5f}, 30 | 31 | { 0.5f, -0.5f, -0.5f}, // right side face 32 | { 0.5f, 0.5f, 0.5f}, 33 | { 0.5f, -0.5f, 0.5f}, 34 | { 0.5f, 0.5f, -0.5f}, 35 | 36 | {-0.5f, 0.5f, 0.5f}, // left side face 37 | {-0.5f, -0.5f, -0.5f}, 38 | {-0.5f, -0.5f, 0.5f}, 39 | {-0.5f, 0.5f, -0.5f}, 40 | 41 | { 0.5f, 0.5f, 0.5f}, // back face 42 | {-0.5f, -0.5f, 0.5f}, 43 | { 0.5f, -0.5f, 0.5f}, 44 | {-0.5f, 0.5f, 0.5f}, 45 | 46 | {-0.5f, 0.5f, -0.5f}, // top face 47 | { 0.5f, 0.5f, 0.5f}, 48 | { 0.5f, 0.5f, -0.5f}, 49 | {-0.5f, 0.5f, 0.5f}, 50 | 51 | { 0.5f, -0.5f, 0.5f}, // bottom face 52 | {-0.5f, -0.5f, -0.5f}, 53 | { 0.5f, -0.5f, -0.5f}, 54 | {-0.5f, -0.5f, 0.5f}, 55 | }; 56 | 57 | static const donut::math::float2 g_TexCoords[] = { 58 | {0.0f, 0.0f}, // front face 59 | {1.0f, 1.0f}, 60 | {0.0f, 1.0f}, 61 | {1.0f, 0.0f}, 62 | 63 | {0.0f, 1.0f}, // right side face 64 | {1.0f, 0.0f}, 65 | {1.0f, 1.0f}, 66 | {0.0f, 0.0f}, 67 | 68 | {0.0f, 0.0f}, // left side face 69 | {1.0f, 1.0f}, 70 | {0.0f, 1.0f}, 71 | {1.0f, 0.0f}, 72 | 73 | {0.0f, 0.0f}, // back face 74 | {1.0f, 1.0f}, 75 | {0.0f, 1.0f}, 76 | {1.0f, 0.0f}, 77 | 78 | {0.0f, 1.0f}, // top face 79 | {1.0f, 0.0f}, 80 | {1.0f, 1.0f}, 81 | {0.0f, 0.0f}, 82 | 83 | {1.0f, 1.0f}, // bottom face 84 | {0.0f, 0.0f}, 85 | {1.0f, 0.0f}, 86 | {0.0f, 1.0f}, 87 | }; 88 | 89 | static const donut::math::uint g_Normals[] = { 90 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 0.0f)), // front face 91 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 0.0f)), 92 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 0.0f)), 93 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 0.0f)), 94 | 95 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 0.0f)), // right side face 96 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 0.0f)), 97 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 0.0f)), 98 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 0.0f)), 99 | 100 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 0.0f)), // left side face 101 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 0.0f)), 102 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 0.0f)), 103 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 0.0f)), 104 | 105 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 0.0f)), // back face 106 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 0.0f)), 107 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 0.0f)), 108 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 0.0f)), 109 | 110 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 1.0f, 0.0f, 0.0f)), // top face 111 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 1.0f, 0.0f, 0.0f)), 112 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 1.0f, 0.0f, 0.0f)), 113 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 1.0f, 0.0f, 0.0f)), 114 | 115 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, -1.0f, 0.0f, 0.0f)), // bottom face 116 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, -1.0f, 0.0f, 0.0f)), 117 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, -1.0f, 0.0f, 0.0f)), 118 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, -1.0f, 0.0f, 0.0f)), 119 | }; 120 | 121 | static const donut::math::uint g_Tangents[] = { 122 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), // front face 123 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 124 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 125 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 126 | 127 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 1.0f)), // right side face 128 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 1.0f)), 129 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 1.0f)), 130 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, 1.0f, 1.0f)), 131 | 132 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 1.0f)), // left side face 133 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 1.0f)), 134 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 1.0f)), 135 | donut::math::vectorToSnorm8(donut::math::float4(0.0f, 0.0f, -1.0f, 1.0f)), 136 | 137 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 1.0f)), // back face 138 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 1.0f)), 139 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 1.0f)), 140 | donut::math::vectorToSnorm8(donut::math::float4(-1.0f, 0.0f, 0.0f, 1.0f)), 141 | 142 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), // top face 143 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 144 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 145 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 146 | 147 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), // bottom face 148 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 149 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 150 | donut::math::vectorToSnorm8(donut::math::float4(1.0f, 0.0f, 0.0f, 1.0f)), 151 | }; 152 | 153 | static const uint32_t g_Indices[] = { 154 | 0, 1, 2, 0, 3, 1, // front face 155 | 4, 5, 6, 4, 7, 5, // left face 156 | 8, 9, 10, 8, 11, 9, // right face 157 | 12, 13, 14, 12, 15, 13, // back face 158 | 16, 17, 18, 16, 19, 17, // top face 159 | 20, 21, 22, 20, 23, 21, // bottom face 160 | }; 161 | -------------------------------------------------------------------------------- /examples/headless/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2024-2023, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project headless) 28 | set(folder "Examples/Headless") 29 | 30 | donut_compile_shaders_all_platforms( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Headless" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | OUTPUT_BASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project} 36 | ) 37 | 38 | add_executable(${project} ${sources}) 39 | target_link_libraries(${project} donut_app donut_engine) 40 | add_dependencies(${project} ${project}_shaders) 41 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 42 | 43 | if (MSVC) 44 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 45 | endif() 46 | -------------------------------------------------------------------------------- /examples/headless/headless.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | using namespace donut; 31 | 32 | bool RunTest(nvrhi::IDevice* device) 33 | { 34 | std::filesystem::path appShaderPath = app::GetDirectoryWithExecutable() / "shaders/headless" / app::GetShaderTypeName(device->getGraphicsAPI()); 35 | 36 | auto nativeFS = std::make_shared(); 37 | engine::ShaderFactory shaderFactory(device, nativeFS, appShaderPath); 38 | 39 | nvrhi::ShaderHandle computeShader = shaderFactory.CreateShader("shaders.hlsl", "main", nullptr, nvrhi::ShaderType::Compute); 40 | 41 | if (!computeShader) 42 | return false; 43 | 44 | // The shader is performing a reduction operation within one thread group, adding all uint's in the input buffer. 45 | // The number of uint's is the same as the thread group size. 46 | constexpr uint32_t numInputValues = 256; 47 | 48 | // Create the input, output, and readback buffers... 49 | 50 | auto inputBufferDesc = nvrhi::BufferDesc() 51 | .setByteSize(sizeof(uint32_t) * numInputValues) 52 | .setCanHaveTypedViews(true) 53 | .setFormat(nvrhi::Format::R32_UINT) 54 | .setDebugName("InputBuffer") 55 | .setInitialState(nvrhi::ResourceStates::CopyDest) 56 | .setKeepInitialState(true); 57 | 58 | auto outputBufferDesc = nvrhi::BufferDesc() 59 | .setByteSize(sizeof(uint32_t)) 60 | .setCanHaveTypedViews(true) 61 | .setCanHaveUAVs(true) 62 | .setFormat(nvrhi::Format::R32_UINT) 63 | .setDebugName("OutputBuffer") 64 | .setInitialState(nvrhi::ResourceStates::UnorderedAccess) 65 | .setKeepInitialState(true); 66 | 67 | auto readbackBufferDesc = nvrhi::BufferDesc() 68 | .setByteSize(outputBufferDesc.byteSize) 69 | .setCpuAccess(nvrhi::CpuAccessMode::Read) 70 | .setDebugName("ReadbackBuffer") 71 | .setInitialState(nvrhi::ResourceStates::CopyDest) 72 | .setKeepInitialState(true); 73 | 74 | auto inputBuffer = device->createBuffer(inputBufferDesc); 75 | auto outputBuffer = device->createBuffer(outputBufferDesc); 76 | auto readbackBuffer = device->createBuffer(readbackBufferDesc); 77 | 78 | // Create the binding layout and binding set... 79 | 80 | auto bindingSetDesc = nvrhi::BindingSetDesc() 81 | .addItem(nvrhi::BindingSetItem::TypedBuffer_SRV(0, inputBuffer)) 82 | .addItem(nvrhi::BindingSetItem::TypedBuffer_UAV(0, outputBuffer)); 83 | 84 | nvrhi::BindingSetHandle bindingSet; 85 | nvrhi::BindingLayoutHandle bindingLayout; 86 | if (!nvrhi::utils::CreateBindingSetAndLayout(device, nvrhi::ShaderType::Compute, 0, bindingSetDesc, bindingLayout, bindingSet)) 87 | return false; 88 | 89 | // Create the compute pipeline... 90 | 91 | auto computePipelineDesc = nvrhi::ComputePipelineDesc() 92 | .setComputeShader(computeShader) 93 | .addBindingLayout(bindingLayout); 94 | 95 | auto computePipeline = device->createComputePipeline(computePipelineDesc); 96 | 97 | // Create a command list and begin recording 98 | 99 | nvrhi::CommandListHandle commandList = device->createCommandList(); 100 | commandList->open(); 101 | 102 | // Fill the input buffer with some numbers and compute the expected result of shader operation 103 | 104 | uint32_t inputData[numInputValues]; 105 | uint32_t expectedResult = 0; 106 | for (uint32_t i = 0; i < numInputValues; ++i) 107 | { 108 | inputData[i] = i + 1; 109 | expectedResult += inputData[i]; 110 | } 111 | commandList->writeBuffer(inputBuffer, inputData, sizeof(inputData)); 112 | 113 | // Run the shader 114 | 115 | auto state = nvrhi::ComputeState() 116 | .setPipeline(computePipeline) 117 | .addBindingSet(bindingSet); 118 | commandList->setComputeState(state); 119 | commandList->dispatch(1, 1, 1); 120 | 121 | // Copy the shader output into the staging buffer 122 | 123 | commandList->copyBuffer(readbackBuffer, 0, outputBuffer, 0, readbackBufferDesc.byteSize); 124 | 125 | // Close and execute the command list, wait on the CPU side for it to be finished 126 | 127 | commandList->close(); 128 | device->executeCommandList(commandList); 129 | device->waitForIdle(); 130 | 131 | // Read the shader output 132 | 133 | uint32_t const* outputData = static_cast(device->mapBuffer(readbackBuffer, nvrhi::CpuAccessMode::Read)); 134 | uint32_t computedResult = *outputData; 135 | device->unmapBuffer(readbackBuffer); 136 | 137 | // Compre the result to the expected one to see if the test passes 138 | 139 | printf("Expected result: %d, computed result: %d\n", expectedResult, computedResult); 140 | if (computedResult == expectedResult) 141 | { 142 | printf("Test PASSED\n"); 143 | return true; 144 | } 145 | else 146 | { 147 | printf("Test FAILED!\n"); 148 | return false; 149 | } 150 | } 151 | 152 | 153 | int main(int argc, const char** argv) 154 | { 155 | log::ConsoleApplicationMode(); 156 | #ifndef _DEBUG 157 | log::SetMinSeverity(log::Severity::Warning); 158 | #endif 159 | 160 | nvrhi::GraphicsAPI api = app::GetGraphicsAPIFromCommandLine(argc, argv); 161 | std::unique_ptr deviceManager = std::unique_ptr(app::DeviceManager::Create(api)); 162 | 163 | app::DeviceCreationParameters deviceParams; 164 | #ifdef _DEBUG 165 | deviceParams.enableDebugRuntime = true; 166 | deviceParams.enableNvrhiValidationLayer = true; 167 | #endif 168 | 169 | for (int i = 1; i < argc; ++i) 170 | { 171 | if (strcmp(argv[i], "--help") == 0) 172 | { 173 | printf("Usage: %s [options]\n" 174 | " -dx11 Use DX11 API\n" 175 | " -dx12 Use DX12 API (default)\n" 176 | " -vk Use Vulkan API\n" 177 | " --list-adapters Enumerate the graphics adapters present in the system\n" 178 | " --adapter Use graphics adapter with index as reported by --list-adapters\n", 179 | argv[0]); 180 | return 0; 181 | } 182 | if (strcmp(argv[i], "--list-adapters") == 0) 183 | { 184 | if (!deviceManager->CreateInstance(deviceParams)) 185 | { 186 | log::error("Cannot initialize a %s subsystem.", nvrhi::utils::GraphicsAPIToString(api)); 187 | return 1; 188 | } 189 | 190 | std::vector adapters; 191 | if (!deviceManager->EnumerateAdapters(adapters)) 192 | { 193 | log::error("Cannot enumerate graphics adapters."); 194 | return 1; 195 | } 196 | 197 | for (int adapterIndex = 0; adapterIndex < int(adapters.size()); ++adapterIndex) 198 | { 199 | auto const& info = adapters[adapterIndex]; 200 | int deviceMemoryMB = int(info.dedicatedVideoMemory / (1024 * 1024)); 201 | printf("Adapter %d: %s (%d MB VRAM)\n", adapterIndex, info.name.c_str(), deviceMemoryMB); 202 | } 203 | return 0; 204 | } 205 | else if (strcmp(argv[i], "--adapter") == 0) 206 | { 207 | if (i + 1 >= argc) 208 | { 209 | log::error("--device requires a parameter"); 210 | return 1; 211 | } 212 | deviceParams.adapterIndex = atoi(argv[i + 1]); 213 | ++i; 214 | } 215 | } 216 | 217 | if (!deviceManager->CreateHeadlessDevice(deviceParams)) 218 | { 219 | log::error("Cannot initialize a graphics device with the requested parameters"); 220 | return 1; 221 | } 222 | 223 | printf("Using %s API with %s.\n", nvrhi::utils::GraphicsAPIToString(api), deviceManager->GetRendererString()); 224 | 225 | if (!RunTest(deviceManager->GetDevice())) 226 | return 1; 227 | 228 | deviceManager->Shutdown(); 229 | 230 | return 0; 231 | } 232 | -------------------------------------------------------------------------------- /examples/headless/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T cs 2 | -------------------------------------------------------------------------------- /examples/headless/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | Buffer t_Input : register(t0); 24 | RWBuffer u_Output : register(u0); 25 | 26 | static const uint GroupSize = 256; 27 | 28 | groupshared uint s_ReductionData[GroupSize/2]; 29 | 30 | [numthreads(GroupSize, 1, 1)] 31 | void main(uint threadIdx : SV_GroupThreadID) 32 | { 33 | uint data = t_Input[threadIdx]; 34 | 35 | // Simple parallel reduction implementation. 36 | // Process the data using groups of threads of reducing size. 37 | // Note: there is a faster way of doing group-wide reduction using wave intrinsics. 38 | for (uint size = GroupSize/2; size >= 1; size >>= 1) 39 | { 40 | // Upper half of the current group stores its data into the shared buffer 41 | if (size <= threadIdx && threadIdx < size * 2) 42 | s_ReductionData[threadIdx - size] = data; 43 | 44 | GroupMemoryBarrierWithGroupSync(); 45 | 46 | // Lower half of the current group loads the data from the shared buffer and adds it to the accumulator 47 | if (threadIdx < size) 48 | data += s_ReductionData[threadIdx]; 49 | 50 | GroupMemoryBarrierWithGroupSync(); 51 | 52 | // Repeat with a smaller group... 53 | } 54 | 55 | if (threadIdx == 0) 56 | u_Output[0] = data; 57 | } -------------------------------------------------------------------------------- /examples/meshlets/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project meshlets) 28 | set(folder "Examples/Meshlets") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Meshlets" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 36 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 37 | SHADERMAKE_OPTIONS_SPIRV "--spirvExt SPV_NV_mesh_shader") 38 | 39 | add_executable(${project} WIN32 ${sources}) 40 | target_link_libraries(${project} donut_app donut_engine) 41 | add_dependencies(${project} ${project}_shaders) 42 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 43 | 44 | if (MSVC) 45 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 46 | endif() 47 | -------------------------------------------------------------------------------- /examples/meshlets/meshlets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | using namespace donut; 31 | 32 | static const char* g_WindowTitle = "Donut Example: Meshlets"; 33 | 34 | class MeshletExample : public app::IRenderPass 35 | { 36 | private: 37 | nvrhi::ShaderHandle m_AmplificationShader; 38 | nvrhi::ShaderHandle m_MeshShader; 39 | nvrhi::ShaderHandle m_PixelShader; 40 | nvrhi::MeshletPipelineHandle m_Pipeline; 41 | nvrhi::CommandListHandle m_CommandList; 42 | 43 | public: 44 | using IRenderPass::IRenderPass; 45 | 46 | bool Init() 47 | { 48 | auto nativeFS = std::make_shared(); 49 | 50 | std::filesystem::path appShaderPath = app::GetDirectoryWithExecutable() / "shaders/meshlets" / app::GetShaderTypeName(GetDevice()->getGraphicsAPI()); 51 | 52 | engine::ShaderFactory shaderFactory(GetDevice(), nativeFS, appShaderPath); 53 | m_AmplificationShader = shaderFactory.CreateShader("shaders.hlsl", "main_as", nullptr, nvrhi::ShaderType::Amplification); 54 | m_MeshShader = shaderFactory.CreateShader("shaders.hlsl", "main_ms", nullptr, nvrhi::ShaderType::Mesh); 55 | m_PixelShader = shaderFactory.CreateShader("shaders.hlsl", "main_ps", nullptr, nvrhi::ShaderType::Pixel); 56 | 57 | if (!m_AmplificationShader || !m_MeshShader || !m_PixelShader) 58 | { 59 | return false; 60 | } 61 | 62 | m_CommandList = GetDevice()->createCommandList(); 63 | 64 | return true; 65 | } 66 | 67 | void Animate(float fElapsedTimeSeconds) override 68 | { 69 | GetDeviceManager()->SetInformativeWindowTitle(g_WindowTitle); 70 | } 71 | 72 | void BackBufferResizing() override 73 | { 74 | m_Pipeline = nullptr; 75 | } 76 | 77 | void Render(nvrhi::IFramebuffer* framebuffer) override 78 | { 79 | if (!m_Pipeline) 80 | { 81 | nvrhi::MeshletPipelineDesc psoDesc; 82 | psoDesc.AS = m_AmplificationShader; 83 | psoDesc.MS = m_MeshShader; 84 | psoDesc.PS = m_PixelShader; 85 | psoDesc.primType = nvrhi::PrimitiveType::TriangleList; 86 | psoDesc.renderState.depthStencilState.depthTestEnable = false; 87 | 88 | m_Pipeline = GetDevice()->createMeshletPipeline(psoDesc, framebuffer); 89 | } 90 | 91 | m_CommandList->open(); 92 | 93 | nvrhi::utils::ClearColorAttachment(m_CommandList, framebuffer, 0, nvrhi::Color(0.f)); 94 | 95 | nvrhi::MeshletState state; 96 | state.pipeline = m_Pipeline; 97 | state.framebuffer = framebuffer; 98 | state.viewport.addViewportAndScissorRect(framebuffer->getFramebufferInfo().getViewport()); 99 | 100 | m_CommandList->setMeshletState(state); 101 | 102 | m_CommandList->dispatchMesh(1); 103 | 104 | m_CommandList->close(); 105 | GetDevice()->executeCommandList(m_CommandList); 106 | } 107 | 108 | }; 109 | 110 | #ifdef WIN32 111 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 112 | #else 113 | int main(int __argc, const char** __argv) 114 | #endif 115 | { 116 | nvrhi::GraphicsAPI api = app::GetGraphicsAPIFromCommandLine(__argc, __argv); 117 | app::DeviceManager* deviceManager = app::DeviceManager::Create(api); 118 | 119 | app::DeviceCreationParameters deviceParams; 120 | #ifdef _DEBUG 121 | deviceParams.enableDebugRuntime = true; 122 | deviceParams.enableNvrhiValidationLayer = true; 123 | #endif 124 | 125 | if (!deviceManager->CreateWindowDeviceAndSwapChain(deviceParams, g_WindowTitle)) 126 | { 127 | log::fatal("Cannot initialize a graphics device with the requested parameters"); 128 | return 1; 129 | } 130 | 131 | if (!deviceManager->GetDevice()->queryFeatureSupport(nvrhi::Feature::Meshlets)) 132 | { 133 | log::fatal("The graphics device does not support Meshlets"); 134 | return 1; 135 | } 136 | 137 | { 138 | MeshletExample example(deviceManager); 139 | if (example.Init()) 140 | { 141 | deviceManager->AddRenderPassToBack(&example); 142 | deviceManager->RunMessageLoop(); 143 | deviceManager->RemoveRenderPass(&example); 144 | } 145 | } 146 | 147 | deviceManager->Shutdown(); 148 | 149 | delete deviceManager; 150 | 151 | return 0; 152 | } 153 | -------------------------------------------------------------------------------- /examples/meshlets/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T as -E main_as 2 | shaders.hlsl -T ms -E main_ms 3 | shaders.hlsl -T ps -E main_ps 4 | -------------------------------------------------------------------------------- /examples/meshlets/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #define MAX_PRIMS_PER_MESHLET 1 24 | #define MAX_VERTICES_PER_MESHLET 3 25 | 26 | static const float2 g_positions[] = { 27 | float2(-0.5, -0.5), 28 | float2(0, 0.5), 29 | float2(0.5, -0.5) 30 | }; 31 | 32 | static const float3 g_colors[] = { 33 | float3(1, 0, 0), 34 | float3(0, 1, 0), 35 | float3(0, 0, 1) 36 | }; 37 | 38 | struct Payload 39 | { 40 | int dummy; 41 | }; 42 | 43 | struct Vertex 44 | { 45 | float4 pos : SV_Position; 46 | float3 color : COLOR; 47 | }; 48 | 49 | groupshared Payload s_payload; 50 | 51 | [numthreads(1, 1, 1)] 52 | void main_as( 53 | uint globalIdx : SV_DispatchThreadID) 54 | { 55 | s_payload.dummy = 0; 56 | DispatchMesh(1, 1, 1, s_payload); 57 | } 58 | 59 | [numthreads(1,1,1)] 60 | [outputtopology("triangle")] 61 | void main_ms( 62 | uint threadId : SV_GroupThreadID, 63 | in payload Payload i_payload, 64 | out indices uint3 o_tris[MAX_PRIMS_PER_MESHLET], 65 | out vertices Vertex o_verts[MAX_VERTICES_PER_MESHLET]) 66 | { 67 | SetMeshOutputCounts(3, 1); 68 | o_tris[0] = uint3(0, 1, 2); 69 | 70 | for (uint i = 0; i < 3; i++) 71 | { 72 | o_verts[i].pos = float4(g_positions[i], 0, 1); 73 | o_verts[i].color = g_colors[i]; 74 | } 75 | } 76 | 77 | 78 | void main_ps( 79 | in Vertex i_vertex, 80 | out float4 o_color : SV_Target0 81 | ) 82 | { 83 | o_color = float4(i_vertex.color, 1); 84 | } 85 | -------------------------------------------------------------------------------- /examples/rt_bindless/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project rt_bindless) 28 | set(folder "Examples/Bindless Ray Tracing") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Bindless Ray Tracing" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_render donut_app donut_engine) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | -------------------------------------------------------------------------------- /examples/rt_bindless/lighting_cb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef LIGHTING_CB_H 24 | #define LIGHTING_CB_H 25 | 26 | #include 27 | #include 28 | 29 | struct LightingConstants 30 | { 31 | float4 ambientColor; 32 | 33 | LightConstants light; 34 | PlanarViewConstants view; 35 | }; 36 | 37 | #endif // LIGHTING_CB_H -------------------------------------------------------------------------------- /examples/rt_bindless/shaders.cfg: -------------------------------------------------------------------------------- 1 | rt_bindless.hlsl -T lib -D USE_RAY_QUERY=0 2 | rt_bindless.hlsl -T cs -D USE_RAY_QUERY=1 3 | -------------------------------------------------------------------------------- /examples/rt_particles/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2022, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl" "*.hlsli") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project rt_particles) 28 | set(folder "Examples/Ray Traced Particles") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Ray Traced Particles" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_render donut_app donut_engine) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | -------------------------------------------------------------------------------- /examples/rt_particles/mlab.hlsli: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | // This file implements the Multi-Layer Alpha Blending (MLAB) algorithm. 24 | // See M. Salvi, K. Vaidyanathan: "Multi-Layer Alpha Blending". 25 | 26 | #ifndef MLAB_FRAGMENTS 27 | #define MLAB_FRAGMENTS 4 28 | #endif 29 | 30 | struct BlendFragment 31 | { 32 | float3 color; 33 | float attenuation; 34 | float depth; 35 | }; 36 | 37 | // Initializes the blending array with empty fragments. 38 | void blendInit(inout BlendFragment buffer[MLAB_FRAGMENTS]) 39 | { 40 | BlendFragment f; 41 | f.color = 0; 42 | f.attenuation = 1; 43 | f.depth = 1.#INF; 44 | 45 | for (int i = 0; i < MLAB_FRAGMENTS; ++i) 46 | { 47 | buffer[i] = f; 48 | } 49 | } 50 | 51 | // Inserts the new fragment f into the blending array. 52 | // Based on Listing 1 in the paper, with one bug fix. 53 | void blendInsert(BlendFragment f, inout BlendFragment buffer[MLAB_FRAGMENTS]) 54 | { 55 | // 1-pass bubble sort to insert fragment 56 | BlendFragment temp; 57 | for (int i = 0; i < MLAB_FRAGMENTS; ++i) 58 | { 59 | if (f.depth < buffer[i].depth) 60 | { 61 | temp = buffer[i]; 62 | buffer[i] = f; 63 | f = temp; 64 | } 65 | } 66 | 67 | // Compression (merge last two rows) 68 | BlendFragment last = buffer[MLAB_FRAGMENTS-1]; 69 | BlendFragment merged; 70 | merged.color = last.color + f.color * last.attenuation; 71 | merged.attenuation = last.attenuation * f.attenuation; 72 | merged.depth = last.depth; 73 | buffer[MLAB_FRAGMENTS-1] = merged; 74 | } 75 | 76 | // Integrates all fragments in the blending array into one fragment. 77 | BlendFragment blendIntegrate(BlendFragment buffer[MLAB_FRAGMENTS]) 78 | { 79 | BlendFragment result = buffer[0]; 80 | 81 | for (int i = 1; i < MLAB_FRAGMENTS; ++i) 82 | { 83 | BlendFragment f = buffer[i]; 84 | result.color += f.color * result.attenuation; 85 | result.attenuation *= f.attenuation; 86 | } 87 | 88 | return result; 89 | } 90 | -------------------------------------------------------------------------------- /examples/rt_particles/rt_particles_cb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2022, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef PARTICLES_CB_H 24 | #define PARTICLES_CB_H 25 | 26 | #include 27 | 28 | struct GlobalConstants 29 | { 30 | PlanarViewConstants view; 31 | 32 | float primaryRayConeAngle; 33 | uint reorientParticlesInPrimaryRays; 34 | uint reorientParticlesInSecondaryRays; 35 | uint orientationMode; 36 | 37 | int environmentMapTextureIndex; 38 | }; 39 | 40 | struct ParticleInfo 41 | { 42 | float3 center; 43 | float rotation; 44 | 45 | float3 xAxis; 46 | float inverseRadius; 47 | 48 | float3 yAxis; 49 | int textureIndex; 50 | 51 | float3 colorFactor; 52 | float opacityFactor; 53 | }; 54 | 55 | #define INSTANCE_MASK_OPAQUE 1 56 | #define INSTANCE_MASK_PARTICLE_GEOMETRY 2 57 | #define INSTANCE_MASK_INTERSECTION_PARTICLE 4 58 | 59 | #define ORIENTATION_MODE_AVT_MATRIX 0 60 | #define ORIENTATION_MODE_QUATERNION 1 61 | #define ORIENTATION_MODE_BEAM 2 62 | #define ORIENTATION_MODE_BASIS 3 63 | 64 | #endif // PARTICLES_CB_H 65 | -------------------------------------------------------------------------------- /examples/rt_particles/shaders.cfg: -------------------------------------------------------------------------------- 1 | rt_particles.hlsl -T cs -D MLAB_FRAGMENTS={1,2,4,8} -------------------------------------------------------------------------------- /examples/rt_particles/utils.hlsli: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2023, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | struct RayHitInfo 24 | { 25 | float hitT; 26 | uint instanceID; 27 | uint primitiveIndex; 28 | uint geometryIndex; 29 | float2 barycentrics; 30 | }; 31 | 32 | static const uint c_MissInstanceID = ~0u; 33 | 34 | // Constructor to make RayHitInfo from a committed hit on a RayQuery. 35 | // Can't make it a function because RayQuery is a template. 36 | #define RAY_QUERY_COMMITTED_HIT(hitInfo, rayQuery) \ 37 | hitInfo.instanceID = rayQuery.CommittedInstanceID(); \ 38 | hitInfo.primitiveIndex = rayQuery.CommittedPrimitiveIndex(); \ 39 | hitInfo.geometryIndex = rayQuery.CommittedGeometryIndex(); \ 40 | hitInfo.barycentrics = rayQuery.CommittedTriangleBarycentrics(); \ 41 | hitInfo.hitT = rayQuery.CommittedRayT(); 42 | 43 | // Constructor to make RayHitInfo from a candidate hit on a RayQuery. 44 | #define RAY_QUERY_CANDIDATE_HIT(hitInfo, rayQuery) \ 45 | hitInfo.instanceID = rayQuery.CandidateInstanceID(); \ 46 | hitInfo.primitiveIndex = rayQuery.CandidatePrimitiveIndex(); \ 47 | hitInfo.geometryIndex = rayQuery.CandidateGeometryIndex(); \ 48 | hitInfo.barycentrics = rayQuery.CandidateTriangleBarycentrics(); \ 49 | hitInfo.hitT = rayQuery.CandidateTriangleRayT(); 50 | 51 | RayDesc setupPrimaryRay(uint2 pixelPosition, PlanarViewConstants view) 52 | { 53 | float2 uv = (float2(pixelPosition) + 0.5) * view.viewportSizeInv; 54 | float4 clipPos = float4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.5, 1); 55 | float4 worldPos = mul(clipPos, view.matClipToWorld); 56 | worldPos.xyz /= worldPos.w; 57 | 58 | RayDesc ray; 59 | ray.Origin = view.cameraDirectionOrPosition.xyz; 60 | ray.Direction = normalize(worldPos.xyz - ray.Origin); 61 | ray.TMin = 0; 62 | ray.TMax = 1000; 63 | return ray; 64 | } 65 | 66 | // Calculates the quaternion which transforms the normalized vector src to normalized vector dst 67 | // Note: returns a zero quat if src == -dst, case when dot(src, dst) == -1 needs to be handled if this is expected. 68 | float4 quaternionCreateOrientation(float3 src, float3 dst) 69 | { 70 | // https://stackoverflow.com/questions/1171849/finding-quaternion-representing-the-rotation-from-one-vector-to-another 71 | float4 q; 72 | q.xyz = cross(src, dst); 73 | q.w = 1.0 + dot(src, dst); 74 | 75 | // Normalize the quaternion 76 | float len = length(q); 77 | q = (len > 0) ? q / len : float4(1.0, 0.0, 0.0, 0.0); 78 | 79 | return q; 80 | } 81 | 82 | // Transform a vector v with a quaternion q, v doesn't need to be normalized 83 | float3 quaternionTransformVector(float4 q, float3 v) 84 | { 85 | return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v); 86 | } 87 | 88 | // Converts a unit direction vector into texture coordinates for sampling a lat-long environment map 89 | float2 directionToEquirectUV(float3 normalizedDirection) 90 | { 91 | float elevation = asin(normalizedDirection.y); 92 | float azimuth = 0; 93 | if (abs(normalizedDirection.y) < 1.0) 94 | azimuth = atan2(normalizedDirection.z, normalizedDirection.x); 95 | 96 | const float c_pi = 3.1415926535; 97 | float2 uv; 98 | uv.x = azimuth / (2 * c_pi) - 0.25; 99 | uv.y = 0.5 - elevation / c_pi; 100 | 101 | return uv; 102 | } 103 | -------------------------------------------------------------------------------- /examples/rt_reflections/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project rt_reflections) 28 | set(folder "Examples/Ray Traced Reflections") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Ray Traced Reflections" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | ) 38 | 39 | add_executable(${project} WIN32 ${sources}) 40 | target_link_libraries(${project} donut_render donut_app donut_engine) 41 | add_dependencies(${project} ${project}_shaders) 42 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 43 | -------------------------------------------------------------------------------- /examples/rt_reflections/lighting_cb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef LIGHTING_CB_H 24 | #define LIGHTING_CB_H 25 | 26 | #include 27 | #include 28 | 29 | #define REFLECTIONS_SPACE_GLOBAL 0 30 | #define REFLECTIONS_BINDING_MATERIAL_SAMPLER 0 31 | #define REFLECTIONS_BINDING_LIGHTING_CONSTANTS 0 32 | #define REFLECTIONS_BINDING_OUTPUT_UAV 0 33 | #define REFLECTIONS_BINDING_SCENE_BVH 0 34 | #define REFLECTIONS_BINDING_GBUFFER_DEPTH_TEXTURE 1 35 | #define REFLECTIONS_BINDING_GBUFFER_0_TEXTURE 2 36 | #define REFLECTIONS_BINDING_GBUFFER_1_TEXTURE 3 37 | #define REFLECTIONS_BINDING_GBUFFER_2_TEXTURE 4 38 | #define REFLECTIONS_BINDING_GBUFFER_3_TEXTURE 5 39 | 40 | #define REFLECTIONS_SPACE_LOCAL 1 41 | #define REFLECTIONS_BINDING_MATERIAL_CONSTANTS 0 42 | #define REFLECTIONS_BINDING_INDEX_BUFFER 0 43 | #define REFLECTIONS_BINDING_TEX_COORD_BUFFER 1 44 | #define REFLECTIONS_BINDING_NORMAL_BUFFER 2 45 | #define REFLECTIONS_BINDING_DIFFUSE_TEXTURE 3 46 | #define REFLECTIONS_BINDING_SPECULAR_TEXTURE 4 47 | #define REFLECTIONS_BINDING_NORMAL_TEXTURE 5 48 | #define REFLECTIONS_BINDING_EMISSIVE_TEXTURE 6 49 | #define REFLECTIONS_BINDING_OCCLUSION_TEXTURE 7 50 | #define REFLECTIONS_BINDING_TRANSMISSION_TEXTURE 8 51 | #define REFLECTIONS_BINDING_OPACITY_TEXTURE 9 52 | 53 | struct LightingConstants 54 | { 55 | float4 ambientColor; 56 | 57 | LightConstants light; 58 | PlanarViewConstants view; 59 | }; 60 | 61 | #endif // LIGHTING_CB_H -------------------------------------------------------------------------------- /examples/rt_reflections/rt_reflections.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #pragma pack_matrix(row_major) 24 | 25 | #include "lighting_cb.h" 26 | 27 | // Declare the binding slots for 'material_bindings.hlsli' 28 | 29 | #define MATERIAL_REGISTER_SPACE REFLECTIONS_SPACE_LOCAL 30 | #define MATERIAL_CB_SLOT REFLECTIONS_BINDING_MATERIAL_CONSTANTS 31 | #define MATERIAL_DIFFUSE_SLOT REFLECTIONS_BINDING_DIFFUSE_TEXTURE 32 | #define MATERIAL_SPECULAR_SLOT REFLECTIONS_BINDING_SPECULAR_TEXTURE 33 | #define MATERIAL_NORMALS_SLOT REFLECTIONS_BINDING_NORMAL_TEXTURE 34 | #define MATERIAL_EMISSIVE_SLOT REFLECTIONS_BINDING_EMISSIVE_TEXTURE 35 | #define MATERIAL_OCCLUSION_SLOT REFLECTIONS_BINDING_OCCLUSION_TEXTURE 36 | #define MATERIAL_TRANSMISSION_SLOT REFLECTIONS_BINDING_TRANSMISSION_TEXTURE 37 | #define MATERIAL_OPACITY_SLOT REFLECTIONS_BINDING_OPACITY_TEXTURE 38 | 39 | #define MATERIAL_SAMPLER_REGISTER_SPACE REFLECTIONS_SPACE_GLOBAL 40 | #define MATERIAL_SAMPLER_SLOT REFLECTIONS_BINDING_MATERIAL_SAMPLER 41 | 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | 48 | // ---[ Structures ]--- 49 | 50 | struct ShadowHitInfo 51 | { 52 | bool missed; 53 | }; 54 | 55 | struct ReflectionHitInfo 56 | { 57 | float3 color; 58 | }; 59 | 60 | struct Attributes 61 | { 62 | float2 uv; 63 | }; 64 | 65 | // ---[ Resources ]--- 66 | 67 | ConstantBuffer g_Lighting : REGISTER_CBUFFER(REFLECTIONS_BINDING_LIGHTING_CONSTANTS, REFLECTIONS_SPACE_GLOBAL); 68 | RWTexture2D u_Output : REGISTER_UAV(REFLECTIONS_BINDING_OUTPUT_UAV, REFLECTIONS_SPACE_GLOBAL); 69 | RaytracingAccelerationStructure SceneBVH : REGISTER_SRV(REFLECTIONS_BINDING_SCENE_BVH, REFLECTIONS_SPACE_GLOBAL); 70 | Texture2D t_GBufferDepth : REGISTER_SRV(REFLECTIONS_BINDING_GBUFFER_DEPTH_TEXTURE, REFLECTIONS_SPACE_GLOBAL); 71 | Texture2D t_GBuffer0 : REGISTER_SRV(REFLECTIONS_BINDING_GBUFFER_0_TEXTURE, REFLECTIONS_SPACE_GLOBAL); 72 | Texture2D t_GBuffer1 : REGISTER_SRV(REFLECTIONS_BINDING_GBUFFER_1_TEXTURE, REFLECTIONS_SPACE_GLOBAL); 73 | Texture2D t_GBuffer2 : REGISTER_SRV(REFLECTIONS_BINDING_GBUFFER_2_TEXTURE, REFLECTIONS_SPACE_GLOBAL); 74 | Texture2D t_GBuffer3 : REGISTER_SRV(REFLECTIONS_BINDING_GBUFFER_3_TEXTURE, REFLECTIONS_SPACE_GLOBAL); 75 | 76 | // ---[ Ray Generation Shader ]--- 77 | 78 | float GetShadow(float3 worldPos, float3 lightDirection) 79 | { 80 | // Setup the ray 81 | RayDesc ray; 82 | ray.Origin = worldPos; 83 | ray.Direction = -normalize(lightDirection); 84 | ray.TMin = 0.01f; 85 | ray.TMax = 100.f; 86 | 87 | // Trace the ray 88 | ShadowHitInfo shadowPayload; 89 | shadowPayload.missed = false; 90 | 91 | TraceRay( 92 | SceneBVH, 93 | RAY_FLAG_CULL_BACK_FACING_TRIANGLES, 94 | 0xFF, // InstanceInclusionMask 95 | 0, // RayContributionToHitGroupIndex 96 | 2, // MultiplierForGeometryContributionToHitGroupIndex 97 | 0, // MissShaderIndex 98 | ray, 99 | shadowPayload); 100 | 101 | return (shadowPayload.missed) ? 1 : 0; 102 | } 103 | 104 | float3 GetReflection(float3 worldPos, float3 reflectedVector) 105 | { 106 | // Setup the ray 107 | RayDesc ray; 108 | ray.Origin = worldPos; 109 | ray.Direction = normalize(reflectedVector); 110 | ray.TMin = 0.01f; 111 | ray.TMax = 100.f; 112 | 113 | // Trace the ray 114 | ReflectionHitInfo reflectionPayload; 115 | reflectionPayload.color = 0; 116 | 117 | TraceRay( 118 | SceneBVH, 119 | RAY_FLAG_CULL_BACK_FACING_TRIANGLES, 120 | 0xFF, // InstanceInclusionMask 121 | 1, // RayContributionToHitGroupIndex 122 | 2, // MultiplierForGeometryContributionToHitGroupIndex 123 | 1, // MissShaderIndex 124 | ray, 125 | reflectionPayload); 126 | 127 | return reflectionPayload.color; 128 | } 129 | 130 | [shader("raygeneration")] 131 | void RayGen() 132 | { 133 | uint2 globalIdx = DispatchRaysIndex().xy; 134 | float2 pixelPosition = float2(globalIdx) + 0.5; 135 | 136 | MaterialSample surfaceMaterial = DecodeGBuffer(globalIdx, t_GBuffer0, t_GBuffer1, t_GBuffer2, t_GBuffer3); 137 | 138 | float3 surfaceWorldPos = ReconstructWorldPosition(g_Lighting.view, pixelPosition.xy, t_GBufferDepth[pixelPosition.xy].x); 139 | 140 | float3 viewIncident = GetIncidentVector(g_Lighting.view.cameraDirectionOrPosition, surfaceWorldPos); 141 | 142 | float3 diffuseTerm = 0; 143 | float3 specularTerm = 0; 144 | 145 | if (any(surfaceMaterial.shadingNormal != 0)) 146 | { 147 | float shadow = GetShadow(surfaceWorldPos, g_Lighting.light.direction); 148 | 149 | if (shadow > 0) 150 | { 151 | float3 diffuseRadiance, specularRadiance; 152 | ShadeSurface(g_Lighting.light, surfaceMaterial, surfaceWorldPos, viewIncident, diffuseRadiance, specularRadiance); 153 | 154 | diffuseTerm += (shadow * diffuseRadiance) * g_Lighting.light.color; 155 | specularTerm += (shadow * specularRadiance) * g_Lighting.light.color; 156 | } 157 | 158 | diffuseTerm += g_Lighting.ambientColor.rgb * surfaceMaterial.diffuseAlbedo; 159 | 160 | float3 reflection = GetReflection(surfaceWorldPos, reflect(viewIncident, surfaceMaterial.shadingNormal)); 161 | float3 fresnel = Schlick_Fresnel(surfaceMaterial.specularF0, saturate(-dot(viewIncident, surfaceMaterial.shadingNormal))); 162 | specularTerm += reflection * fresnel; 163 | } 164 | 165 | float3 outputColor = diffuseTerm 166 | + specularTerm 167 | + surfaceMaterial.emissiveColor; 168 | 169 | u_Output[globalIdx] = float4(outputColor, 1); 170 | } 171 | 172 | // ---[ Shadow Miss Shader ]--- 173 | 174 | [shader("miss")] 175 | void ShadowMiss(inout ShadowHitInfo shadowPayload : SV_RayPayload) 176 | { 177 | shadowPayload.missed = true; 178 | } 179 | 180 | // ---[ Reflection Shaders ]--- 181 | 182 | Buffer t_MeshIndexBuffer : REGISTER_SRV(REFLECTIONS_BINDING_INDEX_BUFFER, REFLECTIONS_SPACE_LOCAL); 183 | Buffer t_MeshTexCoordBuffer : REGISTER_SRV(REFLECTIONS_BINDING_TEX_COORD_BUFFER, REFLECTIONS_SPACE_LOCAL); 184 | Buffer t_MeshNormalsBuffer : REGISTER_SRV(REFLECTIONS_BINDING_NORMAL_BUFFER, REFLECTIONS_SPACE_LOCAL); 185 | 186 | [shader("miss")] 187 | void ReflectionMiss(inout ReflectionHitInfo reflectionPayload : SV_RayPayload) 188 | { 189 | } 190 | 191 | [shader("closesthit")] 192 | void ReflectionClosestHit(inout ReflectionHitInfo reflectionPayload : SV_RayPayload, in Attributes attrib : SV_IntersectionAttributes) 193 | { 194 | uint triangleIndex = PrimitiveIndex(); 195 | float3 barycentrics = float3((1.0f - attrib.uv.x - attrib.uv.y), attrib.uv.x, attrib.uv.y); 196 | 197 | uint3 indices; 198 | indices.x = t_MeshIndexBuffer[triangleIndex * 3 + 0]; 199 | indices.y = t_MeshIndexBuffer[triangleIndex * 3 + 1]; 200 | indices.z = t_MeshIndexBuffer[triangleIndex * 3 + 2]; 201 | 202 | float2 vertexUVs[3]; 203 | vertexUVs[0] = t_MeshTexCoordBuffer[indices.x]; 204 | vertexUVs[1] = t_MeshTexCoordBuffer[indices.y]; 205 | vertexUVs[2] = t_MeshTexCoordBuffer[indices.z]; 206 | 207 | float3 vertexNormals[3]; 208 | vertexNormals[0] = t_MeshNormalsBuffer[indices.x].xyz; 209 | vertexNormals[1] = t_MeshNormalsBuffer[indices.y].xyz; 210 | vertexNormals[2] = t_MeshNormalsBuffer[indices.z].xyz; 211 | 212 | float2 uv = 213 | vertexUVs[0] * barycentrics.x + 214 | vertexUVs[1] * barycentrics.y + 215 | vertexUVs[2] * barycentrics.z; 216 | 217 | float3 normal = normalize( 218 | vertexNormals[0] * barycentrics.x + 219 | vertexNormals[1] * barycentrics.y + 220 | vertexNormals[2] * barycentrics.z); 221 | 222 | 223 | MaterialTextureSample textures = SampleMaterialTexturesLevel(uv, 3); 224 | 225 | MaterialSample surfaceMaterial = EvaluateSceneMaterial(normal, /* tangent = */ 0, g_Material, textures); 226 | 227 | float3 surfaceWorldPos = WorldRayOrigin() + WorldRayDirection() * RayTCurrent(); 228 | 229 | float3 diffuseRadiance, specularRadiance; 230 | float3 viewIncident = WorldRayDirection(); 231 | ShadeSurface(g_Lighting.light, surfaceMaterial, surfaceWorldPos, viewIncident, diffuseRadiance, specularRadiance); 232 | 233 | float3 diffuseTerm = 0; 234 | float3 specularTerm = 0; 235 | 236 | float shadow = GetShadow(surfaceWorldPos, g_Lighting.light.direction); 237 | diffuseTerm += (shadow * diffuseRadiance) * g_Lighting.light.color; 238 | specularTerm += (shadow * specularRadiance) * g_Lighting.light.color; 239 | 240 | diffuseTerm += g_Lighting.ambientColor.rgb * surfaceMaterial.diffuseAlbedo; 241 | 242 | reflectionPayload.color = diffuseTerm + specularTerm; 243 | } -------------------------------------------------------------------------------- /examples/rt_reflections/shaders.cfg: -------------------------------------------------------------------------------- 1 | rt_reflections.hlsl -T lib 2 | -------------------------------------------------------------------------------- /examples/rt_shadows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project rt_shadows) 28 | set(folder "Examples/Ray Traced Shadows") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Ray Traced Shadows" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_render donut_app donut_engine) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | -------------------------------------------------------------------------------- /examples/rt_shadows/lighting_cb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef LIGHTING_CB_H 24 | #define LIGHTING_CB_H 25 | 26 | #include 27 | #include 28 | 29 | struct LightingConstants 30 | { 31 | float4 ambientColor; 32 | 33 | LightConstants light; 34 | PlanarViewConstants view; 35 | }; 36 | 37 | #endif // LIGHTING_CB_H -------------------------------------------------------------------------------- /examples/rt_shadows/rt_shadows.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #pragma pack_matrix(row_major) 24 | 25 | #include 26 | #include 27 | #include "lighting_cb.h" 28 | 29 | // ---[ Structures ]--- 30 | 31 | struct HitInfo 32 | { 33 | bool missed; 34 | }; 35 | 36 | // ---[ Resources ]--- 37 | 38 | ConstantBuffer g_Lighting : register(b0); 39 | 40 | RWTexture2D u_Output : register(u0); 41 | 42 | RaytracingAccelerationStructure SceneBVH : register(t0); 43 | Texture2D t_GBufferDepth : register(t1); 44 | Texture2D t_GBuffer0 : register(t2); 45 | Texture2D t_GBuffer1 : register(t3); 46 | Texture2D t_GBuffer2 : register(t4); 47 | Texture2D t_GBuffer3 : register(t5); 48 | 49 | 50 | // ---[ Ray Generation Shader ]--- 51 | 52 | [shader("raygeneration")] 53 | void RayGen() 54 | { 55 | uint2 globalIdx = DispatchRaysIndex().xy; 56 | float2 pixelPosition = float2(globalIdx) + 0.5; 57 | 58 | MaterialSample surfaceMaterial = DecodeGBuffer(globalIdx, t_GBuffer0, t_GBuffer1, t_GBuffer2, t_GBuffer3); 59 | 60 | float3 surfaceWorldPos = ReconstructWorldPosition(g_Lighting.view, pixelPosition.xy, t_GBufferDepth[pixelPosition.xy].x); 61 | 62 | float3 viewIncident = GetIncidentVector(g_Lighting.view.cameraDirectionOrPosition, surfaceWorldPos); 63 | 64 | // Setup the ray 65 | RayDesc ray; 66 | ray.Origin = surfaceWorldPos; 67 | ray.Direction = -normalize(g_Lighting.light.direction); 68 | ray.TMin = 0.01f; 69 | ray.TMax = 100.f; 70 | 71 | // Trace the ray 72 | HitInfo payload; 73 | payload.missed = false; 74 | 75 | TraceRay( 76 | SceneBVH, 77 | RAY_FLAG_CULL_BACK_FACING_TRIANGLES, 78 | 0xFF, 79 | 0, 80 | 0, 81 | 0, 82 | ray, 83 | payload); 84 | 85 | float shadow = (payload.missed) ? 1 : 0; 86 | 87 | float3 diffuseTerm = 0; 88 | float3 specularTerm = 0; 89 | 90 | float3 diffuseRadiance, specularRadiance; 91 | ShadeSurface(g_Lighting.light, surfaceMaterial, surfaceWorldPos, viewIncident, diffuseRadiance, specularRadiance); 92 | 93 | diffuseTerm += (shadow * diffuseRadiance) * g_Lighting.light.color; 94 | specularTerm += (shadow * specularRadiance) * g_Lighting.light.color; 95 | 96 | diffuseTerm += g_Lighting.ambientColor.rgb * surfaceMaterial.diffuseAlbedo; 97 | 98 | float3 outputColor = diffuseTerm 99 | + specularTerm 100 | + surfaceMaterial.emissiveColor; 101 | 102 | u_Output[globalIdx] = float4(outputColor, 1); 103 | } 104 | 105 | // ---[ Miss Shader ]--- 106 | 107 | [shader("miss")] 108 | void Miss(inout HitInfo payload : SV_RayPayload) 109 | { 110 | payload.missed = true; 111 | } 112 | -------------------------------------------------------------------------------- /examples/rt_shadows/shaders.cfg: -------------------------------------------------------------------------------- 1 | rt_shadows.hlsl -T lib 2 | -------------------------------------------------------------------------------- /examples/rt_triangle/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project rt_triangle) 28 | set(folder "Examples/Ray Traced Triangle") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Ray Traced Triangle" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_app donut_engine) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | -------------------------------------------------------------------------------- /examples/rt_triangle/rt_triangle.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | // ---[ Structures ]--- 24 | 25 | struct HitInfo 26 | { 27 | float4 ShadedColorAndHitT : SHADED_COLOR_AND_HIT_T; 28 | }; 29 | 30 | struct Attributes { 31 | float2 uv; 32 | }; 33 | 34 | // ---[ Constant Buffers ]--- 35 | 36 | // ---[ Resources ]--- 37 | 38 | RWTexture2D RTOutput : register(u0); 39 | RaytracingAccelerationStructure SceneBVH : register(t0); 40 | 41 | 42 | // ---[ Ray Generation Shader ]--- 43 | 44 | [shader("raygeneration")] 45 | void RayGen() 46 | { 47 | uint2 LaunchIndex = DispatchRaysIndex().xy; 48 | uint2 LaunchDimensions = DispatchRaysDimensions().xy; 49 | 50 | // Setup the ray 51 | RayDesc ray; 52 | ray.Origin = float3( 53 | lerp(-1, 1, float(LaunchIndex.x) / float(LaunchDimensions.x)), 54 | lerp(-1, 1, float(LaunchIndex.y) / float(LaunchDimensions.y)), 55 | 0); 56 | ray.Direction = float3(0, 0, 1); 57 | ray.TMin = 0.1f; 58 | ray.TMax = 1000.f; 59 | 60 | // Trace the ray 61 | HitInfo payload; 62 | payload.ShadedColorAndHitT = float4(1, 0, 0, 0); 63 | 64 | TraceRay( 65 | SceneBVH, 66 | RAY_FLAG_NONE, 67 | 0xFF, 68 | 0, 69 | 0, 70 | 0, 71 | ray, 72 | payload); 73 | 74 | RTOutput[LaunchIndex.xy] = float4(payload.ShadedColorAndHitT.rgb, 1.f); 75 | //RTOutput[LaunchIndex.xy] = float4(ray.Origin.xyz, 1.f); 76 | } 77 | 78 | // ---[ Closest Hit Shader ]--- 79 | 80 | [shader("closesthit")] 81 | void ClosestHit(inout HitInfo payload : SV_RayPayload, 82 | Attributes attrib : SV_IntersectionAttributes) 83 | { 84 | float3 barycentrics = float3((1.0f - attrib.uv.x - attrib.uv.y), attrib.uv.x, attrib.uv.y); 85 | payload.ShadedColorAndHitT = float4(barycentrics, RayTCurrent()); 86 | } 87 | 88 | // ---[ Miss Shader ]--- 89 | 90 | [shader("miss")] 91 | void Miss(inout HitInfo payload : SV_RayPayload) 92 | { 93 | payload.ShadedColorAndHitT = float4(0.2f, 0.2f, 0.2f, -1.f); 94 | } 95 | -------------------------------------------------------------------------------- /examples/rt_triangle/shaders.cfg: -------------------------------------------------------------------------------- 1 | rt_triangle.hlsl -T lib 2 | -------------------------------------------------------------------------------- /examples/shader_specializations/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project shader_specializations) 28 | set(folder "Examples/Shader Specializations") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Shader Specializations" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 36 | SOURCES ${shaders} 37 | ) 38 | 39 | add_executable(${project} WIN32 ${sources}) 40 | target_link_libraries(${project} donut_app donut_engine) 41 | add_dependencies(${project} ${project}_shaders) 42 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 43 | 44 | if (MSVC) 45 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 46 | endif() 47 | -------------------------------------------------------------------------------- /examples/shader_specializations/shader_specializations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | using namespace donut; 31 | 32 | static const char* g_WindowTitle = "Donut Example: Vulkan Shader Specializations"; 33 | 34 | class ShaderSpecializations : public app::IRenderPass 35 | { 36 | private: 37 | nvrhi::ShaderHandle m_VertexShader; 38 | nvrhi::ShaderHandle m_PixelShader; 39 | std::vector m_Pipelines; 40 | nvrhi::CommandListHandle m_CommandList; 41 | 42 | public: 43 | using IRenderPass::IRenderPass; 44 | 45 | bool Init() 46 | { 47 | auto nativeFS = std::make_shared(); 48 | 49 | std::filesystem::path appShaderPath = app::GetDirectoryWithExecutable() / "shaders/shader_specializations" / app::GetShaderTypeName(GetDevice()->getGraphicsAPI()); 50 | 51 | engine::ShaderFactory shaderFactory(GetDevice(), nativeFS, appShaderPath); 52 | m_VertexShader = shaderFactory.CreateShader("shaders.hlsl", "main_vs", nullptr, nvrhi::ShaderType::Vertex); 53 | m_PixelShader = shaderFactory.CreateShader("shaders.hlsl", "main_ps", nullptr, nvrhi::ShaderType::Pixel); 54 | 55 | if (!m_VertexShader || !m_PixelShader) 56 | { 57 | return false; 58 | } 59 | 60 | m_CommandList = GetDevice()->createCommandList(); 61 | 62 | return true; 63 | } 64 | 65 | void Animate(float fElapsedTimeSeconds) override 66 | { 67 | GetDeviceManager()->SetInformativeWindowTitle(g_WindowTitle); 68 | } 69 | 70 | void BackBufferResizing() override 71 | { 72 | m_Pipelines.clear(); 73 | } 74 | 75 | void Render(nvrhi::IFramebuffer* framebuffer) override 76 | { 77 | if (m_Pipelines.empty()) 78 | { 79 | nvrhi::IDevice* device = GetDevice(); 80 | 81 | // Create pipelines with shader specializations. 82 | // The specializations could be created ahead of time, but they're cheap and it doesn't really matter. 83 | 84 | for (uint32_t i = 0; i < 4; i++) 85 | { 86 | // Vertex shader specialization 87 | nvrhi::ShaderSpecialization vertexShaderSpecializations[] = { 88 | nvrhi::ShaderSpecialization::Float( 0, float(i) * 0.5f - 0.75f) 89 | }; 90 | nvrhi::ShaderHandle vertexShader = device->createShaderSpecialization(m_VertexShader, 91 | vertexShaderSpecializations, uint32_t(std::size(vertexShaderSpecializations))); 92 | 93 | // Pixel shader specialization 94 | uint32_t colors[4] = { 0x0000ff, 0x00ff00, 0xff0000, 0xff00ff }; 95 | nvrhi::ShaderSpecialization pixelShaderSpecializations[] = { 96 | nvrhi::ShaderSpecialization::UInt32(1, colors[i]) 97 | }; 98 | nvrhi::ShaderHandle pixelShader = device->createShaderSpecialization(m_PixelShader, 99 | pixelShaderSpecializations, uint32_t(std::size(pixelShaderSpecializations))); 100 | 101 | // Pipeline 102 | nvrhi::GraphicsPipelineDesc psoDesc; 103 | psoDesc.VS = vertexShader; 104 | psoDesc.PS = pixelShader; 105 | psoDesc.primType = nvrhi::PrimitiveType::TriangleList; 106 | psoDesc.renderState.depthStencilState.depthTestEnable = false; 107 | 108 | nvrhi::GraphicsPipelineHandle pipeline = device->createGraphicsPipeline(psoDesc, framebuffer); 109 | assert(pipeline); 110 | 111 | m_Pipelines.push_back(pipeline); 112 | } 113 | } 114 | 115 | m_CommandList->open(); 116 | 117 | nvrhi::utils::ClearColorAttachment(m_CommandList, framebuffer, 0, nvrhi::Color(0.f)); 118 | 119 | // Render triangles, one with each pipeline. 120 | // Expected output: 4 triangles side-by-side; red, green, blue, cyan. 121 | 122 | for (const auto& pipeline : m_Pipelines) 123 | { 124 | nvrhi::GraphicsState state; 125 | state.pipeline = pipeline; 126 | state.framebuffer = framebuffer; 127 | state.viewport.addViewportAndScissorRect(framebuffer->getFramebufferInfo().getViewport()); 128 | 129 | m_CommandList->setGraphicsState(state); 130 | 131 | nvrhi::DrawArguments args; 132 | args.vertexCount = 3; 133 | m_CommandList->draw(args); 134 | } 135 | 136 | m_CommandList->close(); 137 | GetDevice()->executeCommandList(m_CommandList); 138 | } 139 | 140 | }; 141 | 142 | #ifdef WIN32 143 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 144 | #else 145 | int main(int __argc, const char** __argv) 146 | #endif 147 | { 148 | app::DeviceManager* deviceManager = app::DeviceManager::Create(nvrhi::GraphicsAPI::VULKAN); 149 | 150 | app::DeviceCreationParameters deviceParams; 151 | #ifdef _DEBUG 152 | deviceParams.enableDebugRuntime = true; 153 | deviceParams.enableNvrhiValidationLayer = true; 154 | #endif 155 | 156 | if (!deviceManager->CreateWindowDeviceAndSwapChain(deviceParams, g_WindowTitle)) 157 | { 158 | log::fatal("Cannot initialize a graphics device with the requested parameters"); 159 | return 1; 160 | } 161 | 162 | { 163 | ShaderSpecializations example(deviceManager); 164 | if (example.Init()) 165 | { 166 | deviceManager->AddRenderPassToBack(&example); 167 | deviceManager->RunMessageLoop(); 168 | deviceManager->RemoveRenderPass(&example); 169 | } 170 | } 171 | 172 | deviceManager->Shutdown(); 173 | 174 | delete deviceManager; 175 | 176 | return 0; 177 | } 178 | -------------------------------------------------------------------------------- /examples/shader_specializations/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T vs -E main_vs 2 | shaders.hlsl -T ps -E main_ps 3 | -------------------------------------------------------------------------------- /examples/shader_specializations/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | [[vk::constant_id(0)]] const float c_offset = 0; 24 | [[vk::constant_id(1)]] const uint c_color = 0xffffff; 25 | 26 | static const float2 g_positions[] = { 27 | float2(-0.5, -0.5), 28 | float2(0, 0.5), 29 | float2(0.5, -0.5) 30 | }; 31 | 32 | static const float3 g_colors[] = { 33 | float3(1, 0, 0), 34 | float3(0, 1, 0), 35 | float3(0, 0, 1) 36 | }; 37 | 38 | void main_vs( 39 | uint i_vertexId : SV_VertexID, 40 | out float4 o_pos : SV_Position, 41 | out float3 o_color : COLOR 42 | ) 43 | { 44 | o_pos = float4(g_positions[i_vertexId], 0, 1); 45 | o_pos.x = o_pos.x * 0.5 + c_offset; 46 | o_color = g_colors[i_vertexId]; 47 | } 48 | 49 | void main_ps( 50 | in float4 i_pos : SV_Position, 51 | in float3 i_color : COLOR, 52 | out float4 o_color : SV_Target0 53 | ) 54 | { 55 | o_color.r = float(c_color & 0xff) / 0xff; 56 | o_color.g = float((c_color >> 8) & 0xff) / 0xff; 57 | o_color.b = float((c_color >> 16) & 0xff) / 0xff; 58 | o_color.a = 1; 59 | } 60 | -------------------------------------------------------------------------------- /examples/threaded_rendering/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | file(GLOB sources "*.cpp" "*.h") 24 | 25 | set(project threaded_rendering) 26 | set(folder "Examples/Threaded Rendering") 27 | 28 | add_executable(${project} WIN32 ${sources}) 29 | target_link_libraries(${project} donut_render donut_app donut_engine) 30 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 31 | -------------------------------------------------------------------------------- /examples/variable_shading/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project variable_shading) 28 | set(folder "Examples/Variable Shading") 29 | 30 | donut_compile_shaders( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Variable Shading" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | SOURCES ${shaders} 35 | FOLDER ${folder} 36 | DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil 37 | SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv 38 | ) 39 | 40 | add_executable(${project} WIN32 ${sources}) 41 | target_link_libraries(${project} donut_core donut_engine donut_app donut_render) 42 | add_dependencies(${project} ${project}_shaders) 43 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 44 | 45 | if (MSVC) 46 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 47 | endif() 48 | -------------------------------------------------------------------------------- /examples/variable_shading/lighting_cb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef LIGHTING_CB_H 24 | #define LIGHTING_CB_H 25 | 26 | #include 27 | #include 28 | 29 | struct LightingConstants 30 | { 31 | float4 ambientColor; 32 | 33 | LightConstants light; 34 | PlanarViewConstants view; 35 | }; 36 | 37 | #endif // LIGHTING_CB_H -------------------------------------------------------------------------------- /examples/variable_shading/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T cs -E main_cs 2 | -------------------------------------------------------------------------------- /examples/variable_shading/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | // Shading rate enum values copied from D3D12 header 24 | /* 25 | { 26 | D3D12_SHADING_RATE_1X1 = 0, 27 | D3D12_SHADING_RATE_1X2 = 0x1, 28 | D3D12_SHADING_RATE_2X1 = 0x4, 29 | D3D12_SHADING_RATE_2X2 = 0x5, 30 | D3D12_SHADING_RATE_2X4 = 0x6, 31 | D3D12_SHADING_RATE_4X2 = 0x9, 32 | D3D12_SHADING_RATE_4X4 = 0xa 33 | } D3D12_SHADING_RATE; 34 | */ 35 | RWTexture2D shadingRateSurface : register(u0); 36 | Texture2D motionVectors : register(t0); 37 | Texture2D prevFrameColors : register(t1); 38 | 39 | #define TILE_SIZE 16 40 | 41 | [numthreads(1, 1, 1)] 42 | void main_cs(uint3 DispatchThreadID : SV_DispatchThreadID) 43 | { 44 | // This is a fairly nonsensical algorithm, reads the average color for the tile in the previous frame 45 | // and sets the shading rate to 4X4 if green channel is bigger than red channel, 1X1 otherwise 46 | // really just intended to make the VRS difference very noticeable to confirm that it is working 47 | float2 motionVector = motionVectors.Load(int3(TILE_SIZE * DispatchThreadID.xy, 0)); 48 | uint2 oldTexel = uint2(float2(DispatchThreadID.xy * TILE_SIZE) + motionVector); 49 | float4 averageColor = 0; 50 | for (int i = 0; i < TILE_SIZE; i++) 51 | { 52 | for (int j = 0; j < TILE_SIZE; j++) 53 | { 54 | averageColor += prevFrameColors.Load(int3(oldTexel + uint2(i, j), 0)); 55 | } 56 | } 57 | averageColor /= (TILE_SIZE * TILE_SIZE); 58 | if (averageColor.g > averageColor.r) 59 | { 60 | shadingRateSurface[DispatchThreadID.xy] = 0xa; 61 | } 62 | else 63 | { 64 | shadingRateSurface[DispatchThreadID.xy] = 0x0; 65 | } 66 | } -------------------------------------------------------------------------------- /examples/vertex_buffer/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | include(../../donut/compileshaders.cmake) 24 | file(GLOB shaders "*.hlsl") 25 | file(GLOB sources "*.cpp" "*.h") 26 | 27 | set(project vertex_buffer) 28 | set(folder "Examples/Vertex Buffer") 29 | 30 | donut_compile_shaders_all_platforms( 31 | TARGET ${project}_shaders 32 | PROJECT_NAME "Vertex Buffer" 33 | CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg 34 | FOLDER ${folder} 35 | OUTPUT_BASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project} 36 | ) 37 | 38 | add_executable(${project} WIN32 ${sources}) 39 | target_link_libraries(${project} donut_app donut_engine) 40 | add_dependencies(${project} ${project}_shaders) 41 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 42 | 43 | if (MSVC) 44 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 45 | endif() 46 | -------------------------------------------------------------------------------- /examples/vertex_buffer/shaders.cfg: -------------------------------------------------------------------------------- 1 | shaders.hlsl -T vs -E main_vs 2 | shaders.hlsl -T ps -E main_ps 3 | -------------------------------------------------------------------------------- /examples/vertex_buffer/shaders.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #pragma pack_matrix(row_major) 24 | 25 | cbuffer CB : register(b0) 26 | { 27 | float4x4 g_Transform; 28 | }; 29 | 30 | void main_vs( 31 | float3 i_pos : POSITION, 32 | float2 i_uv : UV, 33 | out float4 o_pos : SV_Position, 34 | out float2 o_uv : UV 35 | ) 36 | { 37 | o_pos = mul(float4(i_pos, 1), g_Transform); 38 | o_uv = i_uv; 39 | } 40 | 41 | 42 | Texture2D t_Texture : register(t0); 43 | SamplerState s_Sampler : register(s0); 44 | 45 | void main_ps( 46 | in float4 i_pos : SV_Position, 47 | in float2 i_uv : UV, 48 | out float4 o_color : SV_Target0 49 | ) 50 | { 51 | o_color = t_Texture.Sample(s_Sampler, i_uv); 52 | } 53 | -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/d3d12_1.613.0.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/examples/work_graphs/AgilitySDK/d3d12_1.613.0.zip -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/include/d3dx12/d3dx12.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft Corporation. 4 | // Licensed under the MIT License (MIT). 5 | // 6 | //********************************************************* 7 | 8 | #ifndef __D3DX12_H__ 9 | #define __D3DX12_H__ 10 | 11 | #include "d3d12.h" 12 | 13 | #if defined( __cplusplus ) 14 | 15 | #include "d3dx12_barriers.h" 16 | #include "d3dx12_core.h" 17 | #include "d3dx12_default.h" 18 | #include "d3dx12_pipeline_state_stream.h" 19 | #include "d3dx12_render_pass.h" 20 | #include "d3dx12_resource_helpers.h" 21 | #include "d3dx12_root_signature.h" 22 | #include "d3dx12_property_format_table.h" 23 | 24 | #ifndef D3DX12_NO_STATE_OBJECT_HELPERS 25 | #include "d3dx12_state_object.h" 26 | #endif // !D3DX12_NO_STATE_OBJECT_HELPERS 27 | 28 | #ifndef D3DX12_NO_CHECK_FEATURE_SUPPORT_CLASS 29 | #include "d3dx12_check_feature_support.h" 30 | #endif // !D3DX12_NO_CHECK_FEATURE_SUPPORT_CLASS 31 | 32 | #endif // defined( __cplusplus ) 33 | 34 | #endif //__D3DX12_H__ 35 | 36 | -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/include/d3dx12/d3dx12_barriers.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft Corporation. 4 | // Licensed under the MIT License (MIT). 5 | // 6 | //********************************************************* 7 | 8 | #ifndef __D3DX12_BARRIERS_H__ 9 | #define __D3DX12_BARRIERS_H__ 10 | 11 | #if defined( __cplusplus ) 12 | 13 | #include "d3d12.h" 14 | 15 | //------------------------------------------------------------------------------------------------ 16 | struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER 17 | { 18 | CD3DX12_RESOURCE_BARRIER() = default; 19 | explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER &o) noexcept : 20 | D3D12_RESOURCE_BARRIER(o) 21 | {} 22 | static inline CD3DX12_RESOURCE_BARRIER Transition( 23 | _In_ ID3D12Resource* pResource, 24 | D3D12_RESOURCE_STATES stateBefore, 25 | D3D12_RESOURCE_STATES stateAfter, 26 | UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 27 | D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) noexcept 28 | { 29 | CD3DX12_RESOURCE_BARRIER result = {}; 30 | D3D12_RESOURCE_BARRIER &barrier = result; 31 | result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; 32 | result.Flags = flags; 33 | barrier.Transition.pResource = pResource; 34 | barrier.Transition.StateBefore = stateBefore; 35 | barrier.Transition.StateAfter = stateAfter; 36 | barrier.Transition.Subresource = subresource; 37 | return result; 38 | } 39 | static inline CD3DX12_RESOURCE_BARRIER Aliasing( 40 | _In_opt_ ID3D12Resource* pResourceBefore, 41 | _In_opt_ ID3D12Resource* pResourceAfter) noexcept 42 | { 43 | CD3DX12_RESOURCE_BARRIER result = {}; 44 | D3D12_RESOURCE_BARRIER &barrier = result; 45 | result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; 46 | barrier.Aliasing.pResourceBefore = pResourceBefore; 47 | barrier.Aliasing.pResourceAfter = pResourceAfter; 48 | return result; 49 | } 50 | static inline CD3DX12_RESOURCE_BARRIER UAV( 51 | _In_opt_ ID3D12Resource* pResource) noexcept 52 | { 53 | CD3DX12_RESOURCE_BARRIER result = {}; 54 | D3D12_RESOURCE_BARRIER &barrier = result; 55 | result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; 56 | barrier.UAV.pResource = pResource; 57 | return result; 58 | } 59 | }; 60 | 61 | #if defined(D3D12_SDK_VERSION) && (D3D12_SDK_VERSION >= 608) 62 | 63 | //================================================================================================ 64 | // D3DX12 Enhanced Barrier Helpers 65 | //================================================================================================ 66 | 67 | class CD3DX12_BARRIER_SUBRESOURCE_RANGE : public D3D12_BARRIER_SUBRESOURCE_RANGE 68 | { 69 | public: 70 | CD3DX12_BARRIER_SUBRESOURCE_RANGE() = default; 71 | CD3DX12_BARRIER_SUBRESOURCE_RANGE(const D3D12_BARRIER_SUBRESOURCE_RANGE &o) noexcept : 72 | D3D12_BARRIER_SUBRESOURCE_RANGE(o) 73 | {} 74 | explicit CD3DX12_BARRIER_SUBRESOURCE_RANGE(UINT Subresource) noexcept : 75 | D3D12_BARRIER_SUBRESOURCE_RANGE{ Subresource, 0, 0, 0, 0, 0 } 76 | {} 77 | CD3DX12_BARRIER_SUBRESOURCE_RANGE( 78 | UINT firstMipLevel, 79 | UINT numMips, 80 | UINT firstArraySlice, 81 | UINT numArraySlices, 82 | UINT firstPlane = 0, 83 | UINT numPlanes = 1) noexcept : 84 | D3D12_BARRIER_SUBRESOURCE_RANGE 85 | { 86 | firstMipLevel, 87 | numMips, 88 | firstArraySlice, 89 | numArraySlices, 90 | firstPlane, 91 | numPlanes 92 | } 93 | {} 94 | }; 95 | 96 | class CD3DX12_GLOBAL_BARRIER : public D3D12_GLOBAL_BARRIER 97 | { 98 | public: 99 | CD3DX12_GLOBAL_BARRIER() = default; 100 | CD3DX12_GLOBAL_BARRIER(const D3D12_GLOBAL_BARRIER &o) noexcept : D3D12_GLOBAL_BARRIER(o){} 101 | CD3DX12_GLOBAL_BARRIER( 102 | D3D12_BARRIER_SYNC syncBefore, 103 | D3D12_BARRIER_SYNC syncAfter, 104 | D3D12_BARRIER_ACCESS accessBefore, 105 | D3D12_BARRIER_ACCESS accessAfter) noexcept : D3D12_GLOBAL_BARRIER { 106 | syncBefore, 107 | syncAfter, 108 | accessBefore, 109 | accessAfter 110 | } 111 | {} 112 | }; 113 | 114 | class CD3DX12_BUFFER_BARRIER : public D3D12_BUFFER_BARRIER 115 | { 116 | public: 117 | CD3DX12_BUFFER_BARRIER() = default; 118 | CD3DX12_BUFFER_BARRIER(const D3D12_BUFFER_BARRIER &o) noexcept : D3D12_BUFFER_BARRIER(o){} 119 | CD3DX12_BUFFER_BARRIER( 120 | D3D12_BARRIER_SYNC syncBefore, 121 | D3D12_BARRIER_SYNC syncAfter, 122 | D3D12_BARRIER_ACCESS accessBefore, 123 | D3D12_BARRIER_ACCESS accessAfter, 124 | ID3D12Resource *pRes) noexcept : D3D12_BUFFER_BARRIER { 125 | syncBefore, 126 | syncAfter, 127 | accessBefore, 128 | accessAfter, 129 | pRes, 130 | 0, ULLONG_MAX 131 | } 132 | {} 133 | }; 134 | 135 | class CD3DX12_TEXTURE_BARRIER : public D3D12_TEXTURE_BARRIER 136 | { 137 | public: 138 | CD3DX12_TEXTURE_BARRIER() = default; 139 | CD3DX12_TEXTURE_BARRIER(const D3D12_TEXTURE_BARRIER &o) noexcept : D3D12_TEXTURE_BARRIER(o){} 140 | CD3DX12_TEXTURE_BARRIER( 141 | D3D12_BARRIER_SYNC syncBefore, 142 | D3D12_BARRIER_SYNC syncAfter, 143 | D3D12_BARRIER_ACCESS accessBefore, 144 | D3D12_BARRIER_ACCESS accessAfter, 145 | D3D12_BARRIER_LAYOUT layoutBefore, 146 | D3D12_BARRIER_LAYOUT layoutAfter, 147 | ID3D12Resource *pRes, 148 | const D3D12_BARRIER_SUBRESOURCE_RANGE &subresources, 149 | D3D12_TEXTURE_BARRIER_FLAGS flag = D3D12_TEXTURE_BARRIER_FLAG_NONE) noexcept : D3D12_TEXTURE_BARRIER { 150 | syncBefore, 151 | syncAfter, 152 | accessBefore, 153 | accessAfter, 154 | layoutBefore, 155 | layoutAfter, 156 | pRes, 157 | subresources, 158 | flag 159 | } 160 | {} 161 | }; 162 | 163 | class CD3DX12_BARRIER_GROUP : public D3D12_BARRIER_GROUP 164 | { 165 | public: 166 | CD3DX12_BARRIER_GROUP() = default; 167 | CD3DX12_BARRIER_GROUP(const D3D12_BARRIER_GROUP &o) noexcept : D3D12_BARRIER_GROUP(o){} 168 | CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_BUFFER_BARRIER *pBarriers) noexcept 169 | { 170 | Type = D3D12_BARRIER_TYPE_BUFFER; 171 | NumBarriers = numBarriers; 172 | pBufferBarriers = pBarriers; 173 | } 174 | CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_TEXTURE_BARRIER *pBarriers) noexcept 175 | { 176 | Type = D3D12_BARRIER_TYPE_TEXTURE; 177 | NumBarriers = numBarriers; 178 | pTextureBarriers = pBarriers; 179 | } 180 | CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_GLOBAL_BARRIER *pBarriers) noexcept 181 | { 182 | Type = D3D12_BARRIER_TYPE_GLOBAL; 183 | NumBarriers = numBarriers; 184 | pGlobalBarriers = pBarriers; 185 | } 186 | }; 187 | #endif // D3D12_SDK_VERSION >= 608 188 | 189 | 190 | #endif // defined( __cplusplus ) 191 | 192 | #endif // __D3DX12_BARRIERS_H__ 193 | -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/include/d3dx12/d3dx12_default.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft Corporation. 4 | // Licensed under the MIT License (MIT). 5 | // 6 | //********************************************************* 7 | 8 | #pragma once 9 | 10 | struct CD3DX12_DEFAULT {}; 11 | extern const DECLSPEC_SELECTANY CD3DX12_DEFAULT D3D12_DEFAULT; 12 | 13 | -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/include/d3dx12/d3dx12_render_pass.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft Corporation. 4 | // Licensed under the MIT License (MIT). 5 | // 6 | //********************************************************* 7 | 8 | #pragma once 9 | 10 | #ifndef __cplusplus 11 | #error D3DX12 requires C++ 12 | #endif 13 | 14 | #include "d3d12.h" 15 | #if defined(D3D12_SDK_VERSION) && (D3D12_SDK_VERSION >= 609) 16 | inline bool operator==(const D3D12_RENDER_PASS_BEGINNING_ACCESS_PRESERVE_LOCAL_PARAMETERS& a, const D3D12_RENDER_PASS_ENDING_ACCESS_PRESERVE_LOCAL_PARAMETERS& b) noexcept 17 | { 18 | return ((a.AdditionalWidth == b.AdditionalWidth) && (a.AdditionalHeight == b.AdditionalHeight)); 19 | } 20 | 21 | inline bool operator==(const D3D12_RENDER_PASS_BEGINNING_ACCESS_PRESERVE_LOCAL_PARAMETERS& a, const D3D12_RENDER_PASS_BEGINNING_ACCESS_PRESERVE_LOCAL_PARAMETERS& b) noexcept 22 | { 23 | return ((a.AdditionalWidth == b.AdditionalWidth) && (a.AdditionalHeight == b.AdditionalHeight)); 24 | } 25 | 26 | inline bool operator==(const D3D12_RENDER_PASS_ENDING_ACCESS_PRESERVE_LOCAL_PARAMETERS& a, const D3D12_RENDER_PASS_ENDING_ACCESS_PRESERVE_LOCAL_PARAMETERS& b) noexcept 27 | { 28 | return ((a.AdditionalWidth == b.AdditionalWidth) && (a.AdditionalHeight == b.AdditionalHeight)); 29 | } 30 | #endif 31 | 32 | inline bool operator==( const D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS &a, const D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS &b) noexcept 33 | { 34 | return a.ClearValue == b.ClearValue; 35 | } 36 | 37 | inline bool operator==( const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS &a, const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS &b) noexcept 38 | { 39 | if (a.pSrcResource != b.pSrcResource) return false; 40 | if (a.pDstResource != b.pDstResource) return false; 41 | if (a.SubresourceCount != b.SubresourceCount) return false; 42 | if (a.Format != b.Format) return false; 43 | if (a.ResolveMode != b.ResolveMode) return false; 44 | if (a.PreserveResolveSource != b.PreserveResolveSource) return false; 45 | return true; 46 | } 47 | 48 | inline bool operator==( const D3D12_RENDER_PASS_BEGINNING_ACCESS &a, const D3D12_RENDER_PASS_BEGINNING_ACCESS &b) noexcept 49 | { 50 | if (a.Type != b.Type) return false; 51 | switch (a.Type) 52 | { 53 | case D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR: 54 | if (!(a.Clear == b.Clear)) return false; 55 | break; 56 | #if defined(D3D12_SDK_VERSION) && (D3D12_SDK_VERSION >= 609) 57 | case D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE_LOCAL_RENDER: 58 | case D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE_LOCAL_SRV: 59 | case D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE_LOCAL_UAV: 60 | if (!(a.PreserveLocal == b.PreserveLocal)) return false; 61 | break; 62 | #endif 63 | } 64 | return true; 65 | } 66 | 67 | inline bool operator==(const D3D12_RENDER_PASS_ENDING_ACCESS& a, const D3D12_RENDER_PASS_ENDING_ACCESS& b) noexcept 68 | { 69 | if (a.Type != b.Type) return false; 70 | switch (a.Type) 71 | { 72 | case D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE: 73 | if (!(a.Resolve == b.Resolve)) return false; 74 | break; 75 | #if defined(D3D12_SDK_VERSION) && (D3D12_SDK_VERSION >= 609) 76 | case D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE_LOCAL_RENDER: 77 | case D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE_LOCAL_SRV: 78 | case D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE_LOCAL_UAV: 79 | if (!(a.PreserveLocal == b.PreserveLocal)) return false; 80 | break; 81 | #endif 82 | } 83 | 84 | return true; 85 | } 86 | 87 | inline bool operator==( const D3D12_RENDER_PASS_RENDER_TARGET_DESC &a, const D3D12_RENDER_PASS_RENDER_TARGET_DESC &b) noexcept 88 | { 89 | if (a.cpuDescriptor.ptr != b.cpuDescriptor.ptr) return false; 90 | if (!(a.BeginningAccess == b.BeginningAccess)) return false; 91 | if (!(a.EndingAccess == b.EndingAccess)) return false; 92 | return true; 93 | } 94 | inline bool operator==( const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC &a, const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC &b) noexcept 95 | { 96 | if (a.cpuDescriptor.ptr != b.cpuDescriptor.ptr) return false; 97 | if (!(a.DepthBeginningAccess == b.DepthBeginningAccess)) return false; 98 | if (!(a.StencilBeginningAccess == b.StencilBeginningAccess)) return false; 99 | if (!(a.DepthEndingAccess == b.DepthEndingAccess)) return false; 100 | if (!(a.StencilEndingAccess == b.StencilEndingAccess)) return false; 101 | return true; 102 | } 103 | -------------------------------------------------------------------------------- /examples/work_graphs/AgilitySDK/include/dxgiformat.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) Microsoft Corporation. 3 | // Licensed under the MIT license 4 | // 5 | 6 | #ifndef __dxgiformat_h__ 7 | #define __dxgiformat_h__ 8 | 9 | #define DXGI_FORMAT_DEFINED 1 10 | 11 | typedef enum DXGI_FORMAT 12 | { 13 | DXGI_FORMAT_UNKNOWN = 0, 14 | DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, 15 | DXGI_FORMAT_R32G32B32A32_FLOAT = 2, 16 | DXGI_FORMAT_R32G32B32A32_UINT = 3, 17 | DXGI_FORMAT_R32G32B32A32_SINT = 4, 18 | DXGI_FORMAT_R32G32B32_TYPELESS = 5, 19 | DXGI_FORMAT_R32G32B32_FLOAT = 6, 20 | DXGI_FORMAT_R32G32B32_UINT = 7, 21 | DXGI_FORMAT_R32G32B32_SINT = 8, 22 | DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, 23 | DXGI_FORMAT_R16G16B16A16_FLOAT = 10, 24 | DXGI_FORMAT_R16G16B16A16_UNORM = 11, 25 | DXGI_FORMAT_R16G16B16A16_UINT = 12, 26 | DXGI_FORMAT_R16G16B16A16_SNORM = 13, 27 | DXGI_FORMAT_R16G16B16A16_SINT = 14, 28 | DXGI_FORMAT_R32G32_TYPELESS = 15, 29 | DXGI_FORMAT_R32G32_FLOAT = 16, 30 | DXGI_FORMAT_R32G32_UINT = 17, 31 | DXGI_FORMAT_R32G32_SINT = 18, 32 | DXGI_FORMAT_R32G8X24_TYPELESS = 19, 33 | DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, 34 | DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, 35 | DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, 36 | DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, 37 | DXGI_FORMAT_R10G10B10A2_UNORM = 24, 38 | DXGI_FORMAT_R10G10B10A2_UINT = 25, 39 | DXGI_FORMAT_R11G11B10_FLOAT = 26, 40 | DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, 41 | DXGI_FORMAT_R8G8B8A8_UNORM = 28, 42 | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, 43 | DXGI_FORMAT_R8G8B8A8_UINT = 30, 44 | DXGI_FORMAT_R8G8B8A8_SNORM = 31, 45 | DXGI_FORMAT_R8G8B8A8_SINT = 32, 46 | DXGI_FORMAT_R16G16_TYPELESS = 33, 47 | DXGI_FORMAT_R16G16_FLOAT = 34, 48 | DXGI_FORMAT_R16G16_UNORM = 35, 49 | DXGI_FORMAT_R16G16_UINT = 36, 50 | DXGI_FORMAT_R16G16_SNORM = 37, 51 | DXGI_FORMAT_R16G16_SINT = 38, 52 | DXGI_FORMAT_R32_TYPELESS = 39, 53 | DXGI_FORMAT_D32_FLOAT = 40, 54 | DXGI_FORMAT_R32_FLOAT = 41, 55 | DXGI_FORMAT_R32_UINT = 42, 56 | DXGI_FORMAT_R32_SINT = 43, 57 | DXGI_FORMAT_R24G8_TYPELESS = 44, 58 | DXGI_FORMAT_D24_UNORM_S8_UINT = 45, 59 | DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, 60 | DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, 61 | DXGI_FORMAT_R8G8_TYPELESS = 48, 62 | DXGI_FORMAT_R8G8_UNORM = 49, 63 | DXGI_FORMAT_R8G8_UINT = 50, 64 | DXGI_FORMAT_R8G8_SNORM = 51, 65 | DXGI_FORMAT_R8G8_SINT = 52, 66 | DXGI_FORMAT_R16_TYPELESS = 53, 67 | DXGI_FORMAT_R16_FLOAT = 54, 68 | DXGI_FORMAT_D16_UNORM = 55, 69 | DXGI_FORMAT_R16_UNORM = 56, 70 | DXGI_FORMAT_R16_UINT = 57, 71 | DXGI_FORMAT_R16_SNORM = 58, 72 | DXGI_FORMAT_R16_SINT = 59, 73 | DXGI_FORMAT_R8_TYPELESS = 60, 74 | DXGI_FORMAT_R8_UNORM = 61, 75 | DXGI_FORMAT_R8_UINT = 62, 76 | DXGI_FORMAT_R8_SNORM = 63, 77 | DXGI_FORMAT_R8_SINT = 64, 78 | DXGI_FORMAT_A8_UNORM = 65, 79 | DXGI_FORMAT_R1_UNORM = 66, 80 | DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, 81 | DXGI_FORMAT_R8G8_B8G8_UNORM = 68, 82 | DXGI_FORMAT_G8R8_G8B8_UNORM = 69, 83 | DXGI_FORMAT_BC1_TYPELESS = 70, 84 | DXGI_FORMAT_BC1_UNORM = 71, 85 | DXGI_FORMAT_BC1_UNORM_SRGB = 72, 86 | DXGI_FORMAT_BC2_TYPELESS = 73, 87 | DXGI_FORMAT_BC2_UNORM = 74, 88 | DXGI_FORMAT_BC2_UNORM_SRGB = 75, 89 | DXGI_FORMAT_BC3_TYPELESS = 76, 90 | DXGI_FORMAT_BC3_UNORM = 77, 91 | DXGI_FORMAT_BC3_UNORM_SRGB = 78, 92 | DXGI_FORMAT_BC4_TYPELESS = 79, 93 | DXGI_FORMAT_BC4_UNORM = 80, 94 | DXGI_FORMAT_BC4_SNORM = 81, 95 | DXGI_FORMAT_BC5_TYPELESS = 82, 96 | DXGI_FORMAT_BC5_UNORM = 83, 97 | DXGI_FORMAT_BC5_SNORM = 84, 98 | DXGI_FORMAT_B5G6R5_UNORM = 85, 99 | DXGI_FORMAT_B5G5R5A1_UNORM = 86, 100 | DXGI_FORMAT_B8G8R8A8_UNORM = 87, 101 | DXGI_FORMAT_B8G8R8X8_UNORM = 88, 102 | DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, 103 | DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, 104 | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, 105 | DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, 106 | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, 107 | DXGI_FORMAT_BC6H_TYPELESS = 94, 108 | DXGI_FORMAT_BC6H_UF16 = 95, 109 | DXGI_FORMAT_BC6H_SF16 = 96, 110 | DXGI_FORMAT_BC7_TYPELESS = 97, 111 | DXGI_FORMAT_BC7_UNORM = 98, 112 | DXGI_FORMAT_BC7_UNORM_SRGB = 99, 113 | DXGI_FORMAT_AYUV = 100, 114 | DXGI_FORMAT_Y410 = 101, 115 | DXGI_FORMAT_Y416 = 102, 116 | DXGI_FORMAT_NV12 = 103, 117 | DXGI_FORMAT_P010 = 104, 118 | DXGI_FORMAT_P016 = 105, 119 | DXGI_FORMAT_420_OPAQUE = 106, 120 | DXGI_FORMAT_YUY2 = 107, 121 | DXGI_FORMAT_Y210 = 108, 122 | DXGI_FORMAT_Y216 = 109, 123 | DXGI_FORMAT_NV11 = 110, 124 | DXGI_FORMAT_AI44 = 111, 125 | DXGI_FORMAT_IA44 = 112, 126 | DXGI_FORMAT_P8 = 113, 127 | DXGI_FORMAT_A8P8 = 114, 128 | DXGI_FORMAT_B4G4R4A4_UNORM = 115, 129 | 130 | DXGI_FORMAT_P208 = 130, 131 | DXGI_FORMAT_V208 = 131, 132 | DXGI_FORMAT_V408 = 132, 133 | 134 | 135 | DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189, 136 | DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190, 137 | 138 | DXGI_FORMAT_A4B4G4R4_UNORM = 191, 139 | 140 | 141 | DXGI_FORMAT_FORCE_UINT = 0xffffffff 142 | } DXGI_FORMAT; 143 | 144 | #endif // __dxgiformat_h__ 145 | -------------------------------------------------------------------------------- /examples/work_graphs/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | file(GLOB shaders "*.hlsl") 23 | file(GLOB sources "*.cpp" "*.h") 24 | 25 | set(project work_graphs_d3d12) 26 | set(folder "Examples/Work Graphs") 27 | 28 | # Copy agility SDK bits to D3D12 folder right next to the executable 29 | set (D3D12_AGILITY_SDK_RUNTIME_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/D3D12") 30 | 31 | if (NOT EXISTS ${D3D12_AGILITY_SDK_RUNTIME_DIR}) 32 | execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${D3D12_AGILITY_SDK_RUNTIME_DIR}) 33 | endif() 34 | 35 | if (NOT EXISTS "${D3D12_AGILITY_SDK_RUNTIME_DIR}/D3D12Core.dll" OR NOT EXISTS "${D3D12_AGILITY_SDK_RUNTIME_DIR}/D3D12SDKLayers.dll") 36 | message(STATUS "Extracting Agility SDK runtime bits") 37 | execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf "${CMAKE_CURRENT_SOURCE_DIR}/AgilitySDK/d3d12_1.613.0.zip" 38 | WORKING_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/D3D12") 39 | endif() 40 | 41 | # Custom shader compilation using the agility SDK compiler rather than whatever is chosen during CMake config 42 | set_source_files_properties(SHADER_SOURCES FOLDER ${folder} PROPERTIES VS_TOOL_OVERRIDE "None") 43 | add_custom_target(${project}_shaders DEPENDS ShaderMake SOURCES ${SHADER_SOURCES}) 44 | 45 | set(dxcCompilerCommand ShaderMake 46 | --config "${CMAKE_CURRENT_SOURCE_DIR}/shaders.cfg" 47 | --out "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil" 48 | --platform DXIL 49 | --binaryBlob --outputExt .bin 50 | -I ${DONUT_SHADER_INCLUDE_DIR} 51 | --compiler "${DXC_PATH}" 52 | --shaderModel 6_8) 53 | 54 | add_custom_command(TARGET ${project}_shaders PRE_BUILD COMMAND ${dxcCompilerCommand}) 55 | set_target_properties(${project}_shaders PROPERTIES FOLDER ${folder}) 56 | 57 | 58 | add_executable(${project} WIN32 ${sources}) 59 | target_include_directories(${project} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/AgilitySDK/include") 60 | target_link_libraries(${project} donut_app donut_engine) 61 | add_dependencies(${project} ${project}_shaders) 62 | set_target_properties(${project} PROPERTIES FOLDER ${folder}) 63 | 64 | if (MSVC) 65 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 66 | endif() -------------------------------------------------------------------------------- /examples/work_graphs/README.md: -------------------------------------------------------------------------------- 1 | # Direct3D 12 work graphs sample 2 | ![WorkGraphs GUI](work_graphs_d3d12.jpg) 3 | 4 | This sample demonstrates how to achieve GPU-driven shader launches using the [**D3D12 work graphs**](https://github.com/microsoft/DirectX-Specs/blob/master/d3d/WorkGraphs.md) API. In this sample, a large number of meshes animate on the screen in a typical deferred shading rendering environment. After the g-buffer is populated with only normals and material IDs, the sample applies deferred shading using tiled light culling and material shading. This is entirely achieved using one call to **DispatchGraph**. The sample has three variations of work graphs: one that uses tiled light culling and broadcasting launch nodes, and the second variant uses per-pixel light culling and coalescing launch nodes, and the third variant also uses per-pixel light culling but with thread launch nodes. Finally, a standard **Dispatch**-based implementation is provided for comparison. 5 | 6 | ### Work Graph Sample Code 7 | The main focus of this sample is to showcase the use of the D3D12 Work Graphs API and compare it to previous methods to achieve the same results. 8 | 9 | The work graph code is concentrated in a few locations in the sample code: 10 | * **work_graphs_d3d12.cpp**: 11 | * `WorkGraphs::LoadWorkGraphPipelines`: Demonstrates how to compile the work graph library, and how to create the state object. 12 | * `WorkGraphs::PopulateDeferredShadingWorkGraph`: Demonstrates how to prepare and dispatch the work graph. 13 | * **work_graph_broadcasting.hlsl**: The HLSL shader code for all nodes in the work graph, written as broadcasting launch nodes. 14 | 15 | ### Important Build Note 16 | This samples requires a DirectX Compiler with support for shader model 6.8 or later. The first released DXC package with this support can be found here: 17 | https://www.nuget.org/packages/Microsoft.Direct3D.DXC/1.8.2403.18 18 | 19 | Download and extract the package. When configuring the project in CMake, ensure specifying the configuration option **DXC_PATH** to point to 20 | the **dxc.exe** binary from the DXC package you downloaded and unpacked. 21 | 22 | ### Details 23 | #### Scene 24 | The scene is made of multiple floors, where each floor is populated by an animating crowd of energetic cuboids. The ceiling is populated with reflective balls that cast moving lights on each floor. 25 | 26 | This scene is fully procedurally generated to allow resizing flexibly. There are a number of controls to manage scene complexity (number of meshes, lights and materials). 27 | 28 | There are a few types of meshes in the scene: flat plane (used for floors), sphere (used for light balls), and cube (used for the cuboids). During rendering, these meshes are instantiated and randomly placed around the scene. They are animated by a few simple methods (scaling, twist, rotation, translation) which are driven by a special animation compute shader. 29 | 30 | The scene is lit only by spot lights. Spot lights are defined by their two end points and two angles (inner fully lit angle, and outer angle). The spot lights dynamically move their target point. 31 | 32 | Each mesh is assigned a material from a material library. Materials can use one of several types (or "BRDFs") which render in a certain way (e.g. Lambert, Phong, Metallic, Velvet, ...etc). Each material has its own variation of colors and other parameters (e.g. roughness, patterns, flake sizes, ...etc). Evaluating a material requires checking its type first, then executing the shader code that knows how to shade that material under a given light. The list of supported material types can be found in **scene.h**, and material evaluation code can be found in **materials.hlsli**. 33 | 34 | All scene controls can be found grouped at the top of the file **scene.cpp**. Those can be used to control scene size, floor count, mesh count, light count, material count and other parameters to stress test scene performance in various areas. 35 | 36 | The scene's camera and animation speed controls can be found a little down from the beginning of the file **work_graphs_d3d12.cpp**. These parameters are all defined in relation to the scene's size, so tweaking them is not necessary even after changing scene parameters mentioned above. 37 | 38 | 39 | #### Deferred Shading Using Standard Compute Shaders 40 | The sample starts by running a compute shader that updates the scene's animation on the GPU (done by shader file **animation.hlsl**). After which, the G-buffer fill pass is done. In this pass, all meshes in the scene are iterated over and are submitted for drawing. There is no culling to meshes in this sample. 41 | 42 | The g-buffer pass fills a single RGBA16 render target with the following information (RGB: World-space normal, A: Material index). The shader file for this step is **gbuffer_fill.hlsl**. 43 | 44 | After the g-buffer pass, lighting is done using one of four techniques: standard deferred shading compute, work graphs (broadcasting launch), work graphs (coalescing launch) and work graphs (thread launch). 45 | 46 | The standard deferred shading compute pass is done using two compute dispatches: 47 | 1. **Tiled light culling**: The screen is divided to tiles 8x4 pixels each. For each tile, all lights affecting that tile are collected and stored in a buffer. There is a maximum number of lights that can be collected in each tile, and that number is configurable (`DeferredShadingParam_MaxLightsPerTile` in **work_graphs_d3d12.cpp** and `c_MaxLightsPerTile` in **lighting.hlsli**). The shader file for this step is **light_culling.hlsl**. 48 | 2. **Deferred shading using uber shader**: Each tile is processed again. This time using the lights collected by the tile, all materials found in the tile are evaluated in an uber shader. The shader file for this step is **deferred_shading.hlsl**. 49 | 50 | #### Broadcasting Launch Work Graph 51 | The work graph technique completely replaces the two steps mentioned above in the standard deferred shading compute pass (tiled light culling, and deferred shading uber shader). 52 | 53 | This version uses broadcasting launch nodes to replicate the same concept of tiled light culling. The root node of the graph (`LightCull_Node`) is executed for each screen tile. The node does light culling and store the result in a record to be sent to the next step of the graph. 54 | 55 | The root node can target an array of outputs, where each output is specialized for a certain material type (or a screen clear), called `Material_Nodes`. The culled lights list is placed in a record that is sent to the correct node in the graph that can handle the type of material in the tile. 56 | 57 | In the case a tile containing multiple different material types, the root node spawns multiple records to cover the same tile using different material type nodes. 58 | 59 | When launching the work graph for the first time, the work graph's backing memory must be initialized by passing a special flag to work graph's program descriptor. 60 | 61 | #### Performance tuning and controls 62 | 63 | * The g-buffer pass performance is tied to the number and triangle density of the meshes in the scene. The CPU performance is also mainly scaled linearly by the number of meshes in the scene, as no scene acceleration structures are used in the sample. 64 | * The lighting passes (of all techniques) are mainly affected by the number of lights and how many types of materials are supported. 65 | * The maximum number of lights handled per tile affects the standard deferred shading pass and the broadcasting launch work graph. Under-estimating this value will result in some blocky lighting artifacts on the screen. This value also controls storage size in both the culled lights buffer used by the standard deferred shader, as well as the size of the material node record used in the work graphs. -------------------------------------------------------------------------------- /examples/work_graphs/animation.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include "scene_data.hlsli" 24 | 25 | // These are root 32-bit values 26 | cbuffer InlineConstants : register(b0) 27 | { 28 | float g_Time; 29 | float g_TimeDiff; 30 | uint g_ResetState; 31 | }; 32 | 33 | StructuredBuffer t_InstanceData : register(t0); 34 | RWStructuredBuffer u_AnimStateData : register(u0); 35 | RWStructuredBuffer u_LightData : register(u0); 36 | 37 | #define DANCE_BUMP 0 38 | #define DANCE_JUMP 1 39 | #define DANCE_JUMPTWIST 2 40 | #define DANCE_ROCK 3 41 | #define DANCE_TWIST 4 42 | #define DANCE_COUNT 5 43 | 44 | float IntroOutro(float time,float introLength) 45 | { 46 | if (time < introLength) 47 | return time/introLength; 48 | if (time > 1-introLength) 49 | return (1-time)/introLength; 50 | return 1.0f; 51 | } 52 | 53 | float CosineInterpolation(float v) { return (1-cos(v*c_PI))/2; } 54 | 55 | void StepDance(inout AnimState state, uint rndSeed) 56 | { 57 | state.timeInState += g_TimeDiff; 58 | 59 | if (state.timeInState >= state.statePeriod) 60 | { 61 | state.scale = float3(1,1,1); 62 | state.offsetY = 0; 63 | state.rotationY = 0; 64 | state.twist = 0; 65 | state.timeInState = 0; 66 | if (state.stateRepeats > 0) 67 | state.stateRepeats--; 68 | else 69 | { 70 | rndSeed = Random(rndSeed+state.state); 71 | uint oldState = state.state; 72 | state.state = rndSeed % DANCE_COUNT; 73 | if (oldState == state.state) 74 | state.state = (state.state+1) % DANCE_COUNT; 75 | rndSeed = Random(rndSeed); 76 | state.statePeriod = lerp(0.65f,0.8f,NormalizeRandom(rndSeed)); 77 | rndSeed = Random(rndSeed); 78 | state.stateRepeats = 2 + rndSeed % 5; 79 | } 80 | } 81 | 82 | const float timeInStateNrm = state.timeInState / state.statePeriod; 83 | switch (state.state) 84 | { 85 | case DANCE_BUMP: 86 | state.scale.y = lerp(1,0.3f,CosineInterpolation(abs(timeInStateNrm*4))); 87 | break; 88 | 89 | case DANCE_JUMP: 90 | case DANCE_JUMPTWIST: 91 | if (timeInStateNrm < 0.4f) 92 | { 93 | const float compress = timeInStateNrm/0.4f; 94 | state.scale.y = lerp(1,0.3f,CosineInterpolation(compress)); 95 | state.scale.xz = lerp(1.6,1,state.scale.y); 96 | } 97 | else if (timeInStateNrm < 0.6f) { } 98 | else if (timeInStateNrm < 0.9f) 99 | { 100 | const float shoot = (timeInStateNrm-0.6f)/0.3f; 101 | state.scale.y = lerp(0.3f,1.3f,sin(shoot*c_PI*0.5f)); 102 | state.scale.xz = lerp(1.6,1,shoot); 103 | state.offsetY = shoot * 20.0f; 104 | state.rotationY = (state.state == DANCE_JUMPTWIST) ? lerp(0,c_PI*0.5f,CosineInterpolation(shoot)) : 0; 105 | } 106 | else 107 | { 108 | const float land = (timeInStateNrm-0.9f)/0.1f; 109 | state.offsetY = lerp(20,0,land); 110 | state.scale.y = lerp(1.3f,1,CosineInterpolation(land)); 111 | state.rotationY = 0; 112 | } 113 | break; 114 | 115 | case DANCE_ROCK: 116 | { 117 | const float compress = sin(timeInStateNrm*c_PI); 118 | state.rotationY = lerp(0,c_PI*0.5f,compress)*((state.stateRepeats & 1)?1:-1); 119 | state.scale.y = lerp(1,0.5,compress*compress); 120 | state.scale.xz = lerp(1,1.3,compress*compress); 121 | } 122 | break; 123 | 124 | case DANCE_TWIST: 125 | state.twist = sin(timeInStateNrm*c_PI*4); 126 | state.scale.y = 1-IntroOutro(smoothstep(0,1,timeInStateNrm),0.25f)*0.75f; 127 | state.scale.xz = lerp(0.3f/state.scale.y,1,abs(timeInStateNrm-0.5f)); // Volume preservation 128 | { 129 | const float blendToOriginal = IntroOutro(timeInStateNrm,0.15f); 130 | state.twist *= blendToOriginal; 131 | state.scale = lerp(float3(1,1,1),state.scale,blendToOriginal); 132 | state.rotationY *= blendToOriginal; 133 | state.offsetY *= blendToOriginal; 134 | } 135 | break; 136 | } 137 | 138 | } 139 | 140 | [numthreads(32, 1, 1)] 141 | void CSMainObjects(uint2 dispatchThreadId : SV_DispatchThreadID) 142 | { 143 | const uint objectIndex = dispatchThreadId.y*0xFFFF*32 + dispatchThreadId.x; 144 | const uint rnd = Random(objectIndex); 145 | 146 | AnimState state; 147 | if (g_ResetState) 148 | { 149 | state = (AnimState)0; 150 | state.scale = float3(1,1,1); 151 | } 152 | else state = u_AnimStateData[objectIndex]; 153 | 154 | const uint animType = t_InstanceData[objectIndex].animType; 155 | if (animType == AT_RotateY) 156 | state.rotationY += g_TimeDiff * lerp(0.4f, 1.0f, NormalizeRandom(rnd)) * ((rnd & 1) ? -1 : 1); 157 | else if (animType == AT_Dance) 158 | StepDance(state, rnd); 159 | 160 | u_AnimStateData[objectIndex] = state; 161 | } 162 | 163 | [numthreads(32, 1, 1)] 164 | void CSMainLights(uint2 dispatchThreadId : SV_DispatchThreadID) 165 | { 166 | const uint lightIndex = dispatchThreadId.y*0xFFFF*32 + dispatchThreadId.x; 167 | uint rnd = Random(lightIndex); 168 | 169 | Light light = u_LightData[lightIndex]; 170 | if (g_ResetState) 171 | light.targetOffset = float3(0,0,0); 172 | else 173 | { 174 | const float radius = lerp(150,300,NormalizeRandom(rnd)); 175 | rnd = Random(rnd); 176 | const float speed = lerp(1,3,NormalizeRandom(rnd)); 177 | float2 sinCos; 178 | sincos(g_Time*speed,sinCos.x,sinCos.y); 179 | light.targetOffset = float3(sinCos.y*radius,0,sinCos.x*radius); 180 | } 181 | 182 | u_LightData[lightIndex] = light; 183 | } -------------------------------------------------------------------------------- /examples/work_graphs/deferred_shading.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include "scene_data.hlsli" 24 | #include "materials.hlsli" 25 | #include "lighting.hlsli" 26 | 27 | // These are root 32-bit values 28 | cbuffer InlineConstants : register(b0) 29 | { 30 | uint g_LightTilesX, g_LightTilesY; 31 | uint g_LightCount; 32 | }; 33 | 34 | StructuredBuffer t_MaterialData : register(t0); 35 | Texture2D t_GBuffer : register(t1); 36 | Texture2D t_DepthBuffer : register(t2); 37 | StructuredBuffer t_CulledLightsData : register(t3); 38 | StructuredBuffer t_LightData : register(t4); 39 | RWTexture2D u_LDRBuffer : register(u1); 40 | 41 | [numthreads(8, 4, 1)] 42 | void CSMain(uint2 dispatchThreadId : SV_DispatchThreadID, uint2 groupId : SV_GroupID) 43 | { 44 | const uint2 pixelXY = dispatchThreadId; 45 | const float depth = t_DepthBuffer.Load(uint3(pixelXY,0)); 46 | uint lightReadSlotIndex = (groupId.y*g_LightTilesX + groupId.x) * c_MaxLightsPerTile; 47 | 48 | if (depth == 1.0f) 49 | { 50 | u_LDRBuffer[pixelXY] = float4(EvaluateSky(pixelXY),1); // Sky 51 | return; 52 | } 53 | 54 | const uint4 gbufferData = t_GBuffer.Load(uint3(pixelXY,0)); 55 | const float3 worldPosition = Unproject(pixelXY, depth); 56 | const float3 worldNormal = normalize(((gbufferData.xyz/(float)0xFFFF)-0.5f)*2.0f); // Decode normal from g-buffer 57 | const float3 camPosition = camPosAndSceneTime.xyz; 58 | const uint materialID = gbufferData.w; 59 | const Material material = t_MaterialData[materialID]; 60 | 61 | static const bool useCulledLights = true; 62 | 63 | float3 color = float3(0,0,0); 64 | uint lightCount = useCulledLights ? c_MaxLightsPerTile : g_LightCount; 65 | 66 | for (uint i=0;i t_InstanceData : register(t0); 32 | StructuredBuffer t_MaterialData : register(t3); 33 | StructuredBuffer t_AnimStateData : register(t4); 34 | 35 | struct PSInput 36 | { 37 | float4 position : SV_Position; 38 | float3 normal : NORMAL; 39 | float2 sinCos : NRMROTY; 40 | uint faceted : FACETED; 41 | uint material : MATERIAL; 42 | }; 43 | 44 | PSInput VSMain(float3 vertexPosition : POSITION, float3 vertexNormal : NORMAL) 45 | { 46 | const Instance instanceData = t_InstanceData[g_InstanceID]; 47 | const AnimState animStateData = t_AnimStateData[g_InstanceID]; 48 | const Material material = t_MaterialData[instanceData.material]; 49 | 50 | float3 scale = instanceData.size*animStateData.scale; 51 | float rotationY = instanceData.rotationY+animStateData.rotationY+(vertexPosition.y+0.5f)*animStateData.twist; 52 | float3 translation = instanceData.position+float3(0,(scale.y-instanceData.size.y)*0.5f+animStateData.offsetY,0); 53 | 54 | float2 sinCos; 55 | sincos(rotationY, sinCos.x, sinCos.y); 56 | 57 | // Transform position to world space, individual transform steps 58 | vertexPosition *= scale; // Scale 59 | vertexPosition = RotateY(vertexPosition, sinCos); 60 | vertexPosition += translation; // Translation 61 | 62 | // Transform normal to world space 63 | if (material.materialType != BT_Faceted) 64 | { 65 | vertexNormal = RotateY(vertexNormal, sinCos); 66 | sinCos = float2(0,0); 67 | } 68 | 69 | PSInput result; 70 | result.position = mul(float4(vertexPosition,1), viewProj); 71 | result.normal = vertexNormal; 72 | result.sinCos = sinCos; 73 | result.faceted = (material.materialType == BT_Faceted) ? 1 : 0; 74 | result.material = instanceData.material; 75 | 76 | return result; 77 | } 78 | 79 | uint4 PSMain(PSInput input) : SV_Target 80 | { 81 | if (input.faceted) 82 | { 83 | const int sections=16; 84 | const float longitude = atan2(input.normal.z,input.normal.x)/c_PI; 85 | const float latitude = acos(input.normal.y)/c_PI; 86 | const float facetedU = ((int)(latitude*sections))/(float)sections; 87 | const float facetedV = ((int)(longitude*sections))/(float)sections; 88 | 89 | float sinU,cosU,sinV,cosV; 90 | sincos(facetedU*c_PI,sinU,cosU); 91 | sincos(facetedV*c_PI,sinV,cosV); 92 | float3 facetedNormal = float3(sinU*cosV,cosU,sinU*sinV); 93 | 94 | input.normal = RotateY(facetedNormal, input.sinCos); // To world space 95 | } 96 | 97 | return uint4((input.normal*0.5f+0.5f)*0xFFFF, input.material); 98 | } 99 | -------------------------------------------------------------------------------- /examples/work_graphs/light_culling.hlsl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #include "scene_data.hlsli" 24 | #include "lighting.hlsli" 25 | 26 | // These are root 32-bit values 27 | cbuffer InlineConstants : register(b0) 28 | { 29 | uint g_LightTilesX, g_LightTilesY; 30 | uint g_LightCount; 31 | }; 32 | 33 | Texture2D t_DepthBuffer : register(t1); 34 | StructuredBuffer t_LightData : register(t4); 35 | RWStructuredBuffer u_CulledLightsDataRW : register(u0); 36 | 37 | groupshared uint s_LightIsRelevant; 38 | groupshared uint s_LightsAdded; 39 | 40 | [numthreads(8, 4, 1)] 41 | void CSMain(uint2 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) 42 | { 43 | const bool isThread0 = (groupThreadId.x == 0) && (groupThreadId.y == 0); 44 | const uint2 pixelXY = dispatchThreadId; 45 | const float depth = t_DepthBuffer.Load(uint3(pixelXY,0)); 46 | const uint writeSlotStart = (groupId.y*g_LightTilesX + groupId.x) * c_MaxLightsPerTile; 47 | 48 | if (isThread0) 49 | s_LightsAdded = 0; 50 | 51 | for (uint i=0;i= cosOuterAngle) && (dot(lightToPoint, lightToPoint) <= lightLengthSq); 44 | } 45 | 46 | void EvaluateSpotLight(Light light, float3 worldPosition, out float3 outDirection, out float3 outColor, out float outAttenuation) 47 | { 48 | const float3 lightTarget = light.target+light.targetOffset; 49 | const float lightLength = length(lightTarget-light.position); 50 | const float3 lightDir = normalize(lightTarget-light.position); 51 | const float3 lightToPoint = worldPosition-light.position; // Starting at light, pointing towards worldPosition (incoming onto worldPosition) 52 | const float3 lightToPointDir = normalize(lightToPoint); 53 | 54 | const float cosInnerAngle = cos(light.innerAngle*0.5f); 55 | const float cosOuterAngle = cos(light.outerAngle*0.5f); 56 | const float cosAlpha = saturate(dot(lightToPointDir, lightDir)); 57 | 58 | const float distanceAttenuation = 1-saturate(length(lightToPoint)/lightLength); 59 | const float angleAttenuation = saturate((cosAlpha-cosOuterAngle)/(cosInnerAngle-cosOuterAngle)); 60 | 61 | outDirection = lightToPointDir; 62 | outColor = light.color; 63 | outAttenuation = angleAttenuation*distanceAttenuation; 64 | } 65 | 66 | float3 EvaluateSky(uint2 pixelXY) 67 | { 68 | float2 sinCosRotY; 69 | sincos(camPosAndSceneTime.w*-0.24f,sinCosRotY.x,sinCosRotY.y); 70 | const float3 worldPos = Unproject(pixelXY, 1); 71 | const float3 pointToCamDir = RotateY(normalize(worldPos-camPosAndSceneTime.xyz),sinCosRotY); 72 | 73 | const int sections = 125; 74 | const float2 uv = float2( 75 | (atan2(pointToCamDir.z,pointToCamDir.x)/c_PI+1)*0.5f, 76 | acos(pointToCamDir.y)/c_PI); 77 | const uint2 sector = uint2(uv*sections); 78 | const float2 facetedUV = sector/(float2)sections; 79 | const float2 fractionUV = (uv-facetedUV)*sections*float2(2,1); 80 | 81 | const uint r0 = Random(sector.x); 82 | const uint r1 = Random(sector.y); 83 | const uint r2 = Random(r0+r1); 84 | const uint enable = ((r0 & 1) == (r1 & 1)) && ((sector.x % 2) == (sector.y % 3)) ? 1 : 0; 85 | const float timev = (r2%1003/1002.0f)*0.5f+0.5f; 86 | const float brightness = abs(fmod(camPosAndSceneTime.w,timev)-timev*0.5f); 87 | const float2 clr = uint2(r0,r1)%343/342.0f; 88 | 89 | const float d = pow(1-length(fractionUV-float2(0.25f,0.5f)),10) * 5.0f; 90 | return float3(clr*d*enable*brightness,0); 91 | } -------------------------------------------------------------------------------- /examples/work_graphs/materials.hlsli: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | float3 EvaluateMaterial_Lambert(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation) 24 | { 25 | return saturate(dot(-lightToPointDir, worldNormal)) * lightColor * lightAttenuation * material.baseColor; 26 | } 27 | 28 | float3 EvaluateMaterial_Phong(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 29 | { 30 | const float3 specularColor = material.param1; 31 | const float specularPower = material.param2; 32 | const float3 pointToEyeDir = normalize(viewPosition-worldPosition); // Starting from worldPosition, pointing towards camera position 33 | 34 | const float3 diffuse = EvaluateMaterial_Lambert(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation); 35 | const float3 specular = pow(saturate(dot(reflect(lightToPointDir, worldNormal), pointToEyeDir)), specularPower) * specularColor * lightColor; 36 | return diffuse + specular; 37 | } 38 | 39 | float3 EvaluateMaterial_Metallic(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 40 | { 41 | const float specularPower = 60.0f; 42 | const float3 pointToEyeDir = normalize(viewPosition-worldPosition); // Starting from worldPosition, pointing towards camera position 43 | const float3 specular = pow(saturate(dot(reflect(lightToPointDir, worldNormal), pointToEyeDir)), specularPower) * material.baseColor * lightColor; 44 | return specular; 45 | } 46 | 47 | float3 EvaluateMaterial_Velvet(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 48 | { 49 | const float roughness = material.param1.x; 50 | 51 | const float3 specularColor = sqrt(material.baseColor*0.25f); 52 | const float3 pointToEyeDir = normalize(viewPosition-worldPosition); // Starting from worldPosition, pointing towards camera position 53 | const float3 halfDir = normalize(pointToEyeDir-lightToPointDir); 54 | 55 | // Some dots 56 | const float cosNrmHalfDir = saturate(dot(worldNormal, halfDir)); 57 | const float cosNrmLightDir = saturate(dot(-lightToPointDir, worldNormal)); 58 | const float cosNrmViewDir = saturate(dot(pointToEyeDir, worldNormal)); 59 | const float cosViewHalfDir = saturate(dot(pointToEyeDir, halfDir)); 60 | 61 | float distribution; 62 | { 63 | const float roughnessSq = roughness*roughness; 64 | const float cosNrmHalfDirSq = cosNrmHalfDir*cosNrmHalfDir; 65 | const float sinNrmHalfDirSq = 1-cosNrmHalfDirSq; 66 | const float sinNrmHalfDirQd = sinNrmHalfDirSq*sinNrmHalfDirSq; 67 | distribution = saturate((sinNrmHalfDirQd + 4*exp(-cosNrmHalfDirSq/(sinNrmHalfDirSq*roughnessSq))) / (c_PI*(1+4*roughnessSq)*sinNrmHalfDirQd)); 68 | } 69 | 70 | const float v = 1/(4*(cosNrmLightDir+cosNrmViewDir-cosNrmLightDir*cosNrmViewDir)); 71 | const float3 fresnel = specularColor + (1-specularColor) * pow((1-cosViewHalfDir), 5); 72 | const float3 specular = fresnel * (distribution*v*c_PI*cosNrmLightDir) * lightColor; 73 | 74 | const float3 diffuse = EvaluateMaterial_Lambert(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation) * 0.25f; 75 | return diffuse + specular; 76 | } 77 | 78 | float3 EvaluateMaterial_Flakes(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 79 | { 80 | const float3 specularColor = material.param1; 81 | const float specularPower = material.param2; 82 | const float granularity = material.param3; 83 | const float diffusionStrength = 0.3f; 84 | const float3 pointToEyeDir = normalize(viewPosition-worldPosition); // Starting from worldPosition, pointing towards camera position 85 | 86 | const int3 flake = (int3)(worldPosition/granularity); 87 | const uint rand0 = Random(flake.x*flake.y+flake.z); 88 | const uint rand1 = Random(rand0); 89 | const uint rand2 = Random(rand1); 90 | const float3 offset = normalize(float3(rand0,rand1,rand2))*diffusionStrength; 91 | const float3 flakeWorldNormal = normalize(worldNormal+offset); 92 | 93 | const float3 diffuse = EvaluateMaterial_Lambert(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation); 94 | const float3 specular = pow(saturate(dot(reflect(lightToPointDir, worldNormal), pointToEyeDir)), specularPower) * specularColor * lightColor; 95 | const float3 specularFlakes = pow(saturate(dot(reflect(lightToPointDir, flakeWorldNormal), pointToEyeDir)), specularPower) * specularColor * lightColor; 96 | return diffuse + (specular+specularFlakes)*0.5f; 97 | } 98 | 99 | float3 EvaluateMaterial_Faceted(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 100 | { 101 | lightToPointDir = -lightToPointDir; // Make all lights point towards the object 102 | 103 | return EvaluateMaterial_Metallic(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation, viewPosition); 104 | } 105 | 106 | float3 EvaluateMaterial_Stan(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation) 107 | { 108 | const float3 linesColor = material.param1; 109 | const float linesThickness = material.param2; 110 | const float linesSpacing = material.param3; 111 | 112 | const float3 patternPos = fmod(abs(worldPosition),(float3)(linesSpacing+linesThickness)); 113 | material.baseColor = lerp(linesColor, material.baseColor, any((patternPos-linesThickness) < 0)); 114 | 115 | return EvaluateMaterial_Lambert(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation); 116 | } 117 | 118 | float3 EvaluateMaterial_Checker(Material material, float3 worldPosition, float3 worldNormal, float3 lightToPointDir, float3 lightColor, float lightAttenuation, float3 viewPosition) 119 | { 120 | const float3 baseColor2 = material.param1; 121 | const float checkerSize = material.param2; 122 | const float specularPower = material.param3; 123 | 124 | const float3 patternPos = fmod(abs(worldPosition),(float3)checkerSize*2); 125 | const bool alternate = any((patternPos.xy-checkerSize.xx) < 0) ^ ((patternPos.z-checkerSize) > 0); 126 | if (alternate) 127 | { 128 | material.baseColor = baseColor2; 129 | return EvaluateMaterial_Phong(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation, viewPosition); 130 | } 131 | else return EvaluateMaterial_Lambert(material, worldPosition, worldNormal, lightToPointDir, lightColor, lightAttenuation); 132 | } -------------------------------------------------------------------------------- /examples/work_graphs/scene.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #pragma once 24 | 25 | class Scene 26 | { 27 | public: 28 | 29 | enum class AnimType : uint32_t 30 | { 31 | AT_Static, 32 | AT_RotateY, 33 | AT_Dance, 34 | AT_COUNT 35 | }; 36 | 37 | enum class MeshType : uint32_t 38 | { 39 | MT_Plane, 40 | MT_Box, 41 | MT_Sphere, 42 | MT_COUNT 43 | }; 44 | 45 | enum class MaterialType : uint32_t 46 | { 47 | BT_Lambert, 48 | BT_Phong, 49 | BT_Metallic, 50 | BT_Velvet, 51 | BT_Flakes, 52 | BT_Faceted, 53 | BT_Stan, 54 | BT_Checker, 55 | BT_COUNT 56 | }; 57 | 58 | struct Material 59 | { 60 | struct PhongParams 61 | { 62 | dm::float3 specularColor; 63 | float specularPower; 64 | }; 65 | struct VelvetParams 66 | { 67 | float roughness; 68 | }; 69 | struct FlakesParams 70 | { 71 | dm::float3 specularColor; 72 | float specularPower; 73 | float granularity; 74 | }; 75 | struct StanParams 76 | { 77 | dm::float3 linesColor; 78 | float linesThickness; 79 | float linesSpacing; 80 | }; 81 | struct CheckerParams 82 | { 83 | dm::float3 baseColor2; 84 | float checkerSize; 85 | float specularPower; 86 | }; 87 | 88 | dm::float3 baseColor; 89 | MaterialType materialType; 90 | union 91 | { 92 | PhongParams phong; 93 | VelvetParams velvet; 94 | FlakesParams flakes; 95 | StanParams stan; 96 | CheckerParams curvature; 97 | }; 98 | }; 99 | 100 | struct Instance 101 | { 102 | dm::float3 position; 103 | float rotationY; 104 | dm::float3 size; 105 | MeshType meshType; 106 | uint32_t material; 107 | AnimType animType; 108 | }; 109 | 110 | struct Light 111 | { 112 | dm::float3 position; 113 | dm::float3 target; 114 | dm::float3 targetOffset; 115 | dm::float3 color; 116 | float innerAngle; 117 | float outerAngle; 118 | }; 119 | 120 | struct AnimState 121 | { 122 | uint32_t state; 123 | uint32_t stateRepeats; 124 | float statePeriod; 125 | float timeInState; 126 | 127 | dm::float3 scale; 128 | float rotationY; 129 | float offsetY; 130 | float twist; 131 | }; 132 | 133 | void CreateAssets(nvrhi::IDevice *device,nvrhi::ICommandList *commandList); 134 | 135 | const std::vector& GetMaterials() const { return m_materials; } 136 | const std::vector& GetWorldObjects() const { return m_worldObjects; } 137 | const std::vector& GetLights() const { return m_lights; } 138 | nvrhi::BufferHandle GetMaterialsBuffer() const { return m_materialDataBuffer; } 139 | nvrhi::BufferHandle GetWorldObjectsBuffer() const { return m_instanceDataBuffer; } 140 | nvrhi::BufferHandle GetLightsBuffer() const { return m_lightDataBuffer; } 141 | nvrhi::BufferHandle GetAnimStateBuffer() const { return m_animStateBuffer; } 142 | nvrhi::BufferHandle GetMeshVertexBuffer(MeshType meshType) const { return m_vertexBuffers[(int)meshType]; } 143 | nvrhi::BufferHandle GetMeshIndexBuffer(MeshType meshType) const { return m_indexBuffers[(int)meshType]; } 144 | 145 | static float GetSceneSize(); 146 | static float GetSceneHeight(); 147 | 148 | protected: 149 | void PopulateWorld(); 150 | 151 | nvrhi::BufferHandle m_vertexBuffers[(int)MeshType::MT_COUNT]; 152 | nvrhi::BufferHandle m_indexBuffers[(int)MeshType::MT_COUNT]; 153 | nvrhi::BufferHandle m_materialDataBuffer; 154 | nvrhi::BufferHandle m_instanceDataBuffer; 155 | nvrhi::BufferHandle m_lightDataBuffer; 156 | nvrhi::BufferHandle m_animStateBuffer; 157 | 158 | std::vector m_materials; 159 | std::vector m_worldObjects; 160 | std::vector m_lights; 161 | }; -------------------------------------------------------------------------------- /examples/work_graphs/scene_data.hlsli: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | // enum AnimType 24 | #define AT_Static 0 25 | #define AT_RotateY 1 26 | #define AT_Dance 2 27 | 28 | // enum MaterialType 29 | #define BT_Lambert 0 30 | #define BT_Phong 1 31 | #define BT_Metallic 2 32 | #define BT_Velvet 3 33 | #define BT_Flakes 4 34 | #define BT_Faceted 5 35 | #define BT_Stan 6 36 | #define BT_Checker 7 37 | #define BT_COUNT 8 38 | 39 | // Root constant buffer 40 | cbuffer SceneConstantBuffer : register(b1) 41 | { 42 | float4x4 viewProj; 43 | float4x4 viewProjInverse; 44 | float4 camPosAndSceneTime; 45 | float4 camDir; 46 | float4 viewportSizeXY; 47 | }; 48 | 49 | struct Instance 50 | { 51 | float3 position; 52 | float rotationY; 53 | float3 size; 54 | uint meshType; 55 | uint material; 56 | uint animType; 57 | }; 58 | 59 | struct Light 60 | { 61 | float3 position; 62 | float3 target; 63 | float3 targetOffset; 64 | float3 color; 65 | float innerAngle; 66 | float outerAngle; 67 | }; 68 | 69 | struct Material 70 | { 71 | float3 baseColor; 72 | uint materialType; 73 | float3 param1; 74 | float param2; 75 | float param3; 76 | }; 77 | 78 | struct AnimState 79 | { 80 | uint state; 81 | uint stateRepeats; 82 | float statePeriod; 83 | float timeInState; 84 | 85 | float3 scale; 86 | float rotationY; 87 | float offsetY; 88 | float twist; 89 | }; 90 | 91 | static const float c_PI = 3.1415926535897932384626433832795f; 92 | 93 | uint Random(uint seed) 94 | { 95 | // WangHash 96 | seed = (seed ^ 61) ^ (seed >> 16); 97 | seed *= 9; 98 | seed = seed ^ (seed >> 4); 99 | seed *= 0x27d4eb2d; 100 | seed = seed ^ (seed >> 15); 101 | return seed; 102 | } 103 | 104 | float NormalizeRandom(uint rnd) { return rnd%0x43F2EC13 / (float)(0x43F2EC12); } 105 | 106 | float3 RotateY(float3 v,float2 sinCos) 107 | { 108 | return float3(v.x*sinCos.y - v.z*sinCos.x, v.y, v.x*sinCos.x + v.z*sinCos.y); 109 | } 110 | -------------------------------------------------------------------------------- /examples/work_graphs/shaders.cfg: -------------------------------------------------------------------------------- 1 | animation.hlsl -T cs -E CSMainObjects 2 | animation.hlsl -T cs -E CSMainLights 3 | gbuffer_fill.hlsl -T vs -E VSMain 4 | gbuffer_fill.hlsl -T ps -E PSMain 5 | light_culling.hlsl -T cs -E CSMain 6 | deferred_shading.hlsl -T cs -E CSMain 7 | work_graph_broadcasting.hlsl -T lib -------------------------------------------------------------------------------- /examples/work_graphs/ver_test.hlsl: -------------------------------------------------------------------------------- 1 | [numthreads(1, 1, 1)] void main() {} -------------------------------------------------------------------------------- /examples/work_graphs/work_graphs_d3d12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/examples/work_graphs/work_graphs_d3d12.jpg -------------------------------------------------------------------------------- /feature_demo/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a 5 | # copy of this software and associated documentation files (the "Software"), 6 | # to deal in the Software without restriction, including without limitation 7 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | # and/or sell copies of the Software, and to permit persons to whom the 9 | # Software is furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | # DEALINGS IN THE SOFTWARE. 21 | 22 | 23 | add_executable(feature_demo WIN32 FeatureDemo.cpp) 24 | target_link_libraries(feature_demo donut_render donut_app donut_engine) 25 | 26 | set_target_properties(feature_demo PROPERTIES FOLDER "Donut Feature Demo") 27 | 28 | if (MSVC) 29 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /MP") 30 | endif() 31 | -------------------------------------------------------------------------------- /media/fonts/DroidSans/DroidSans-Mono.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/fonts/DroidSans/DroidSans-Mono.ttf -------------------------------------------------------------------------------- /media/fonts/OpenSans/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/fonts/OpenSans/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /media/nvidia-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/nvidia-logo.png -------------------------------------------------------------------------------- /media/rt_particles/ParticleScene.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/rt_particles/ParticleScene.bin -------------------------------------------------------------------------------- /media/rt_particles/environment-map.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/rt_particles/environment-map.dds -------------------------------------------------------------------------------- /media/rt_particles/smoke-particle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVIDIA-RTX/Donut-Samples/fd107285489d423c881c690e98197094d3663abf/media/rt_particles/smoke-particle.png -------------------------------------------------------------------------------- /media/sponza-plus.scene.json: -------------------------------------------------------------------------------- 1 | { 2 | "models": [ 3 | "glTF-Sample-Assets/Models/Sponza/glTF/Sponza.gltf", 4 | "glTF-Sample-Assets/Models/BrainStem/glTF/BrainStem.gltf" 5 | ], 6 | "graph": [ 7 | { 8 | "name": "Sponza", 9 | "model": 0 10 | }, 11 | { 12 | "name": "DancingRobot1", 13 | "model": 1, 14 | "translation": [4, 0, -0.5], 15 | "scaling": 1.2, 16 | "rotation": [0, 0.7071068, 0, -0.7071068] 17 | }, 18 | { 19 | "name": "DancingRobot2", 20 | "model": 1, 21 | "translation": [-5, 0, -0.5], 22 | "scaling": 1.2, 23 | "rotation": [0, 0.7071068, 0, 0.7071068] 24 | } 25 | ] 26 | } 27 | --------------------------------------------------------------------------------