├── .gitattributes ├── .gitignore ├── Bin ├── Assets │ ├── TuringBowl.obj │ ├── bunny.obj │ ├── dragon.obj │ ├── galileo_cross.dds │ ├── grace_cross.dds │ ├── rnl_cross.dds │ ├── stpeters_cross.dds │ └── uffizi_cross.dds ├── Bunny.bat ├── CSSpatial_H_Diff.cso ├── CSSpatial_H_Diff_S.cso ├── CSSpatial_H_Refl.cso ├── CSSpatial_H_Refl_S.cso ├── CSSpatial_V_Diff.cso ├── CSSpatial_V_Diff_S.cso ├── CSSpatial_V_Refl.cso ├── CSSpatial_V_Refl_S.cso ├── CSTemporalSS.cso ├── PSToneMap.cso ├── PSVisibility.cso ├── RayTracedGGX.exe ├── RayTracing.cso ├── TuringBowl.bat ├── VSScreenQuad.cso ├── VSVisibility.cso ├── WinPixEventRuntime.dll ├── XUSG.dll ├── XUSGRayTracing.dll ├── dxc.exe ├── dxcompiler.dll ├── dxil.dll ├── dxrfallbackcompiler.dll ├── galileo.bat ├── grace.bat ├── stpeters.bat └── uffizi.bat ├── Doc └── Images │ └── rnl_dragon.png ├── README.md ├── RayTracedGGX.sln └── RayTracedGGX ├── Common ├── D3D12RaytracingFallback.h ├── DXFramework.cpp ├── DXFramework.h ├── DXFrameworkHelper.h ├── DirectX-Graphics-Samples │ └── LICENSE ├── StepTimer.h ├── Win32Application.cpp ├── Win32Application.h ├── d3d12.h ├── d3d12 │ ├── LICENSE-CODE.txt │ └── LICENSE.txt ├── d3dcommon.h ├── dxgiformat.h ├── stb │ └── LICENSE ├── stb_image_write.cpp └── stb_image_write.h ├── Content ├── Denoiser.cpp ├── Denoiser.h ├── RayTracer.cpp ├── RayTracer.h └── Shaders │ ├── BRDFModels.hlsli │ ├── CSSpatial_H_Diff.hlsl │ ├── CSSpatial_H_Diff_S.hlsl │ ├── CSSpatial_H_Refl.hlsl │ ├── CSSpatial_H_Refl_S.hlsl │ ├── CSSpatial_V_Diff.hlsl │ ├── CSSpatial_V_Diff_S.hlsl │ ├── CSSpatial_V_Refl.hlsl │ ├── CSSpatial_V_Refl_S.hlsl │ ├── CSTemporalSS.hlsl │ ├── FilterCommon.hlsli │ ├── Material.hlsli │ ├── PSToneMap.hlsl │ ├── PSVisibility.hlsl │ ├── RayTracing.hlsl │ ├── SpatialFilter.hlsli │ ├── VSScreenQuad.hlsl │ └── VSVisibility.hlsl ├── Main.cpp ├── RayTracedGGX.cpp ├── RayTracedGGX.h ├── RayTracedGGX.vcxproj ├── RayTracedGGX.vcxproj.filters ├── RayTracedGGX.vcxproj.user ├── XUSG ├── Advanced │ └── XUSGAdvanced.h ├── Bin │ └── x64 │ │ ├── Debug │ │ ├── XUSG.dll │ │ ├── XUSG.lib │ │ ├── XUSG.pdb │ │ ├── XUSGRayTracing.dll │ │ ├── XUSGRayTracing.lib │ │ └── XUSGRayTracing.pdb │ │ └── Release │ │ ├── XUSG.dll │ │ ├── XUSG.lib │ │ ├── XUSGRayTracing.dll │ │ └── XUSGRayTracing.lib ├── Core │ └── XUSG.h ├── Optional │ ├── XUSGObjLoader.cpp │ └── XUSGObjLoader.h ├── RayTracing │ └── XUSGRayTracing.h ├── Shaders │ ├── SHIrradiance.hlsli │ └── SHIrradianceTypeless.hlsli └── Ultimate │ └── XUSGUltimate.h ├── dxc ├── LICENCE-MIT.txt ├── LICENSE-LLVM.txt └── LICENSE-MS.txt ├── stdafx.cpp └── stdafx.h /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | //*.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/* 15 | */[Dd]ebug/* 16 | [Dd]ebugPublic/ 17 | [Rr]elease/* 18 | */[Rr]elease/* 19 | [Rr]eleases/ 20 | x64/* 21 | */x64/* 22 | x86/ 23 | bld/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | artifacts/ 48 | 49 | *_i.c 50 | *_p.c 51 | *_i.h 52 | *.ilk 53 | *.iobj 54 | *.ipdb 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.res 62 | *.rsp 63 | *.sbr 64 | *.tlb 65 | *.tli 66 | *.tlh 67 | *.tmp 68 | *.tmp_proj 69 | *.log 70 | *.vspscc 71 | *.vssscc 72 | .builds 73 | *.pidb 74 | *.svclog 75 | *.scc 76 | 77 | # Chutzpah Test files 78 | _Chutzpah* 79 | 80 | # Visual C++ cache files 81 | ipch/ 82 | *.aps 83 | *.ncb 84 | *.opendb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | *.VC.db 89 | *.VC.VC.opendb 90 | 91 | # Visual Studio profiler 92 | *.psess 93 | *.vsp 94 | *.vspx 95 | *.sap 96 | 97 | # TFS 2012 Local Workspace 98 | $tf/ 99 | 100 | # Guidance Automation Toolkit 101 | *.gpState 102 | 103 | # ReSharper is a .NET coding add-in 104 | _ReSharper*/ 105 | *.[Rr]e[Ss]harper 106 | *.DotSettings.user 107 | 108 | # JustCode is a .NET coding add-in 109 | .JustCode 110 | 111 | # TeamCity is a build add-in 112 | _TeamCity* 113 | 114 | # DotCover is a Code Coverage Tool 115 | *.dotCover 116 | 117 | # NCrunch 118 | _NCrunch_* 119 | .*crunch*.local.xml 120 | nCrunchTemp_* 121 | 122 | # MightyMoose 123 | *.mm.* 124 | AutoTest.Net/ 125 | 126 | # Web workbench (sass) 127 | .sass-cache/ 128 | 129 | # Installshield output folder 130 | [Ee]xpress/ 131 | 132 | # DocProject is a documentation generator add-in 133 | DocProject/buildhelp/ 134 | DocProject/Help/*.HxT 135 | DocProject/Help/*.HxC 136 | DocProject/Help/*.hhc 137 | DocProject/Help/*.hhk 138 | DocProject/Help/*.hhp 139 | DocProject/Help/Html2 140 | DocProject/Help/html 141 | 142 | # Click-Once directory 143 | publish/ 144 | 145 | # Publish Web Output 146 | *.[Pp]ublish.xml 147 | *.azurePubxml 148 | # TODO: Comment the next line if you want to checkin your web deploy settings 149 | # but database connection strings (with potential passwords) will be unencrypted 150 | *.pubxml 151 | *.publishproj 152 | 153 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 154 | # checkin your Azure Web App publish settings, but sensitive information contained 155 | # in these scripts will be unencrypted 156 | PublishScripts/ 157 | 158 | # NuGet Packages 159 | *.nupkg 160 | # The packages folder can be ignored because of Package Restore 161 | **/packages/* 162 | # except build/, which is used as an MSBuild target. 163 | !**/packages/build/ 164 | # Uncomment if necessary however generally it will be regenerated when needed 165 | #!**/packages/repositories.config 166 | # NuGet v3's project.json files produces more ignoreable files 167 | *.nuget.props 168 | *.nuget.targets 169 | 170 | # Microsoft Azure Build Output 171 | csx/ 172 | *.build.csdef 173 | 174 | # Microsoft Azure Emulator 175 | ecf/ 176 | rcf/ 177 | 178 | # Windows Store app package directories and files 179 | AppPackages/ 180 | BundleArtifacts/ 181 | Package.StoreAssociation.xml 182 | _pkginfo.txt 183 | 184 | # Visual Studio cache files 185 | # files ending in .cache can be ignored 186 | *.[Cc]ache 187 | # but keep track of directories ending in .cache 188 | !*.[Cc]ache/ 189 | 190 | # Others 191 | ClientBin/ 192 | ~$* 193 | *~ 194 | *.dbmdl 195 | *.dbproj.schemaview 196 | *.pfx 197 | *.publishsettings 198 | node_modules/ 199 | orleans.codegen.cs 200 | 201 | # Since there are multiple workflows, uncomment next line to ignore bower_components 202 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 203 | #bower_components/ 204 | 205 | # RIA/Silverlight projects 206 | Generated_Code/ 207 | 208 | # Backup & report files from converting an old project file 209 | # to a newer Visual Studio version. Backup files are not needed, 210 | # because we have git ;-) 211 | _UpgradeReport_Files/ 212 | Backup*/ 213 | UpgradeLog*.XML 214 | UpgradeLog*.htm 215 | 216 | # SQL Server files 217 | *.mdf 218 | *.ldf 219 | 220 | # Business Intelligence projects 221 | *.rdl.data 222 | *.bim.layout 223 | *.bim_*.settings 224 | 225 | # Microsoft Fakes 226 | FakesAssemblies/ 227 | 228 | # GhostDoc plugin setting file 229 | *.GhostDoc.xml 230 | 231 | # Node.js Tools for Visual Studio 232 | .ntvs_analysis.dat 233 | 234 | # Visual Studio 6 build log 235 | *.plg 236 | 237 | # Visual Studio 6 workspace options file 238 | *.opt 239 | 240 | # Visual Studio LightSwitch build output 241 | **/*.HTMLClient/GeneratedArtifacts 242 | **/*.DesktopClient/GeneratedArtifacts 243 | **/*.DesktopClient/ModelManifest.xml 244 | **/*.Server/GeneratedArtifacts 245 | **/*.Server/ModelManifest.xml 246 | _Pvt_Extensions 247 | 248 | # Paket dependency manager 249 | .paket/paket.exe 250 | paket-files/ 251 | 252 | # FAKE - F# Make 253 | .fake/ 254 | 255 | # JetBrains Rider 256 | .idea/ 257 | *.sln.iml 258 | 259 | # ========================= 260 | # Operating System Files 261 | # ========================= 262 | 263 | # OSX 264 | # ========================= 265 | 266 | .DS_Store 267 | .AppleDouble 268 | .LSOverride 269 | 270 | # Thumbnails 271 | ._* 272 | 273 | # Files that might appear in the root of a volume 274 | .DocumentRevisions-V100 275 | .fseventsd 276 | .Spotlight-V100 277 | .TemporaryItems 278 | .Trashes 279 | .VolumeIcon.icns 280 | 281 | # Directories potentially created on remote AFP share 282 | .AppleDB 283 | .AppleDesktop 284 | Network Trash Folder 285 | Temporary Items 286 | .apdisk 287 | 288 | # Windows 289 | # ========================= 290 | 291 | # Windows image file caches 292 | Thumbs.db 293 | ehthumbs.db 294 | 295 | # Folder config file 296 | Desktop.ini 297 | 298 | # Recycle Bin used on file shares 299 | $RECYCLE.BIN/ 300 | 301 | # Windows Installer files 302 | *.cab 303 | *.msi 304 | *.msm 305 | *.msp 306 | 307 | # Windows shortcuts 308 | *.lnk 309 | 310 | !XUSG*.pdb 311 | !FallbackLayer.pdb 312 | !Bin/*/*.[Oo]bj 313 | -------------------------------------------------------------------------------- /Bin/Assets/galileo_cross.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/Assets/galileo_cross.dds -------------------------------------------------------------------------------- /Bin/Assets/grace_cross.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/Assets/grace_cross.dds -------------------------------------------------------------------------------- /Bin/Assets/rnl_cross.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/Assets/rnl_cross.dds -------------------------------------------------------------------------------- /Bin/Assets/stpeters_cross.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/Assets/stpeters_cross.dds -------------------------------------------------------------------------------- /Bin/Assets/uffizi_cross.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/Assets/uffizi_cross.dds -------------------------------------------------------------------------------- /Bin/Bunny.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -mesh Assets/bunny.obj 0.0 0.0 0.0 1.0 2 | -------------------------------------------------------------------------------- /Bin/CSSpatial_H_Diff.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_H_Diff.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_H_Diff_S.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_H_Diff_S.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_H_Refl.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_H_Refl.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_H_Refl_S.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_H_Refl_S.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_V_Diff.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_V_Diff.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_V_Diff_S.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_V_Diff_S.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_V_Refl.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_V_Refl.cso -------------------------------------------------------------------------------- /Bin/CSSpatial_V_Refl_S.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSSpatial_V_Refl_S.cso -------------------------------------------------------------------------------- /Bin/CSTemporalSS.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/CSTemporalSS.cso -------------------------------------------------------------------------------- /Bin/PSToneMap.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/PSToneMap.cso -------------------------------------------------------------------------------- /Bin/PSVisibility.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/PSVisibility.cso -------------------------------------------------------------------------------- /Bin/RayTracedGGX.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/RayTracedGGX.exe -------------------------------------------------------------------------------- /Bin/RayTracing.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/RayTracing.cso -------------------------------------------------------------------------------- /Bin/TuringBowl.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -mesh Assets/TuringBowl.obj 0.0 2.8 0.0 0.03 2 | -------------------------------------------------------------------------------- /Bin/VSScreenQuad.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/VSScreenQuad.cso -------------------------------------------------------------------------------- /Bin/VSVisibility.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/VSVisibility.cso -------------------------------------------------------------------------------- /Bin/WinPixEventRuntime.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/WinPixEventRuntime.dll -------------------------------------------------------------------------------- /Bin/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/XUSG.dll -------------------------------------------------------------------------------- /Bin/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/XUSGRayTracing.dll -------------------------------------------------------------------------------- /Bin/dxc.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/dxc.exe -------------------------------------------------------------------------------- /Bin/dxcompiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/dxcompiler.dll -------------------------------------------------------------------------------- /Bin/dxil.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/dxil.dll -------------------------------------------------------------------------------- /Bin/dxrfallbackcompiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Bin/dxrfallbackcompiler.dll -------------------------------------------------------------------------------- /Bin/galileo.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -env Assets/galileo_cross.dds 2 | -------------------------------------------------------------------------------- /Bin/grace.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -env Assets/grace_cross.dds 2 | -------------------------------------------------------------------------------- /Bin/stpeters.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -env Assets/stpeters_cross.dds 2 | -------------------------------------------------------------------------------- /Bin/uffizi.bat: -------------------------------------------------------------------------------- 1 | start RayTracedGGX.exe -env Assets/uffizi_cross.dds 2 | -------------------------------------------------------------------------------- /Doc/Images/rnl_dragon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/Doc/Images/rnl_dragon.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RayTracedGGX 2 | Ray tracing sample using GGX reflection model, 1spp with spatial-temporal denoiser. Acceleration structure build uses async compute. 3 | 4 | ![RayTraceGGX result dragon](https://github.com/StarsX/RayTracedGGX/blob/master/Doc/Images/rnl_dragon.png "rnl_dragon") 5 | 6 | Hot keys: 7 | 8 | [Space] pause/play animation 9 | 10 | [V] switch spatial denoiser paths 11 | 12 | Prerequisite: https://github.com/StarsX/XUSG 13 | -------------------------------------------------------------------------------- /RayTracedGGX.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.106 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RayTracedGGX", "RayTracedGGX\RayTracedGGX.vcxproj", "{12876612-F1E8-4F22-86F7-699505458AF8}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Release|x64 = Release|x64 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {12876612-F1E8-4F22-86F7-699505458AF8}.Debug|x64.ActiveCfg = Debug|x64 15 | {12876612-F1E8-4F22-86F7-699505458AF8}.Debug|x64.Build.0 = Debug|x64 16 | {12876612-F1E8-4F22-86F7-699505458AF8}.Release|x64.ActiveCfg = Release|x64 17 | {12876612-F1E8-4F22-86F7-699505458AF8}.Release|x64.Build.0 = Release|x64 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {F680BF24-7B0B-4E9C-8581-FAC1E0D1D622} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/D3D12RaytracingFallback.h: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // D3D12RaytracingFallback.h // 4 | // // 5 | // Provides a simplified interface for the DX12 Ray Tracing interface that // 6 | // will use native DX12 ray tracing when available. For drivers that do not // 7 | // support ray tracing, a fallback compute-shader based solution will be // 8 | // used instead. // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////// 11 | 12 | #pragma once 13 | 14 | struct EMULATED_GPU_POINTER 15 | { 16 | UINT32 OffsetInBytes; 17 | UINT32 DescriptorHeapIndex; 18 | }; 19 | 20 | struct WRAPPED_GPU_POINTER 21 | { 22 | union 23 | { 24 | EMULATED_GPU_POINTER EmulatedGpuPtr; 25 | D3D12_GPU_VIRTUAL_ADDRESS GpuVA; 26 | }; 27 | 28 | WRAPPED_GPU_POINTER operator+(UINT64 offset) 29 | { 30 | WRAPPED_GPU_POINTER pointer = *this; 31 | pointer.GpuVA += offset; 32 | return pointer; 33 | } 34 | }; 35 | 36 | typedef struct D3D12_RAYTRACING_FALLBACK_INSTANCE_DESC 37 | { 38 | FLOAT Transform[3][4]; 39 | UINT InstanceID : 24; 40 | UINT InstanceMask : 8; 41 | UINT InstanceContributionToHitGroupIndex : 24; 42 | UINT Flags : 8; 43 | WRAPPED_GPU_POINTER AccelerationStructure; 44 | } D3D12_RAYTRACING_FALLBACK_INSTANCE_DESC; 45 | 46 | class 47 | _declspec(uuid("539e5c40-df25-4c7d-81d8-6537f54306ed")) 48 | ID3D12RaytracingFallbackStateObject : public IUnknown 49 | { 50 | public: 51 | virtual ~ID3D12RaytracingFallbackStateObject() {}; 52 | 53 | virtual void *STDMETHODCALLTYPE GetShaderIdentifier( 54 | _In_ LPCWSTR pExportName) = 0; 55 | 56 | virtual UINT64 STDMETHODCALLTYPE GetShaderStackSize( 57 | _In_ LPCWSTR pExportName) = 0; 58 | 59 | virtual UINT64 STDMETHODCALLTYPE GetPipelineStackSize(void) = 0; 60 | 61 | virtual void STDMETHODCALLTYPE SetPipelineStackSize( 62 | UINT64 PipelineStackSizeInBytes) = 0; 63 | 64 | virtual ID3D12StateObject *GetStateObject() = 0; 65 | }; 66 | 67 | class 68 | _declspec(uuid("348a2a6b-6760-4b78-a9a7-1758b6f78d46")) 69 | ID3D12RaytracingFallbackCommandList : public IUnknown 70 | { 71 | public: 72 | virtual ~ID3D12RaytracingFallbackCommandList() {} 73 | 74 | virtual void BuildRaytracingAccelerationStructure( 75 | _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC *pDesc, 76 | _In_ UINT NumPostbuildInfoDescs, 77 | _In_reads_opt_(NumPostbuildInfoDescs) const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC *pPostbuildInfoDescs, 78 | _In_ UINT NumUAVs) = 0; 79 | 80 | virtual void STDMETHODCALLTYPE EmitRaytracingAccelerationStructurePostbuildInfo( 81 | _In_ const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC *pDesc, 82 | _In_ UINT NumSourceAccelerationStructures, 83 | _In_reads_(NumSourceAccelerationStructures) const D3D12_GPU_VIRTUAL_ADDRESS *pSourceAccelerationStructureData, 84 | _In_ UINT NumUAVs) = 0; 85 | 86 | virtual void STDMETHODCALLTYPE CopyRaytracingAccelerationStructure( 87 | _In_ D3D12_GPU_VIRTUAL_ADDRESS DestAccelerationStructureData, 88 | _In_ D3D12_GPU_VIRTUAL_ADDRESS SourceAccelerationStructureData, 89 | _In_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE Mode, 90 | _In_ UINT NumUAVs) = 0; 91 | 92 | virtual void STDMETHODCALLTYPE SetDescriptorHeaps( 93 | _In_ UINT NumDescriptorHeaps, 94 | _In_reads_(NumDescriptorHeaps) ID3D12DescriptorHeap *const *ppDescriptorHeaps) = 0; 95 | 96 | virtual void STDMETHODCALLTYPE SetTopLevelAccelerationStructure( 97 | _In_ UINT RootParameterIndex, 98 | _In_ WRAPPED_GPU_POINTER BufferLocation) = 0; 99 | 100 | virtual void STDMETHODCALLTYPE SetPipelineState1( 101 | _In_ ID3D12RaytracingFallbackStateObject *pStateObject) = 0; 102 | 103 | virtual void STDMETHODCALLTYPE DispatchRays( 104 | _In_ const D3D12_DISPATCH_RAYS_DESC *pDesc) = 0; 105 | }; 106 | 107 | class 108 | _declspec(uuid("0a662ea0-ab43-423a-848f-4824ae4b25ba")) 109 | ID3D12RaytracingFallbackDevice : public IUnknown 110 | { 111 | public: 112 | virtual ~ID3D12RaytracingFallbackDevice() {}; 113 | 114 | virtual bool UsingRaytracingDriver() = 0; 115 | 116 | // Automatically determine how to create WRAPPED_GPU_POINTER based on UsingRaytracingDriver() 117 | virtual WRAPPED_GPU_POINTER GetWrappedPointerSimple(UINT32 DescriptorHeapIndex, D3D12_GPU_VIRTUAL_ADDRESS GpuVA) = 0; 118 | 119 | // Pre-condition: UsingRaytracingDriver() must be false 120 | virtual WRAPPED_GPU_POINTER GetWrappedPointerFromDescriptorHeapIndex(UINT32 DescriptorHeapIndex, UINT32 OffsetInBytes = 0) = 0; 121 | 122 | // Pre-condition: UsingRaytracingDriver() must be true 123 | virtual WRAPPED_GPU_POINTER GetWrappedPointerFromGpuVA(D3D12_GPU_VIRTUAL_ADDRESS gpuVA) = 0; 124 | 125 | virtual D3D12_RESOURCE_STATES GetAccelerationStructureResourceState() = 0; 126 | 127 | virtual UINT STDMETHODCALLTYPE GetShaderIdentifierSize(void) = 0; 128 | 129 | virtual HRESULT STDMETHODCALLTYPE CreateStateObject( 130 | const D3D12_STATE_OBJECT_DESC *pDesc, 131 | REFIID riid, 132 | _COM_Outptr_ void **ppStateObject) = 0; 133 | 134 | virtual void STDMETHODCALLTYPE GetRaytracingAccelerationStructurePrebuildInfo( 135 | _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS *pDesc, 136 | _Out_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO *pInfo, 137 | _In_ UINT NumUAVs) = 0; 138 | 139 | virtual void QueryRaytracingCommandList( 140 | ID3D12GraphicsCommandList *pCommandList, 141 | REFIID riid, 142 | _COM_Outptr_ void **ppRaytracingCommandList) = 0; 143 | 144 | virtual HRESULT STDMETHODCALLTYPE CreateRootSignature( 145 | _In_ UINT nodeMask, 146 | _In_reads_(blobLengthInBytes) const void *pBlobWithRootSignature, 147 | _In_ SIZE_T blobLengthInBytes, 148 | REFIID riid, 149 | _COM_Outptr_ void **ppvRootSignature) = 0; 150 | 151 | virtual HRESULT D3D12SerializeVersionedRootSignature( 152 | _In_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* pRootSignature, 153 | _Out_ ID3DBlob** ppBlob, 154 | _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob, 155 | _In_ UINT numUAVs, _In_ UINT numCBVs = 0) = 0; 156 | 157 | virtual HRESULT WINAPI D3D12SerializeRootSignature( 158 | _In_ const D3D12_ROOT_SIGNATURE_DESC* pRootSignature, 159 | _In_ D3D_ROOT_SIGNATURE_VERSION Version, 160 | _Out_ ID3DBlob** ppBlob, 161 | _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob, 162 | _In_ UINT numUAVs, _In_ UINT numCBVs = 0) = 0; 163 | }; 164 | 165 | enum CreateRaytracingFallbackDeviceFlags 166 | { 167 | None = 0x0, 168 | ForceComputeFallback = 0x1, 169 | EnableRootDescriptorsInShaderRecords = 0x2 170 | }; 171 | 172 | HRESULT D3D12CreateRaytracingFallbackDevice( 173 | _In_ ID3D12Device *pDevice, 174 | _In_ DWORD createRaytracingFallbackDeviceFlags, 175 | _In_ UINT NodeMask, 176 | _In_ REFIID riid, 177 | _COM_Outptr_opt_ void** ppDevice); -------------------------------------------------------------------------------- /RayTracedGGX/Common/DXFramework.cpp: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #include "DXFramework.h" 13 | 14 | using namespace Microsoft::WRL; 15 | 16 | DXFramework::DXFramework(uint32_t width, uint32_t height, std::wstring name) : 17 | m_width(width), 18 | m_height(height), 19 | m_title(name) 20 | { 21 | WCHAR assetsPath[512]; 22 | GetAssetsPath(assetsPath, _countof(assetsPath)); 23 | m_assetsPath = assetsPath; 24 | 25 | m_aspectRatio = static_cast(width) / static_cast(height); 26 | } 27 | 28 | DXFramework::~DXFramework() 29 | { 30 | } 31 | 32 | // Helper function for resolving the full path of assets. 33 | std::wstring DXFramework::GetAssetFullPath(LPCWSTR assetName) 34 | { 35 | return m_assetsPath + assetName; 36 | } 37 | 38 | // Helper function for acquiring the first available hardware adapter that supports Direct3D 12. 39 | // If no such adapter can be found, *ppAdapter will be set to nullptr. 40 | _Use_decl_annotations_ 41 | void DXFramework::GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter) 42 | { 43 | ComPtr adapter; 44 | *ppAdapter = nullptr; 45 | 46 | for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex) 47 | { 48 | DXGI_ADAPTER_DESC1 desc; 49 | adapter->GetDesc1(&desc); 50 | 51 | if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) 52 | { 53 | // Don't select the Basic Render Driver adapter. 54 | // If you want a software adapter, pass in "/warp" on the command line. 55 | continue; 56 | } 57 | 58 | // Check to see if the adapter supports Direct3D 12, but don't create the 59 | // actual device yet. 60 | if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) 61 | { 62 | break; 63 | } 64 | } 65 | 66 | *ppAdapter = adapter.Detach(); 67 | } 68 | 69 | // Helper function for setting the window's title text. 70 | void DXFramework::SetCustomWindowText(LPCWSTR text) 71 | { 72 | std::wstring windowText = m_title + L": " + text; 73 | SetWindowText(Win32Application::GetHwnd(), windowText.c_str()); 74 | } 75 | 76 | // Helper function for parsing any supplied command line args. 77 | _Use_decl_annotations_ 78 | void DXFramework::ParseCommandLineArgs(WCHAR* argv[], int argc) 79 | { 80 | } 81 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/DXFramework.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #pragma once 13 | 14 | #include "DXFrameworkHelper.h" 15 | #include "Win32Application.h" 16 | 17 | class DXFramework 18 | { 19 | public: 20 | DXFramework(uint32_t width, uint32_t height, std::wstring name); 21 | virtual ~DXFramework(); 22 | 23 | virtual void OnInit() = 0; 24 | virtual void OnUpdate() = 0; 25 | virtual void OnRender() = 0; 26 | virtual void OnDestroy() = 0; 27 | 28 | virtual void OnSuspending() {} 29 | virtual void OnResuming() {} 30 | virtual void OnWindowMoved() {} 31 | virtual void OnWindowSizeChanged(int width, int height) {} 32 | 33 | // Samples override the event handlers to handle specific messages. 34 | virtual void OnKeyDown(uint8_t /*key*/) {} 35 | virtual void OnKeyUp(uint8_t /*key*/) {} 36 | 37 | virtual void OnLButtonDown(float posX, float posY) {} 38 | virtual void OnLButtonUp(float posX, float posY) {} 39 | virtual void OnRButtonDown(float posX, float posY) {} 40 | virtual void OnRButtonUp(float posX, float posY) {} 41 | virtual void OnMouseMove(float posX, float posY) {} 42 | virtual void OnMouseWheel(float deltaZ, float posX, float posY) {} 43 | virtual void OnMouseLeave() {} 44 | 45 | // Accessors. 46 | uint32_t GetWidth() const { return m_width; } 47 | uint32_t GetHeight() const { return m_height; } 48 | const WCHAR* GetTitle() const { return m_title.c_str(); } 49 | 50 | virtual void ParseCommandLineArgs(_In_reads_(argc) WCHAR* argv[], int argc); 51 | 52 | protected: 53 | std::wstring GetAssetFullPath(LPCWSTR assetName); 54 | void GetHardwareAdapter(_In_ IDXGIFactory2* pFactory, _Outptr_result_maybenull_ IDXGIAdapter1** ppAdapter); 55 | void SetCustomWindowText(LPCWSTR text); 56 | 57 | // Viewport dimensions. 58 | uint32_t m_width; 59 | uint32_t m_height; 60 | float m_aspectRatio; 61 | 62 | // Window title. 63 | std::wstring m_title; 64 | 65 | private: 66 | // Root assets path. 67 | std::wstring m_assetsPath; 68 | }; 69 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/DXFrameworkHelper.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #pragma once 13 | 14 | // Note that while ComPtr is used to manage the lifetime of resources on the CPU, 15 | // it has no understanding of the lifetime of resources on the GPU. Apps must account 16 | // for the GPU lifetime of resources to avoid destroying objects that may still be 17 | // referenced by the GPU. 18 | using Microsoft::WRL::ComPtr; 19 | 20 | inline std::string HrToString(HRESULT hr) 21 | { 22 | char s_str[64] = {}; 23 | sprintf_s(s_str, "HRESULT of 0x%08X", static_cast(hr)); 24 | return std::string(s_str); 25 | } 26 | 27 | class HrException : public std::runtime_error 28 | { 29 | public: 30 | HrException(HRESULT hr) : std::runtime_error(HrToString(hr)), m_hr(hr) {} 31 | HRESULT Error() const { return m_hr; } 32 | private: 33 | const HRESULT m_hr; 34 | }; 35 | 36 | #define SAFE_RELEASE(p) if (p) (p)->Release() 37 | 38 | inline void ThrowIfFailed(HRESULT hr) 39 | { 40 | if (FAILED(hr)) 41 | { 42 | throw HrException(hr); 43 | } 44 | } 45 | 46 | inline void GetAssetsPath(_Out_writes_(pathSize) WCHAR* path, UINT pathSize) 47 | { 48 | if (path == nullptr) 49 | { 50 | throw std::exception(); 51 | } 52 | 53 | DWORD size = GetModuleFileName(nullptr, path, pathSize); 54 | if (size == 0 || size == pathSize) 55 | { 56 | // Method failed or path was truncated. 57 | throw std::exception(); 58 | } 59 | 60 | WCHAR* lastSlash = wcsrchr(path, L'\\'); 61 | if (lastSlash) 62 | { 63 | *(lastSlash + 1) = L'\0'; 64 | } 65 | } 66 | 67 | inline HRESULT ReadDataFromFile(LPCWSTR filename, byte** data, UINT* size) 68 | { 69 | using namespace Microsoft::WRL; 70 | 71 | CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {}; 72 | extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); 73 | extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; 74 | extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN; 75 | extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; 76 | extendedParams.lpSecurityAttributes = nullptr; 77 | extendedParams.hTemplateFile = nullptr; 78 | 79 | Wrappers::FileHandle file(CreateFile2(filename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extendedParams)); 80 | if (file.Get() == INVALID_HANDLE_VALUE) 81 | { 82 | throw std::exception(); 83 | } 84 | 85 | FILE_STANDARD_INFO fileInfo = {}; 86 | if (!GetFileInformationByHandleEx(file.Get(), FileStandardInfo, &fileInfo, sizeof(fileInfo))) 87 | { 88 | throw std::exception(); 89 | } 90 | 91 | if (fileInfo.EndOfFile.HighPart != 0) 92 | { 93 | throw std::exception(); 94 | } 95 | 96 | *data = reinterpret_cast(malloc(fileInfo.EndOfFile.LowPart)); 97 | *size = fileInfo.EndOfFile.LowPart; 98 | 99 | if (!ReadFile(file.Get(), *data, fileInfo.EndOfFile.LowPart, nullptr, nullptr)) 100 | { 101 | throw std::exception(); 102 | } 103 | 104 | return S_OK; 105 | } 106 | 107 | // Assign a name to the object to aid with debugging. 108 | #if defined(_DEBUG) || defined(DBG) 109 | inline void SetName(ID3D12Object* pObject, LPCWSTR name) 110 | { 111 | pObject->SetName(name); 112 | } 113 | inline void SetNameIndexed(ID3D12Object* pObject, LPCWSTR name, UINT index) 114 | { 115 | WCHAR fullName[50]; 116 | if (swprintf_s(fullName, L"%s[%u]", name, index) > 0) 117 | { 118 | pObject->SetName(fullName); 119 | } 120 | } 121 | #else 122 | inline void SetName(ID3D12Object*, LPCWSTR) 123 | { 124 | } 125 | inline void SetNameIndexed(ID3D12Object*, LPCWSTR, UINT) 126 | { 127 | } 128 | #endif 129 | 130 | // Naming helper for ComPtr. 131 | // Assigns the name of the variable as the name of the object. 132 | // The indexed variant will include the index in the name of the object. 133 | #define NAME_D3D12_OBJECT(x) SetName((x).Get(), L#x) 134 | #define NAME_D3D12_OBJECT_INDEXED(x, n) SetNameIndexed((x)[n].Get(), L#x, n) 135 | 136 | inline UINT CalculateConstantBufferByteSize(UINT byteSize) 137 | { 138 | // Constant buffer size is required to be aligned. 139 | return (byteSize + (D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1)) & ~(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1); 140 | } 141 | 142 | #ifdef D3D_COMPILE_STANDARD_FILE_INCLUDE 143 | inline Microsoft::WRL::ComPtr CompileShader( 144 | const std::wstring& filename, 145 | const D3D_SHADER_MACRO* defines, 146 | const std::string& entrypoint, 147 | const std::string& target) 148 | { 149 | UINT compileFlags = 0; 150 | #if defined(_DEBUG) || defined(DBG) 151 | compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; 152 | #endif 153 | 154 | HRESULT hr; 155 | 156 | Microsoft::WRL::ComPtr byteCode = nullptr; 157 | Microsoft::WRL::ComPtr errors; 158 | hr = D3DCompileFromFile(filename.c_str(), defines, D3D_COMPILE_STANDARD_FILE_INCLUDE, 159 | entrypoint.c_str(), target.c_str(), compileFlags, 0, &byteCode, &errors); 160 | 161 | if (errors != nullptr) 162 | { 163 | OutputDebugStringA((char*)errors->GetBufferPointer()); 164 | } 165 | ThrowIfFailed(hr); 166 | 167 | return byteCode; 168 | } 169 | #endif 170 | 171 | // Resets all elements in a ComPtr array. 172 | template 173 | void ResetComPtrArray(T* comPtrArray) 174 | { 175 | for (auto &i : *comPtrArray) 176 | { 177 | i.Reset(); 178 | } 179 | } 180 | 181 | 182 | // Resets all elements in a unique_ptr array. 183 | template 184 | void ResetUniquePtrArray(T* uniquePtrArray) 185 | { 186 | for (auto &i : *uniquePtrArray) 187 | { 188 | i.reset(); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/DirectX-Graphics-Samples/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Microsoft 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/StepTimer.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #pragma once 13 | 14 | // Helper class for animation and simulation timing. 15 | class StepTimer 16 | { 17 | public: 18 | StepTimer() : 19 | m_elapsedTicks(0), 20 | m_totalTicks(0), 21 | m_leftOverTicks(0), 22 | m_frameCount(0), 23 | m_framesPerSecond(0), 24 | m_framesThisSecond(0), 25 | m_qpcSecondCounter(0), 26 | m_isFixedTimeStep(false), 27 | m_targetElapsedTicks(TicksPerSecond / 60) 28 | { 29 | QueryPerformanceFrequency(&m_qpcFrequency); 30 | QueryPerformanceCounter(&m_qpcLastTime); 31 | 32 | // Initialize max delta to a second. 33 | m_qpcMaxDelta = m_qpcFrequency.QuadPart; 34 | } 35 | 36 | // Get elapsed time since the previous Update call. 37 | UINT64 GetElapsedTicks() const { return m_elapsedTicks; } 38 | double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } 39 | 40 | // Get total time since the start of the program. 41 | UINT64 GetTotalTicks() const { return m_totalTicks; } 42 | double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } 43 | 44 | // Get total number of updates since start of the program. 45 | UINT32 GetFrameCount() const { return m_frameCount; } 46 | 47 | // Get the current framerate. 48 | UINT32 GetFramesPerSecond() const { return m_framesPerSecond; } 49 | 50 | // Set whether to use fixed or variable timestep mode. 51 | void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } 52 | 53 | // Set how often to call Update when in fixed timestep mode. 54 | void SetTargetElapsedTicks(UINT64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } 55 | void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } 56 | 57 | // Integer format represents time using 10,000,000 ticks per second. 58 | static const UINT64 TicksPerSecond = 10000000; 59 | 60 | static double TicksToSeconds(UINT64 ticks) { return static_cast(ticks) / TicksPerSecond; } 61 | static UINT64 SecondsToTicks(double seconds) { return static_cast(seconds * TicksPerSecond); } 62 | 63 | // After an intentional timing discontinuity (for instance a blocking IO operation) 64 | // call this to avoid having the fixed timestep logic attempt a set of catch-up 65 | // Update calls. 66 | 67 | void ResetElapsedTime() 68 | { 69 | QueryPerformanceCounter(&m_qpcLastTime); 70 | 71 | m_leftOverTicks = 0; 72 | m_framesPerSecond = 0; 73 | m_framesThisSecond = 0; 74 | m_qpcSecondCounter = 0; 75 | } 76 | 77 | typedef void(*LPUPDATEFUNC) (void); 78 | 79 | // Update timer state, calling the specified Update function the appropriate number of times. 80 | void Tick(LPUPDATEFUNC update = nullptr) 81 | { 82 | // Query the current time. 83 | LARGE_INTEGER currentTime; 84 | 85 | QueryPerformanceCounter(¤tTime); 86 | 87 | UINT64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; 88 | 89 | m_qpcLastTime = currentTime; 90 | m_qpcSecondCounter += timeDelta; 91 | 92 | // Clamp excessively large time deltas (e.g. after paused in the debugger). 93 | if (timeDelta > m_qpcMaxDelta) 94 | { 95 | timeDelta = m_qpcMaxDelta; 96 | } 97 | 98 | // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. 99 | timeDelta *= TicksPerSecond; 100 | timeDelta /= m_qpcFrequency.QuadPart; 101 | 102 | UINT32 lastFrameCount = m_frameCount; 103 | 104 | if (m_isFixedTimeStep) 105 | { 106 | // Fixed timestep update logic 107 | 108 | // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp 109 | // the clock to exactly match the target value. This prevents tiny and irrelevant errors 110 | // from accumulating over time. Without this clamping, a game that requested a 60 fps 111 | // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually 112 | // accumulate enough tiny errors that it would drop a frame. It is better to just round 113 | // small deviations down to zero to leave things running smoothly. 114 | 115 | if (abs(static_cast(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) 116 | { 117 | timeDelta = m_targetElapsedTicks; 118 | } 119 | 120 | m_leftOverTicks += timeDelta; 121 | 122 | while (m_leftOverTicks >= m_targetElapsedTicks) 123 | { 124 | m_elapsedTicks = m_targetElapsedTicks; 125 | m_totalTicks += m_targetElapsedTicks; 126 | m_leftOverTicks -= m_targetElapsedTicks; 127 | m_frameCount++; 128 | 129 | if (update) 130 | { 131 | update(); 132 | } 133 | } 134 | } 135 | else 136 | { 137 | // Variable timestep update logic. 138 | m_elapsedTicks = timeDelta; 139 | m_totalTicks += timeDelta; 140 | m_leftOverTicks = 0; 141 | m_frameCount++; 142 | 143 | if (update) 144 | { 145 | update(); 146 | } 147 | } 148 | 149 | // Track the current framerate. 150 | if (m_frameCount != lastFrameCount) 151 | { 152 | m_framesThisSecond++; 153 | } 154 | 155 | if (m_qpcSecondCounter >= static_cast(m_qpcFrequency.QuadPart)) 156 | { 157 | m_framesPerSecond = m_framesThisSecond; 158 | m_framesThisSecond = 0; 159 | m_qpcSecondCounter %= m_qpcFrequency.QuadPart; 160 | } 161 | } 162 | 163 | private: 164 | // Source timing data uses QPC units. 165 | LARGE_INTEGER m_qpcFrequency; 166 | LARGE_INTEGER m_qpcLastTime; 167 | UINT64 m_qpcMaxDelta; 168 | 169 | // Derived timing data uses a canonical tick format. 170 | UINT64 m_elapsedTicks; 171 | UINT64 m_totalTicks; 172 | UINT64 m_leftOverTicks; 173 | 174 | // Members for tracking the framerate. 175 | UINT32 m_frameCount; 176 | UINT32 m_framesPerSecond; 177 | UINT32 m_framesThisSecond; 178 | UINT64 m_qpcSecondCounter; 179 | 180 | // Members for configuring fixed timestep mode. 181 | bool m_isFixedTimeStep; 182 | UINT64 m_targetElapsedTicks; 183 | }; 184 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/Win32Application.cpp: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #include 13 | #include "Win32Application.h" 14 | 15 | HWND Win32Application::m_hwnd = nullptr; 16 | 17 | int Win32Application::Run(DXFramework *pFramework, HINSTANCE hInstance, int nCmdShow, HICON hIcon) 18 | { 19 | // Parse the command line parameters 20 | int argc; 21 | const auto argv = CommandLineToArgvW(GetCommandLineW(), &argc); 22 | pFramework->ParseCommandLineArgs(argv, argc); 23 | LocalFree(argv); 24 | 25 | // Initialize the window class. 26 | WNDCLASSEX windowClass = { 0 }; 27 | windowClass.cbSize = sizeof(WNDCLASSEX); 28 | windowClass.style = CS_HREDRAW | CS_VREDRAW; 29 | windowClass.lpfnWndProc = WindowProc; 30 | windowClass.hInstance = hInstance; 31 | windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); 32 | windowClass.lpszClassName = L"DXFrameworkClass"; 33 | RegisterClassEx(&windowClass); 34 | 35 | RECT windowRect = { 0, 0, static_cast(pFramework->GetWidth()), static_cast(pFramework->GetHeight()) }; 36 | AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE); 37 | 38 | // Create the window and store a handle to it. 39 | m_hwnd = CreateWindow( 40 | windowClass.lpszClassName, 41 | pFramework->GetTitle(), 42 | WS_OVERLAPPEDWINDOW, 43 | CW_USEDEFAULT, 44 | CW_USEDEFAULT, 45 | windowRect.right - windowRect.left, 46 | windowRect.bottom - windowRect.top, 47 | nullptr, // We have no parent window. 48 | nullptr, // We aren't using menus. 49 | hInstance, 50 | pFramework); 51 | 52 | if (hIcon) 53 | { 54 | SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon); 55 | SendMessage(m_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon); 56 | } 57 | 58 | // Initialize the sample. OnInit is defined in each child-implementation of DXSample. 59 | pFramework->OnInit(); 60 | 61 | ShowWindow(m_hwnd, nCmdShow); 62 | 63 | // Main sample loop. 64 | MSG msg = {}; 65 | while (msg.message != WM_QUIT) 66 | { 67 | // Process any messages in the queue. 68 | if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) 69 | { 70 | TranslateMessage(&msg); 71 | DispatchMessage(&msg); 72 | } 73 | } 74 | 75 | pFramework->OnDestroy(); 76 | 77 | // Return this part of the WM_QUIT message to Windows. 78 | return static_cast(msg.wParam); 79 | } 80 | 81 | // Main message handler for the sample. 82 | LRESULT CALLBACK Win32Application::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) 83 | { 84 | static bool s_in_sizemove = false; 85 | static bool s_in_suspend = false; 86 | static bool s_minimized = false; 87 | static bool s_fullscreen = false; 88 | // Set s_fullscreen to true if defaulting to fullscreen. 89 | 90 | static uint32_t s_width = 0; 91 | static uint32_t s_height = 0; 92 | 93 | const auto pFramework = reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); 94 | 95 | switch (message) 96 | { 97 | case WM_CREATE: 98 | { 99 | // Save the DXSample* passed in to CreateWindow. 100 | LPCREATESTRUCT pCreateStruct = reinterpret_cast(lParam); 101 | SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast(pCreateStruct->lpCreateParams)); 102 | } 103 | return 0; 104 | 105 | case WM_MOVE: 106 | if (pFramework) 107 | pFramework->OnWindowMoved(); 108 | return 0; 109 | 110 | case WM_SIZE: 111 | if (wParam == SIZE_MINIMIZED) 112 | { 113 | if (!s_minimized) 114 | { 115 | s_minimized = true; 116 | if (!s_in_suspend && pFramework) 117 | pFramework->OnSuspending(); 118 | s_in_suspend = true; 119 | } 120 | } 121 | else if (s_minimized) 122 | { 123 | s_minimized = false; 124 | if (s_in_suspend && pFramework) 125 | pFramework->OnResuming(); 126 | s_in_suspend = false; 127 | } 128 | else if (!s_in_sizemove && pFramework) 129 | { 130 | s_width = LOWORD(lParam); 131 | s_height = HIWORD(lParam); 132 | pFramework->OnWindowSizeChanged(s_width, s_height); 133 | } 134 | return 0; 135 | 136 | case WM_ENTERSIZEMOVE: 137 | s_in_sizemove = true; 138 | return 0; 139 | 140 | case WM_EXITSIZEMOVE: 141 | s_in_sizemove = false; 142 | if (pFramework) 143 | { 144 | RECT rc; 145 | GetClientRect(hWnd, &rc); 146 | 147 | const auto w = rc.right - rc.left; 148 | const auto h = rc.bottom - rc.top; 149 | 150 | if (s_width != w || s_height != h) 151 | { 152 | pFramework->OnWindowSizeChanged(w, h); 153 | s_width = w; 154 | s_height = h; 155 | } 156 | } 157 | return 0; 158 | 159 | case WM_KEYDOWN: 160 | if (pFramework) pFramework->OnKeyDown(static_cast(wParam)); 161 | return 0; 162 | 163 | case WM_KEYUP: 164 | if (pFramework) pFramework->OnKeyUp(static_cast(wParam)); 165 | return 0; 166 | 167 | case WM_LBUTTONDOWN: 168 | if (pFramework) 169 | pFramework->OnLButtonDown(static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 170 | return 0; 171 | 172 | case WM_LBUTTONUP: 173 | if (pFramework) 174 | pFramework->OnLButtonUp(static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 175 | return 0; 176 | 177 | case WM_RBUTTONDOWN: 178 | if (pFramework) 179 | pFramework->OnRButtonDown(static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 180 | return 0; 181 | 182 | case WM_RBUTTONUP: 183 | if (pFramework) 184 | pFramework->OnRButtonUp(static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 185 | return 0; 186 | 187 | case WM_MOUSEMOVE: 188 | if (pFramework) 189 | pFramework->OnMouseMove(static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 190 | { 191 | TRACKMOUSEEVENT csTME = { sizeof(TRACKMOUSEEVENT), TME_LEAVE, hWnd }; 192 | TrackMouseEvent(&csTME); 193 | } 194 | return 0; 195 | 196 | case WM_MOUSELEAVE: 197 | if (pFramework) pFramework->OnMouseLeave(); 198 | return 0; 199 | 200 | case WM_MOUSEWHEEL: 201 | if (pFramework) pFramework->OnMouseWheel(static_cast(GET_WHEEL_DELTA_WPARAM(wParam)) / WHEEL_DELTA, 202 | static_cast(GET_X_LPARAM(lParam)), static_cast(GET_Y_LPARAM(lParam))); 203 | return 0; 204 | 205 | case WM_PAINT: 206 | if (pFramework) 207 | { 208 | pFramework->OnUpdate(); 209 | pFramework->OnRender(); 210 | } 211 | return 0; 212 | 213 | case WM_DESTROY: 214 | PostQuitMessage(0); 215 | return 0; 216 | } 217 | 218 | // Handle any messages the switch statement didn't. 219 | return DefWindowProc(hWnd, message, wParam, lParam); 220 | } 221 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/Win32Application.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #pragma once 13 | 14 | #include "DXFramework.h" 15 | 16 | class DXFramework; 17 | 18 | class Win32Application 19 | { 20 | public: 21 | static int Run(DXFramework *pFramework, HINSTANCE hInstance, int nCmdShow, HICON hIcon = nullptr); 22 | static HWND GetHwnd() { return m_hwnd; } 23 | 24 | protected: 25 | static LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); 26 | 27 | private: 28 | static HWND m_hwnd; 29 | }; 30 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/d3d12/LICENSE-CODE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Corporation. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /RayTracedGGX/Common/d3d12/LICENSE.txt: -------------------------------------------------------------------------------- 1 | MICROSOFT SOFTWARE LICENSE TERMS 2 | 3 | MICROSOFT DIRECTX 4 | 5 | These license terms are an agreement between you and Microsoft 6 | Corporation (or one of its affiliates). They apply to the software named 7 | above and any Microsoft services or software updates (except to the 8 | extent such services or updates are accompanied by new or additional 9 | terms, in which case those different terms apply prospectively and do 10 | not alter your or Microsoft’s rights relating to pre-updated software or 11 | services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS 12 | BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. 13 | 14 | INSTALLATION AND USE RIGHTS. 15 | 16 | General. Subject to the terms of this agreement, you may install and use any number of copies of the software, and solely for use on Windows. 17 | 18 | Included Microsoft Applications. The software may include other Microsoft applications. These license terms apply to those included applications, if any, unless other license terms are provided with the other Microsoft applications. 19 | 20 | Microsoft Platforms. The software may include components from Microsoft Windows. These components are governed by separate agreements and their own product support policies, as described in the license terms found in the installation directory for that component or in the “Licenses” folder accompanying the software. 21 | 22 | Third Party Components. The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) accompanying the software. 23 | 24 | DATA. 25 | 26 | Data Collection. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may opt-out of many of these scenarios, but not all, as described in the product documentation.  There are also some features in the software that may enable you to collect data from users of your applications. If you use these features to enable data collection in your applications, you must comply with applicable law, including providing appropriate notices to users of your applications. You can learn more about data collection and use in the help documentation and the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to these practices. 27 | 28 | Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. 29 | 30 | DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make available for third parties) in applications you develop, as described in this Section. 31 | 32 | Distribution Rights. The code and test files described below are distributable if included with the software. 33 | 34 | Distributables. You may copy and distribute the object code form of the software listed in the distributables file list in the software; and 35 | 36 | Third Party Distribution. You may permit distributors of your applications to copy and distribute any of this distributable code you elect to distribute with your applications. 37 | 38 | Distribution Requirements. For any code you distribute, you must: 39 | 40 | add significant primary functionality to it in your applications; 41 | 42 | i. require distributors and external end users to agree to terms that protect it and Microsoft at least as much as this agreement; and 43 | 44 | ii. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified distributable code. 45 | 46 | Distribution Restrictions. You may not: 47 | 48 | use Microsoft’s trademarks or trade dress in your application in any way that suggests your application comes from or is endorsed by Microsoft; or modify or distribute the source code of any distributable code so that any part of it becomes subject to any license that requires that the distributable code, any other part of the software, or any of Microsoft’s other intellectual property be disclosed or distributed in source code form, or that others have the right to modify it. 49 | 50 | SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to): 51 | 52 | work around any technical limitations in the software that only allow you to use it in certain ways; 53 | 54 | reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software; 55 | 56 | remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software; 57 | 58 | use the software in any way that is against the law or to create or propagate malware; or 59 | 60 | share, publish, distribute, or lease the software (except for any distributable code, subject to the terms above), provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party. 61 | 62 | EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit https://aka.ms/exporting. 63 | 64 | SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind. 65 | 66 | UPDATES. The software may periodically check for updates, and download and install them for you. You may obtain updates only from Microsoft or authorized sources. Microsoft may need to update your system to provide you with updates. You agree to receive these automatic updates without any additional notice. Updates may not include or support all existing software features, services, or peripheral devices. 67 | 68 | ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software. 69 | 70 | APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court. 71 | 72 | CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you: 73 | 74 | a. Australia. You have statutory guarantees under the Australian 75 | Consumer Law and nothing in this agreement is intended to affect 76 | those rights. 77 | 78 | b. Canada. If you acquired this software in Canada, you may stop 79 | receiving updates by turning off the automatic update feature, 80 | disconnecting your device from the Internet (if and when you 81 | re-connect to the Internet, however, the software will resume 82 | checking for and installing updates), or uninstalling the software. 83 | The product documentation, if any, may also specify how to turn off 84 | updates for your specific device or software. 85 | 86 | c. Germany and Austria. 87 | 88 | i. Warranty. The properly licensed software will perform substantially 89 | as described in any Microsoft materials that accompany the software. 90 | However, Microsoft gives no contractual guarantee in relation to the 91 | licensed software. 92 | 93 | ii. Limitation of Liability. In case of intentional conduct, gross 94 | negligence, claims based on the Product Liability Act, as well as, in 95 | case of death or personal or physical injury, Microsoft is liable 96 | according to the statutory law. 97 | 98 | Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence. 99 | 100 | DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. 101 | 102 | LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT, OR INCIDENTAL DAMAGES. 103 | 104 | This limitation applies to (a) anything related to the software, 105 | services, content (including code) on third party Internet sites, or 106 | third party applications; and (b) claims for breach of contract, 107 | warranty, guarantee, or condition; strict liability, negligence, or 108 | other tort; or any other claim; in each case to the extent permitted by 109 | applicable law. 110 | 111 | It also applies even if Microsoft knew or should have known about the 112 | possibility of the damages. The above limitation or exclusion may not 113 | apply to you because your state, province, or country may not allow the 114 | exclusion or limitation of incidental, consequential, or other damages. 115 | 116 | Please note: As this software is distributed in Canada, some of the 117 | clauses in this agreement are provided below in French. 118 | 119 | Remarque: Ce logiciel étant distribué au Canada, certaines des clauses 120 | dans ce contrat sont fournies ci-dessous en français. 121 | 122 | EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « 123 | tel quel ». Toute utilisation de ce logiciel est à votre seule risque et 124 | péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez 125 | bénéficier de droits additionnels en vertu du droit local sur la 126 | protection des consommateurs, que ce contrat ne peut modifier. La ou 127 | elles sont permises par le droit locale, les garanties implicites de 128 | qualité marchande, d’adéquation à un usage particulier et d’absence de 129 | contrefaçon sont exclues. 130 | 131 | LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES 132 | DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une 133 | indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ 134 | US. Vous ne pouvez prétendre à aucune indemnisation pour les autres 135 | dommages, y compris les dommages spéciaux, indirects ou accessoires et 136 | pertes de bénéfices. 137 | 138 | Cette limitation concerne: 139 | 140 | • tout ce qui est relié au logiciel, aux services ou au contenu (y 141 | compris le code) figurant sur des sites Internet tiers ou dans des 142 | programmes tiers; et 143 | 144 | • les réclamations au titre de violation de contrat ou de garantie, ou 145 | au titre de responsabilité stricte, de négligence ou d’une autre faute 146 | dans la limite autorisée par la loi en vigueur. 147 | 148 | Elle s’applique également, même si Microsoft connaissait ou devrait 149 | connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas 150 | l’exclusion ou la limitation de responsabilité pour les dommages 151 | indirects, accessoires ou de quelque nature que ce soit, il se peut que 152 | la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre 153 | égard. 154 | 155 | EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. 156 | Vous pourriez avoir d’autres droits prévus par les lois de votre pays. 157 | Le présent contrat ne modifie pas les droits que vous confèrent les lois 158 | de votre pays si celles-ci ne le permettent pas. 159 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/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 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/stb/LICENSE: -------------------------------------------------------------------------------- 1 | This software is available under 2 licenses -- choose whichever you prefer. 2 | ------------------------------------------------------------------------------ 3 | ALTERNATIVE A - MIT License 4 | Copyright (c) 2017 Sean Barrett 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 | of the Software, and to permit persons to whom the Software is furnished to do 10 | so, subject to the following conditions: 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 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 THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | ------------------------------------------------------------------------------ 21 | ALTERNATIVE B - Public Domain (www.unlicense.org) 22 | This is free and unencumbered software released into the public domain. 23 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 24 | software, either in source code form or as a compiled binary, for any purpose, 25 | commercial or non-commercial, and by any means. 26 | In jurisdictions that recognize copyright laws, the author or authors of this 27 | software dedicate any and all copyright interest in the software to the public 28 | domain. We make this dedication for the benefit of the public at large and to 29 | the detriment of our heirs and successors. We intend this dedication to be an 30 | overt act of relinquishment in perpetuity of all present and future rights to 31 | this software under copyright law. 32 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 33 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 34 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 35 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 36 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 37 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 38 | -------------------------------------------------------------------------------- /RayTracedGGX/Common/stb_image_write.cpp: -------------------------------------------------------------------------------- 1 | /* stb_image_write - v1.16 - public domain - http://nothings.org/stb 2 | writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 3 | no warranty implied; use at your own risk 4 | 5 | Before #including, 6 | 7 | #define STB_IMAGE_WRITE_IMPLEMENTATION 8 | 9 | in the file that you want to have the implementation. 10 | 11 | Will probably not work correctly with strict-aliasing optimizations. 12 | 13 | ABOUT: 14 | 15 | This header file is a library for writing images to C stdio or a callback. 16 | 17 | The PNG output is not optimal; it is 20-50% larger than the file 18 | written by a decent optimizing implementation; though providing a custom 19 | zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. 20 | This library is designed for source code compactness and simplicity, 21 | not optimal image file size or run-time performance. 22 | 23 | BUILDING: 24 | 25 | You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. 26 | You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace 27 | malloc,realloc,free. 28 | You can #define STBIW_MEMMOVE() to replace memmove() 29 | You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function 30 | for PNG compression (instead of the builtin one), it must have the following signature: 31 | unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); 32 | The returned data will be freed with STBIW_FREE() (free() by default), 33 | so it must be heap allocated with STBIW_MALLOC() (malloc() by default), 34 | 35 | UNICODE: 36 | 37 | If compiling for Windows and you wish to use Unicode filenames, compile 38 | with 39 | #define STBIW_WINDOWS_UTF8 40 | and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert 41 | Windows wchar_t filenames to utf8. 42 | 43 | USAGE: 44 | 45 | There are five functions, one for each image file format: 46 | 47 | int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); 48 | int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); 49 | int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); 50 | int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); 51 | int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); 52 | 53 | void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically 54 | 55 | There are also five equivalent functions that use an arbitrary write function. You are 56 | expected to open/close your file-equivalent before and after calling these: 57 | 58 | int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); 59 | int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); 60 | int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); 61 | int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); 62 | int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); 63 | 64 | where the callback is: 65 | void stbi_write_func(void *context, void *data, int size); 66 | 67 | You can configure it with these global variables: 68 | int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE 69 | int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression 70 | int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode 71 | 72 | 73 | You can define STBI_WRITE_NO_STDIO to disable the file variant of these 74 | functions, so the library will not use stdio.h at all. However, this will 75 | also disable HDR writing, because it requires stdio for formatted output. 76 | 77 | Each function returns 0 on failure and non-0 on success. 78 | 79 | The functions create an image file defined by the parameters. The image 80 | is a rectangle of pixels stored from left-to-right, top-to-bottom. 81 | Each pixel contains 'comp' channels of data stored interleaved with 8-bits 82 | per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is 83 | monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. 84 | The *data pointer points to the first byte of the top-left-most pixel. 85 | For PNG, "stride_in_bytes" is the distance in bytes from the first byte of 86 | a row of pixels to the first byte of the next row of pixels. 87 | 88 | PNG creates output files with the same number of components as the input. 89 | The BMP format expands Y to RGB in the file format and does not 90 | output alpha. 91 | 92 | PNG supports writing rectangles of data even when the bytes storing rows of 93 | data are not consecutive in memory (e.g. sub-rectangles of a larger image), 94 | by supplying the stride between the beginning of adjacent rows. The other 95 | formats do not. (Thus you cannot write a native-format BMP through the BMP 96 | writer, both because it is in BGR order and because it may have padding 97 | at the end of the line.) 98 | 99 | PNG allows you to set the deflate compression level by setting the global 100 | variable 'stbi_write_png_compression_level' (it defaults to 8). 101 | 102 | HDR expects linear float data. Since the format is always 32-bit rgb(e) 103 | data, alpha (if provided) is discarded, and for monochrome data it is 104 | replicated across all three channels. 105 | 106 | TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed 107 | data, set the global variable 'stbi_write_tga_with_rle' to 0. 108 | 109 | JPEG does ignore alpha channels in input data; quality is between 1 and 100. 110 | Higher quality looks better but results in a bigger image. 111 | JPEG baseline (no JPEG progressive). 112 | 113 | CREDITS: 114 | 115 | 116 | Sean Barrett - PNG/BMP/TGA 117 | Baldur Karlsson - HDR 118 | Jean-Sebastien Guay - TGA monochrome 119 | Tim Kelsey - misc enhancements 120 | Alan Hickman - TGA RLE 121 | Emmanuel Julien - initial file IO callback implementation 122 | Jon Olick - original jo_jpeg.cpp code 123 | Daniel Gibson - integrate JPEG, allow external zlib 124 | Aarni Koskela - allow choosing PNG filter 125 | 126 | bugfixes: 127 | github:Chribba 128 | Guillaume Chereau 129 | github:jry2 130 | github:romigrou 131 | Sergio Gonzalez 132 | Jonas Karlsson 133 | Filip Wasil 134 | Thatcher Ulrich 135 | github:poppolopoppo 136 | Patrick Boettcher 137 | github:xeekworx 138 | Cap Petschulat 139 | Simon Rodriguez 140 | Ivan Tikhonov 141 | github:ignotion 142 | Adam Schackart 143 | Andrew Kensler 144 | 145 | LICENSE 146 | 147 | See end of file for license information. 148 | 149 | */ 150 | 151 | #define STB_IMAGE_WRITE_IMPLEMENTATION 152 | #define __STDC_LIB_EXT1__ 153 | #include "stb_image_write.h" 154 | 155 | /* 156 | ------------------------------------------------------------------------------ 157 | This software is available under 2 licenses -- choose whichever you prefer. 158 | ------------------------------------------------------------------------------ 159 | ALTERNATIVE A - MIT License 160 | Copyright (c) 2017 Sean Barrett 161 | Permission is hereby granted, free of charge, to any person obtaining a copy of 162 | this software and associated documentation files (the "Software"), to deal in 163 | the Software without restriction, including without limitation the rights to 164 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 165 | of the Software, and to permit persons to whom the Software is furnished to do 166 | so, subject to the following conditions: 167 | The above copyright notice and this permission notice shall be included in all 168 | copies or substantial portions of the Software. 169 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 170 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 171 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 172 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 173 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 174 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 175 | SOFTWARE. 176 | ------------------------------------------------------------------------------ 177 | ALTERNATIVE B - Public Domain (www.unlicense.org) 178 | This is free and unencumbered software released into the public domain. 179 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 180 | software, either in source code form or as a compiled binary, for any purpose, 181 | commercial or non-commercial, and by any means. 182 | In jurisdictions that recognize copyright laws, the author or authors of this 183 | software dedicate any and all copyright interest in the software to the public 184 | domain. We make this dedication for the benefit of the public at large and to 185 | the detriment of our heirs and successors. We intend this dedication to be an 186 | overt act of relinquishment in perpetuity of all present and future rights to 187 | this software under copyright law. 188 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 189 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 190 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 191 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 192 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 193 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 194 | ------------------------------------------------------------------------------ 195 | */ 196 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Denoiser.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "Core/XUSG.h" 8 | 9 | class Denoiser 10 | { 11 | public: 12 | Denoiser(); 13 | virtual ~Denoiser(); 14 | 15 | bool Init(XUSG::CommandList* pCommandList, const XUSG::DescriptorTableLib::sptr& descriptorTableLib, 16 | uint32_t width, uint32_t height, XUSG::Format rtFormat, const XUSG::Texture2D::uptr* inputViews, 17 | const XUSG::RenderTarget::uptr* pGbuffers, const XUSG::DepthStencil::sptr& depth, uint8_t maxMips = 1); 18 | void Denoise(XUSG::CommandList* pCommandList, uint32_t numBarriers, 19 | XUSG::ResourceBarrier* pBarriers, bool useSharedMem = false, bool asyncCompute = false); 20 | void ToneMap(XUSG::CommandList* pCommandList, const XUSG::Descriptor& rtv, 21 | uint32_t numBarriers, XUSG::ResourceBarrier* pBarriers); 22 | 23 | protected: 24 | enum PipelineLayoutIndex : uint8_t 25 | { 26 | SPATIAL_H_LAYOUT, // Spatial horizontal pass 27 | SPT_V_RFL_LAYOUT, // Spatial vertical pass of reflection map 28 | SPT_V_DFF_LAYOUT, // Spatial vertical pass of diffuse map 29 | TEMPORAL_SS_LAYOUT, // Temporal super sampling 30 | TONE_MAP_LAYOUT, 31 | 32 | NUM_PIPELINE_LAYOUT 33 | }; 34 | 35 | enum PipelineLayoutSlot : uint8_t 36 | { 37 | OUTPUT_VIEW, 38 | SHADER_RESOURCES, 39 | G_BUFFERS 40 | }; 41 | 42 | enum PipelineIndex : uint8_t 43 | { 44 | SPATIAL_H_RFL, // Spatial horizontal pass of reflection map 45 | SPATIAL_V_RFL, // Spatial vertical pass of reflection map 46 | SPATIAL_H_DFF, // Spatial horizontal pass of diffuse map 47 | SPATIAL_V_DFF, // Spatial vertical pass of diffuse map 48 | SPATIAL_H_RFL_S, // Spatial horizontal pass of reflection map using shared memory 49 | SPATIAL_V_RFL_S, // Spatial vertical pass of reflection map using shared memory 50 | SPATIAL_H_DFF_S, // Spatial horizontal pass of diffuse map using shared memory 51 | SPATIAL_V_DFF_S, // Spatial vertical pass of diffuse map using shared memory 52 | TEMPORAL_SS, // Temporal super sampling 53 | TONE_MAP, 54 | 55 | NUM_PIPELINE 56 | }; 57 | 58 | enum GBuffer : uint8_t 59 | { 60 | NORMAL, 61 | ROUGH_METAL, 62 | VELOCITY, 63 | 64 | NUM_GBUFFER 65 | }; 66 | 67 | enum UAVResource : uint8_t 68 | { 69 | UAV_TSS, // For temporal super sampling 70 | UAV_TSS1, 71 | UAV_FLT, 72 | UAV_FLT_RFL = UAV_FLT, // Spatially filtered reflection 73 | UAV_FLT_DFF, 74 | 75 | NUM_UAV 76 | }; 77 | 78 | enum SRVTable : uint8_t 79 | { 80 | SRV_TABLE_GB, 81 | SRV_TABLE_SPF_RFL, 82 | SRV_TABLE_SPF_RFL1, 83 | SRV_TABLE_SPF_DFF, // For spatial filter of diffuse map 84 | SRV_TABLE_SPF_DFF1, 85 | SRV_TABLE_TSS, // For temporal super sampling map 86 | SRV_TABLE_TSS1, 87 | SRV_TABLE_TM, // For tone mapping 88 | SRV_TABLE_TM1, 89 | 90 | NUM_SRV_TABLE 91 | }; 92 | 93 | enum UAVTable : uint8_t 94 | { 95 | UAV_TABLE_FLT_RFL, 96 | UAV_TABLE_FLT_DFF, 97 | UAV_TABLE_TSS, 98 | UAV_TABLE_TSS1, 99 | 100 | NUM_UAV_TABLE, 101 | 102 | UAV_TABLE_FLT = UAV_TABLE_FLT_RFL, 103 | UAV_TABLE_SCT = UAV_TABLE_TSS, // For spatial horizontal filter scratch 104 | }; 105 | 106 | enum FilterTerm : uint8_t 107 | { 108 | TERM_REFLECTION, 109 | TERM_DIFFUSE, 110 | 111 | NUM_TERM 112 | }; 113 | 114 | bool createPipelineLayouts(); 115 | bool createPipelines(XUSG::Format rtFormat); 116 | bool createDescriptorTables(); 117 | 118 | void reflectionSpatialFilter(XUSG::CommandList* pCommandList, uint32_t numBarriers, 119 | XUSG::ResourceBarrier* pBarriers, bool useSharedMem); 120 | void diffuseSpatialFilter(XUSG::CommandList* pCommandList, uint32_t numBarriers, 121 | XUSG::ResourceBarrier* pBarriers, bool useSharedMem); 122 | void temporalSS(XUSG::CommandList* pCommandList, bool asyncCompute); 123 | 124 | uint8_t m_frameParity; 125 | DirectX::XMUINT2 m_viewport; 126 | 127 | XUSG::PipelineLayout m_pipelineLayouts[NUM_PIPELINE_LAYOUT]; 128 | XUSG::Pipeline m_pipelines[NUM_PIPELINE]; 129 | 130 | XUSG::DescriptorTable m_srvTables[NUM_SRV_TABLE]; 131 | XUSG::DescriptorTable m_uavTables[NUM_UAV_TABLE]; 132 | 133 | XUSG::Texture2D::uptr m_outputViews[NUM_UAV]; 134 | XUSG::DepthStencil::sptr m_depth; 135 | const XUSG::Texture2D::uptr* m_inputViews; 136 | const XUSG::RenderTarget::uptr* m_pGbuffers; 137 | 138 | XUSG::ShaderLib::uptr m_shaderLib; 139 | XUSG::Graphics::PipelineLib::uptr m_graphicsPipelineLib; 140 | XUSG::Compute::PipelineLib::uptr m_computePipelineLib; 141 | XUSG::PipelineLayoutLib::uptr m_pipelineLayoutLib; 142 | XUSG::DescriptorTableLib::sptr m_descriptorTableLib; 143 | }; 144 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/RayTracer.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "Advanced/XUSGAdvanced.h" 8 | #include "RayTracing/XUSGRayTracing.h" 9 | 10 | class RayTracer 11 | { 12 | public: 13 | enum MeshIndex : uint32_t 14 | { 15 | GROUND, 16 | MODEL_OBJ, 17 | 18 | NUM_MESH 19 | }; 20 | 21 | RayTracer(); 22 | virtual ~RayTracer(); 23 | 24 | bool Init(XUSG::RayTracing::CommandList* pCommandList, const XUSG::DescriptorTableLib::sptr& descriptorTableLib, 25 | uint32_t width, uint32_t height, std::vector& uploaders, XUSG::RayTracing::GeometryBuffer* pGeometries, 26 | XUSG::RayTracing::BottomLevelAS::uptr bottomLevelASes[NUM_MESH], const char* fileName, const wchar_t* envFileName, 27 | XUSG::Format rtFormat, const DirectX::XMFLOAT4& posScale = DirectX::XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f), uint8_t maxGBufferMips = 1); 28 | bool BuildAccelerationStructures(XUSG::RayTracing::CommandList* pCommandList, 29 | const XUSG::RayTracing::BottomLevelAS::uptr bottomLevelASes[NUM_MESH]); 30 | bool Postinit(const XUSG::RayTracing::Device* pDevice); 31 | 32 | void SetMetallic(uint32_t meshIdx, float metallic); 33 | void UpdateFrame(const XUSG::RayTracing::Device* pDevice, uint8_t frameIndex, 34 | DirectX::CXMVECTOR eyePt, DirectX::CXMMATRIX viewProj, float timeStep); 35 | void TransformSH(XUSG::CommandList* pCommandList); 36 | void Render(XUSG::RayTracing::CommandList* pCommandList, uint8_t frameIndex); 37 | void UpdateAccelerationStructure(XUSG::RayTracing::CommandList* pCommandList, uint8_t frameIndex); 38 | void RenderVisibility(XUSG::RayTracing::CommandList* pCommandList, uint8_t frameIndex, bool asyncCompute = false); 39 | void RayTrace(XUSG::RayTracing::CommandList* pCommandList, uint8_t frameIndex); 40 | 41 | const XUSG::Texture2D::uptr* GetRayTracingOutputs() const; 42 | const XUSG::RenderTarget::uptr* GetGBuffers() const; 43 | const XUSG::DepthStencil::sptr GetDepth() const; 44 | 45 | static const uint8_t FrameCount = 3; 46 | 47 | protected: 48 | enum PipelineLayoutIndex : uint8_t 49 | { 50 | VISIBILITY_LAYOUT, 51 | RT_GLOBAL_LAYOUT, 52 | RAY_GEN_LAYOUT, 53 | 54 | NUM_PIPELINE_LAYOUT 55 | }; 56 | 57 | enum PipelineIndex : uint8_t 58 | { 59 | VISIBILITY, 60 | RAY_TRACING, 61 | 62 | NUM_PIPELINE 63 | }; 64 | 65 | enum CSIndex : uint8_t 66 | { 67 | CS_RAY_TRACING 68 | }; 69 | 70 | enum GlobalPipelineLayoutSlot : uint8_t 71 | { 72 | OUTPUT_VIEW, 73 | ACCELERATION_STRUCTURE, 74 | INDEX_BUFFERS, 75 | VERTEX_BUFFERS, 76 | MATERIALS, 77 | CONSTANTS, 78 | SHADER_RESOURCES, 79 | SH_COEFFICIENTS, 80 | }; 81 | 82 | enum GBuffer : uint8_t 83 | { 84 | NORMAL, 85 | ROUGH_METAL, 86 | VELOCITY, 87 | 88 | NUM_GBUFFER 89 | }; 90 | 91 | enum SRVTable : uint8_t 92 | { 93 | SRV_TABLE_IB, 94 | SRV_TABLE_VB, 95 | SRV_TABLE_RO, 96 | SRV_TABLE_LP, 97 | 98 | NUM_SRV_TABLE 99 | }; 100 | 101 | enum HitGroup : uint8_t 102 | { 103 | HIT_GROUP_REFLECTION, 104 | HIT_GROUP_DIFFUSE, 105 | 106 | NUM_HIT_GROUP 107 | }; 108 | 109 | bool createVB(XUSG::CommandList* pCommandList, uint32_t numVert, uint32_t stride, 110 | const uint8_t* pData, std::vector& uploaders); 111 | bool createIB(XUSG::CommandList* pCommandList, uint32_t numIndices, 112 | const uint32_t* pData, std::vector& uploaders); 113 | bool createGroundMesh(XUSG::CommandList* pCommandList, std::vector& uploaders); 114 | bool createInputLayout(); 115 | bool createPipelineLayouts(const XUSG::RayTracing::Device* pDevice); 116 | bool createPipelines(XUSG::Format rtFormat, XUSG::Format dsFormat); 117 | bool createDescriptorTables(); 118 | virtual bool createOutViewTable(); 119 | bool buildAccelerationStructures(XUSG::RayTracing::CommandList* pCommandList, 120 | XUSG::RayTracing::GeometryBuffer* pGeometries, XUSG::RayTracing::BottomLevelAS::uptr bottomLevelASes[NUM_MESH]); 121 | bool buildShaderTables(const XUSG::RayTracing::Device* pDevice); 122 | 123 | void visibility(XUSG::CommandList* pCommandList, uint8_t frameIndex); 124 | void rayTrace(const XUSG::RayTracing::CommandList* pCommandList, uint8_t frameIndex); 125 | 126 | uint32_t m_numIndices[NUM_MESH]; 127 | 128 | DirectX::XMUINT2 m_viewport; 129 | DirectX::XMFLOAT4 m_posScale; 130 | DirectX::XMFLOAT4X4 m_worlds[NUM_MESH]; 131 | DirectX::XMFLOAT4X4 m_worldViewProjs[NUM_MESH]; 132 | 133 | XUSG::RayTracing::BottomLevelAS::uptr m_bottomLevelASes[NUM_MESH]; 134 | XUSG::RayTracing::TopLevelAS::uptr m_topLevelAS; 135 | 136 | const XUSG::InputLayout* m_pInputLayout; 137 | XUSG::PipelineLayout m_pipelineLayouts[NUM_PIPELINE_LAYOUT]; 138 | XUSG::Pipeline m_pipelines[NUM_PIPELINE]; 139 | 140 | XUSG::SphericalHarmonics::uptr m_sphericalHarmonics; 141 | 142 | XUSG::DescriptorTable m_srvTables[NUM_SRV_TABLE]; 143 | XUSG::DescriptorTable m_uavTable; 144 | XUSG::Framebuffer m_framebuffer; 145 | 146 | XUSG::VertexBuffer::uptr m_vertexBuffers[NUM_MESH]; 147 | XUSG::IndexBuffer::uptr m_indexBuffers[NUM_MESH]; 148 | 149 | XUSG::Texture2D::uptr m_outputViews[NUM_HIT_GROUP]; 150 | XUSG::RenderTarget::uptr m_visBuffer; 151 | XUSG::RenderTarget::uptr m_gbuffers[NUM_GBUFFER]; 152 | XUSG::DepthStencil::sptr m_depth; 153 | 154 | XUSG::ConstantBuffer::uptr m_cbPerOjects[NUM_MESH]; 155 | XUSG::ConstantBuffer::uptr m_cbMaterials; 156 | XUSG::ConstantBuffer::uptr m_cbRaytracing; 157 | 158 | XUSG::Buffer::uptr m_scratch; 159 | XUSG::Buffer::uptr m_instances[FrameCount]; 160 | 161 | XUSG::Texture::sptr m_lightProbe; 162 | 163 | // Shader tables 164 | static const wchar_t* HitGroupNames[NUM_HIT_GROUP]; 165 | static const wchar_t* RaygenShaderName; 166 | static const wchar_t* ClosestHitShaderNames[NUM_HIT_GROUP]; 167 | static const wchar_t* MissShaderName; 168 | XUSG::RayTracing::ShaderTable::uptr m_missShaderTable; 169 | XUSG::RayTracing::ShaderTable::uptr m_hitGroupShaderTable; 170 | XUSG::RayTracing::ShaderTable::uptr m_rayGenShaderTables[FrameCount]; 171 | 172 | XUSG::ShaderLib::sptr m_shaderLib; 173 | XUSG::RayTracing::PipelineLib::uptr m_rayTracingPipelineLib; 174 | XUSG::Graphics::PipelineLib::uptr m_graphicsPipelineLib; 175 | XUSG::Compute::PipelineLib::sptr m_computePipelineLib; 176 | XUSG::PipelineLayoutLib::sptr m_pipelineLayoutLib; 177 | XUSG::DescriptorTableLib::sptr m_descriptorTableLib; 178 | 179 | XUSG::Format m_rtFormat; 180 | }; 181 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/BRDFModels.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #define PI 3.1415926535897 6 | 7 | // GGX / Trowbridge-Reitz 8 | // [Walter et al. 2007, "Microfacet models for refraction through rough surfaces"] 9 | float D_GGX(float roughness, float NoH) 10 | { 11 | const float m = roughness * roughness; 12 | const float m2 = m * m; 13 | const float d = (NoH * m2 - NoH) * NoH + 1; // 2 mad 14 | 15 | return m2 / (PI * d * d); // 4 mul, 1 rcp 16 | } 17 | 18 | // [Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"] 19 | float Vis_Schlick(float roughness, float NoV, float NoL) 20 | { 21 | const float k = roughness * roughness * 0.5; 22 | const float vis_SchlickV = NoV * (1 - k) + k; 23 | const float vis_SchlickL = NoL * (1 - k) + k; 24 | 25 | return 0.25 / (vis_SchlickV * vis_SchlickL); 26 | } 27 | 28 | // Smith term for GGX 29 | // [Smith 1967, "Geometrical shadowing of a random rough surface"] 30 | float Vis_Smith(float roughness, float NoV, float NoL) 31 | { 32 | const float a = roughness * roughness; 33 | const float a2 = a * a; 34 | 35 | const float vis_SmithV = NoV + sqrt(NoV * (NoV - NoV * a2) + a2); 36 | const float vis_SmithL = NoL + sqrt(NoL * (NoL - NoL * a2) + a2); 37 | 38 | return 1.0 / (vis_SmithV * vis_SmithL); 39 | } 40 | 41 | // Appoximation of joint Smith term for GGX 42 | // [Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs"] 43 | float Vis_SmithJointApprox(float roughness, float NoV, float NoL) 44 | { 45 | const float a = roughness * roughness; 46 | const float vis_SmithV = NoL * (NoV * (1 - a) + a); 47 | const float vis_SmithL = NoV * (NoL * (1 - a) + a); 48 | 49 | return 0.5 / (vis_SmithV + vis_SmithL); 50 | } 51 | 52 | // [Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"] 53 | // [Lagarde 2012, "Spherical Gaussian approximation for Blinn-Phong, Phong and Fresnel"] 54 | float3 F_Schlick(float3 specularColor, float VoH) 55 | { 56 | const float fc = pow(1.0 - VoH, 5.0); // 1 sub, 3 mul 57 | //float fc = exp2( (-5.55473 * VoH - 6.98316) * VoH ); // 1 mad, 1 mul, 1 exp 58 | //return fc + (1 - fc) * specularColor; // 1 add, 3 mad 59 | 60 | // Anything less than 2% is physically impossible and is instead considered to be shadowing 61 | return saturate(50.0 * specularColor.g) * fc + (1.0 - fc) * specularColor; 62 | } 63 | 64 | float3 EnvBRDFApprox(float3 specularColor, float roughness, float NoV) 65 | { 66 | // [ Lazarov 2013, "Getting More Physical in Call of Duty: Black Ops II" ] 67 | // Adaptation to fit our G term. 68 | const float4 c0 = { -1.0, -0.0275, -0.572, 0.022 }; 69 | const float4 c1 = { 1.0, 0.0425, 1.04, -0.04 }; 70 | float4 r = roughness * c0 + c1; 71 | float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y; 72 | float2 AB = float2(-1.04, 1.04) * a004 + r.zw; 73 | 74 | AB.y *= saturate(50.0 * specularColor.y); 75 | 76 | return specularColor * AB.x + AB.y; 77 | } 78 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_H_Diff.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txNormal : register (t1); 12 | Texture2D g_txRoughMetal : register (t2); 13 | Texture2D g_txDepth : register (t3); 14 | 15 | [numthreads(8, 8, 1)] 16 | void main(uint2 DTid : SV_DispatchThreadID) 17 | { 18 | float4 normC = g_txNormal[DTid]; 19 | if (normC.w <= 0.0 || g_txRoughMetal[DTid].y >= 1.0) return; 20 | 21 | const float depthC = g_txDepth[DTid]; 22 | normC.xyz = normC.xyz * 2.0 - 1.0; 23 | 24 | float3 mu = 0.0; 25 | float wsum = 0.0; 26 | 27 | [unroll] 28 | for (int i = -RADIUS; i <= RADIUS; ++i) 29 | { 30 | const uint2 index = uint2((int)DTid.x + i, DTid.y); 31 | 32 | float4 norm = g_txNormal[index]; 33 | const float mtl = g_txRoughMetal[index].y; 34 | 35 | if (norm.w <= 0.0 || mtl >= 1.0) continue; 36 | 37 | float3 src = g_txSource[index]; 38 | const float depth = g_txDepth[index]; 39 | 40 | norm.xyz = norm.xyz * 2.0 - 1.0; 41 | src = TM(src); 42 | const float w = DiffuseWeight(normC.xyz, norm.xyz, depthC, depth); 43 | mu += src * w; 44 | wsum += w; 45 | } 46 | 47 | g_renderTarget[DTid] = mu / wsum; 48 | } 49 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_H_Diff_S.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txNormal : register (t1); 12 | Texture2D g_txRoughMetal : register (t2); 13 | Texture2D g_txDepth : register (t3); 14 | 15 | groupshared uint4 g_srcMtlNrms[SHARED_MEM_SIZE]; 16 | groupshared float g_depths[SHARED_MEM_SIZE]; 17 | 18 | void loadSamples(uint2 dTid, uint gTid, uint radius) 19 | { 20 | const uint offset = radius * 2; 21 | dTid.x -= radius; 22 | 23 | [unroll] 24 | for (uint i = 0; i < 2; ++i, dTid.x += 32, gTid += 32) 25 | { 26 | float3 src = g_txSource[dTid]; 27 | float4 norm = g_txNormal[dTid]; 28 | const float mtl = g_txRoughMetal[dTid].y; 29 | const float depth = g_txDepth[dTid]; 30 | 31 | src = TM(src); 32 | norm.xyz = norm.xyz * 2.0 - 1.0; 33 | g_srcMtlNrms[gTid] = uint4(pack(float4(src, mtl)), pack(norm)); 34 | g_depths[gTid] = depth; 35 | } 36 | 37 | GroupMemoryBarrierWithGroupSync(); 38 | } 39 | 40 | [numthreads(THREADS_PER_WAVE, 1, 1)] 41 | void main(uint2 DTid : SV_DispatchThreadID, uint2 GTid : SV_GroupThreadID) 42 | { 43 | float4 normC = g_txNormal[DTid]; 44 | const bool vis = normC.w > 0.0 && g_txRoughMetal[DTid].y < 1.0; 45 | if (WaveActiveAllTrue(!vis)) return; 46 | 47 | loadSamples(DTid, GTid.x, RADIUS); 48 | if (!vis) return; 49 | 50 | const float depthC = g_depths[GTid.x + RADIUS]; 51 | normC.xyz = normC.xyz * 2.0 - 1.0; 52 | 53 | float3 mu = 0.0; 54 | float wsum = 0.0; 55 | 56 | [unroll] 57 | for (int i = -RADIUS; i <= RADIUS; ++i) 58 | { 59 | const uint j = GTid.x + i + RADIUS; 60 | const float4 srcMtl = unpack(g_srcMtlNrms[j].xy); 61 | const float4 norm = unpack(g_srcMtlNrms[j].zw); 62 | const float depth = g_depths[j]; 63 | 64 | const float w = DiffuseWeight(normC.xyz, norm, depthC, depth, srcMtl.w); 65 | mu += srcMtl.xyz * w; 66 | wsum += w; 67 | } 68 | 69 | g_renderTarget[DTid] = mu / wsum; 70 | } 71 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_H_Refl.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txNormal : register (t1); 12 | Texture2D g_txRoughness : register (t2); 13 | Texture2D g_txDepth : register (t3); 14 | 15 | [numthreads(8, 8, 1)] 16 | void main(uint2 DTid : SV_DispatchThreadID) 17 | { 18 | float4 normC = g_txNormal[DTid]; 19 | if (normC.w <= 0.0) return; 20 | 21 | float2 imageSize; 22 | g_renderTarget.GetDimensions(imageSize.x, imageSize.y); 23 | 24 | const float roughness = g_txRoughness[DTid]; 25 | const float depthC = g_txDepth[DTid]; 26 | normC.xyz = normC.xyz * 2.0 - 1.0; 27 | 28 | const float br = GaussianRadiusFromRoughness(roughness, imageSize); 29 | float3 mu = 0.0; 30 | float wsum = 0.0; 31 | 32 | [unroll] 33 | for (int i = -RADIUS; i <= RADIUS; ++i) 34 | { 35 | const uint2 index = uint2((int)DTid.x + i, DTid.y); 36 | 37 | float4 norm = g_txNormal[index]; 38 | float3 src = g_txSource[index]; 39 | const float depth = g_txDepth[index]; 40 | const float rgh = g_txRoughness[index]; 41 | 42 | norm.xyz = norm.xyz * 2.0 - 1.0; 43 | src = TM(src); 44 | const float w = ReflectionWeight(normC.xyz, norm, roughness, rgh, depthC, depth, abs(i), br); 45 | mu += src * w; 46 | wsum += w; 47 | } 48 | 49 | g_renderTarget[DTid] = mu / wsum; 50 | } 51 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_H_Refl_S.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txNormal : register (t1); 12 | Texture2D g_txRoughness : register (t2); 13 | Texture2D g_txDepth : register (t3); 14 | 15 | groupshared uint4 g_srcRghNrms[SHARED_MEM_SIZE]; 16 | groupshared float g_depths[SHARED_MEM_SIZE]; 17 | 18 | void loadSamples(uint2 dTid, uint gTid, uint radius) 19 | { 20 | const uint offset = radius * 2; 21 | dTid.x -= radius; 22 | 23 | [unroll] 24 | for (uint i = 0; i < 2; ++i, dTid.x += 32, gTid += 32) 25 | { 26 | float3 src = g_txSource[dTid]; 27 | float4 norm = g_txNormal[dTid]; 28 | const float rgh = g_txRoughness[dTid]; 29 | const float depth = g_txDepth[dTid]; 30 | 31 | src = TM(src); 32 | norm.xyz = norm.xyz * 2.0 - 1.0; 33 | g_srcRghNrms[gTid] = uint4(pack(float4(src, rgh)), pack(norm)); 34 | g_depths[gTid] = depth; 35 | } 36 | 37 | GroupMemoryBarrierWithGroupSync(); 38 | } 39 | 40 | [numthreads(THREADS_PER_WAVE, 1, 1)] 41 | void main(uint2 DTid : SV_DispatchThreadID, uint2 GTid : SV_GroupThreadID) 42 | { 43 | float4 normC = g_txNormal[DTid]; 44 | const bool vis = normC.w > 0.0; 45 | if (WaveActiveAllTrue(!vis)) return; 46 | 47 | loadSamples(DTid, GTid.x, RADIUS); 48 | if (!vis) return; 49 | 50 | float2 imageSize; 51 | g_renderTarget.GetDimensions(imageSize.x, imageSize.y); 52 | 53 | const float roughness = g_txRoughness[DTid]; 54 | const float depthC = g_depths[GTid.x + RADIUS]; 55 | normC.xyz = normC.xyz * 2.0 - 1.0; 56 | 57 | const float br = GaussianRadiusFromRoughness(roughness, imageSize); 58 | float3 mu = 0.0; 59 | float wsum = 0.0; 60 | 61 | [unroll] 62 | for (int i = -RADIUS; i <= RADIUS; ++i) 63 | { 64 | const uint j = GTid.x + i + RADIUS; 65 | const float4 srcRgh = unpack(g_srcRghNrms[j].xy); 66 | const float4 norm = unpack(g_srcRghNrms[j].zw); 67 | const float depth = g_depths[j]; 68 | 69 | const float w = ReflectionWeight(normC.xyz, norm, roughness, srcRgh.w, depthC, depth, i, br); 70 | mu += srcRgh.xyz * w; 71 | wsum += w; 72 | } 73 | 74 | g_renderTarget[DTid] = mu / wsum; 75 | } 76 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_V_Diff.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txAverage : register (t1); 12 | Texture2D g_txDest : register (t2); 13 | Texture2D g_txNormal : register (t3); 14 | Texture2D g_txRoughMetal : register (t4); 15 | Texture2D g_txDepth : register (t5); 16 | 17 | [numthreads(8, 8, 1)] 18 | void main(uint2 DTid : SV_DispatchThreadID) 19 | { 20 | const float4 dest = g_txDest[DTid]; 21 | float4 normC = g_txNormal[DTid]; 22 | if (normC.w <= 0.0 || g_txRoughMetal[DTid].y >= 1.0) 23 | { 24 | g_renderTarget[DTid] = dest; 25 | return; 26 | } 27 | 28 | const float3 src = g_txSource[DTid]; 29 | const float depthC = g_txDepth[DTid]; 30 | normC.xyz = normC.xyz * 2.0 - 1.0; 31 | 32 | float3 mu = 0.0, m2 = 0.0; 33 | float wsum = 0.0; 34 | 35 | [unroll] 36 | for (int i = -RADIUS; i <= RADIUS; ++i) 37 | { 38 | const uint2 index = uint2(DTid.x, (int)DTid.y + i); 39 | 40 | float4 norm = g_txNormal[index]; 41 | const float mtl = g_txRoughMetal[index].y; 42 | 43 | if (norm.w <= 0.0 || mtl >= 1.0) continue; 44 | 45 | float3 avg = g_txAverage[index]; 46 | const float depth = g_txDepth[index]; 47 | 48 | norm.xyz = norm.xyz * 2.0 - 1.0; 49 | const float w = DiffuseWeight(normC.xyz, norm.xyz, depthC, depth); 50 | mu += avg * w; 51 | wsum += w; 52 | } 53 | 54 | mu /= wsum; 55 | const float3 result = mu; 56 | //const float3 result = Denoise(src, mu, 1.0); 57 | 58 | g_renderTarget[DTid] = float4(dest.xyz + ITM(result), dest.w); 59 | } 60 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_V_Diff_S.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txAverage : register (t1); 12 | Texture2D g_txDest : register (t2); 13 | Texture2D g_txNormal : register (t3); 14 | Texture2D g_txRoughMetal : register (t4); 15 | Texture2D g_txDepth : register (t5); 16 | 17 | groupshared uint4 g_avgMtlNrms[SHARED_MEM_SIZE]; 18 | groupshared float g_depths[SHARED_MEM_SIZE]; 19 | 20 | void loadSamples(uint2 dTid, uint gTid, uint radius) 21 | { 22 | const uint offset = radius * 2; 23 | dTid.y -= radius; 24 | 25 | [unroll] 26 | for (uint i = 0; i < 2; ++i, dTid.y += offset, gTid += offset) 27 | { 28 | const float3 avg = g_txAverage[dTid]; 29 | float4 norm = g_txNormal[dTid]; 30 | const float mtl = g_txRoughMetal[dTid].y; 31 | const float depth = g_txDepth[dTid]; 32 | 33 | norm.xyz = norm.xyz * 2.0 - 1.0; 34 | g_avgMtlNrms[gTid] = uint4(pack(float4(avg, mtl)), pack(norm)); 35 | g_depths[gTid] = depth; 36 | } 37 | 38 | GroupMemoryBarrierWithGroupSync(); 39 | } 40 | 41 | [numthreads(1, THREADS_PER_WAVE, 1)] 42 | void main(uint2 DTid : SV_DispatchThreadID, uint2 GTid : SV_GroupThreadID) 43 | { 44 | const float4 dest = g_txDest[DTid]; 45 | float4 normC = g_txNormal[DTid]; 46 | const bool vis = normC.w > 0.0 && g_txRoughMetal[DTid].y < 1.0; 47 | if (WaveActiveAllTrue(!vis)) 48 | { 49 | g_renderTarget[DTid] = dest; 50 | return; 51 | } 52 | 53 | loadSamples(DTid, GTid.y, RADIUS); 54 | if (!vis) 55 | { 56 | g_renderTarget[DTid] = dest; 57 | return; 58 | } 59 | 60 | const float3 src = g_txSource[DTid]; 61 | const float depthC = g_depths[GTid.y + RADIUS]; 62 | normC.xyz = normC.xyz * 2.0 - 1.0; 63 | 64 | float3 mu = 0.0, m2 = 0.0; 65 | float wsum = 0.0; 66 | 67 | [unroll] 68 | for (int i = -RADIUS; i <= RADIUS; ++i) 69 | { 70 | const uint j = GTid.y + i + RADIUS; 71 | const float4 avgMtl = unpack(g_avgMtlNrms[j].xy); 72 | const float4 norm = unpack(g_avgMtlNrms[j].zw); 73 | const float depth = g_depths[j]; 74 | 75 | const float w = DiffuseWeight(normC.xyz, norm, depthC, depth, avgMtl.w); 76 | mu += avgMtl.xyz * w; 77 | wsum += w; 78 | } 79 | 80 | mu /= wsum; 81 | const float3 result = mu; 82 | //const float3 result = Denoise(src, mu, 1.0); 83 | 84 | g_renderTarget[DTid] = float4(dest.xyz + ITM(result), dest.w); 85 | } 86 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_V_Refl.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txAverage : register (t1); 12 | Texture2D g_txNormal : register (t2); 13 | Texture2D g_txRoughness : register (t3); 14 | Texture2D g_txDepth : register (t4); 15 | 16 | [numthreads(8, 8, 1)] 17 | void main(uint2 DTid : SV_DispatchThreadID) 18 | { 19 | const float3 src = g_txSource[DTid]; 20 | float4 normC = g_txNormal[DTid]; 21 | if (normC.w <= 0.0) 22 | { 23 | g_renderTarget[DTid] = float4(src, 0.0); 24 | return; 25 | } 26 | 27 | float2 imageSize; 28 | g_renderTarget.GetDimensions(imageSize.x, imageSize.y); 29 | 30 | const float roughness = g_txRoughness[DTid]; 31 | const float depthC = g_txDepth[DTid]; 32 | normC.xyz = normC.xyz * 2.0 - 1.0; 33 | 34 | const float br = GaussianRadiusFromRoughness(roughness, imageSize); 35 | float3 mu = 0.0, m2 = 0.0; 36 | float wsum = 0.0; 37 | 38 | [unroll] 39 | for (int i = -RADIUS; i <= RADIUS; ++i) 40 | { 41 | const uint2 index = uint2(DTid.x, (int)DTid.y + i); 42 | 43 | float4 norm = g_txNormal[index]; 44 | const float3 avg = g_txAverage[index]; 45 | const float depth = g_txDepth[index]; 46 | const float rgh = g_txRoughness[index]; 47 | 48 | norm.xyz = norm.xyz * 2.0 - 1.0; 49 | const float w = ReflectionWeight(normC.xyz, norm, roughness, rgh, depthC, depth, i, br); 50 | mu += avg * w; 51 | wsum += w; 52 | } 53 | 54 | mu /= wsum; 55 | const float3 result = mu; 56 | //const float3 result = Denoise(src, mu, roughness); 57 | 58 | g_renderTarget[DTid] = float4(ITM(result), 1.0); 59 | } 60 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSSpatial_V_Refl_S.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "SpatialFilter.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Textures 9 | //-------------------------------------------------------------------------------------- 10 | RWTexture2D g_renderTarget; 11 | Texture2D g_txAverage : register (t1); 12 | Texture2D g_txNormal : register (t2); 13 | Texture2D g_txRoughness : register (t3); 14 | Texture2D g_txDepth : register (t4); 15 | 16 | groupshared uint4 g_avgRghNrms[SHARED_MEM_SIZE]; 17 | groupshared float g_depths[SHARED_MEM_SIZE]; 18 | 19 | void loadSamples(uint2 dTid, uint gTid, uint radius) 20 | { 21 | const uint offset = radius * 2; 22 | dTid.y -= radius; 23 | 24 | [unroll] 25 | for (uint i = 0; i < 2; ++i, dTid.y += offset, gTid += offset) 26 | { 27 | const float3 avg = g_txAverage[dTid]; 28 | float4 norm = g_txNormal[dTid]; 29 | const float rgh = g_txRoughness[dTid]; 30 | const float depth = g_txDepth[dTid]; 31 | 32 | norm.xyz = norm.xyz * 2.0 - 1.0; 33 | g_avgRghNrms[gTid] = uint4(pack(float4(avg, rgh)), pack(norm)); 34 | g_depths[gTid] = depth; 35 | } 36 | 37 | GroupMemoryBarrierWithGroupSync(); 38 | } 39 | 40 | [numthreads(1, THREADS_PER_WAVE, 1)] 41 | void main(uint2 DTid : SV_DispatchThreadID, uint2 GTid : SV_GroupThreadID) 42 | { 43 | const float3 src = g_txSource[DTid]; 44 | float4 normC = g_txNormal[DTid]; 45 | const bool vis = normC.w > 0.0; 46 | if (WaveActiveAllTrue(!vis)) 47 | { 48 | g_renderTarget[DTid] = float4(src, 0.0); 49 | return; 50 | } 51 | 52 | loadSamples(DTid, GTid.y, RADIUS); 53 | if (!vis) 54 | { 55 | g_renderTarget[DTid] = float4(src, 0.0); 56 | return; 57 | } 58 | 59 | float2 imageSize; 60 | g_renderTarget.GetDimensions(imageSize.x, imageSize.y); 61 | 62 | const float depthC = g_depths[GTid.y + RADIUS]; 63 | const float roughness = g_txRoughness[DTid]; 64 | normC.xyz = normC.xyz * 2.0 - 1.0; 65 | 66 | const float br = GaussianRadiusFromRoughness(roughness, imageSize); 67 | float3 mu = 0.0, m2 = 0.0; 68 | float wsum = 0.0; 69 | 70 | [unroll] 71 | for (int i = -RADIUS; i <= RADIUS; ++i) 72 | { 73 | const uint j = GTid.y + i + RADIUS; 74 | const float4 avgRgh = unpack(g_avgRghNrms[j].xy); 75 | const float4 norm = unpack(g_avgRghNrms[j].zw); 76 | const float depth = g_depths[j]; 77 | 78 | const float w = ReflectionWeight(normC.xyz, norm, roughness, avgRgh.w, depthC, depth, i, br); 79 | mu += avgRgh.xyz * w; 80 | wsum += w; 81 | } 82 | 83 | mu /= wsum; 84 | const float3 result = mu; 85 | //const float3 result = Denoise(src, mu, roughness); 86 | 87 | g_renderTarget[DTid] = float4(ITM(result), 1.0); 88 | } 89 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/CSTemporalSS.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | //-------------------------------------------------------------------------------------- 6 | // Definitions 7 | //-------------------------------------------------------------------------------------- 8 | #ifdef _FORCE_FP32_ 9 | typedef float HALF; 10 | typedef float2 HALF2; 11 | typedef float3 HALF3; 12 | typedef float4 HALF4; 13 | #else 14 | typedef min16float HALF; 15 | typedef min16float2 HALF2; 16 | typedef min16float3 HALF3; 17 | typedef min16float4 HALF4; 18 | #endif 19 | 20 | #define _VARIANCE_AABB_ 1 21 | #define _USE_YCOCG_ 1 22 | 23 | #define NUM_NEIGHBORS 8 24 | #define NUM_SAMPLES (NUM_NEIGHBORS + 1) 25 | #define NUM_NEIGHBORS_H 4 26 | 27 | #ifndef ALPHA_BOUND 28 | #define ALPHA_BOUND 0.5 29 | #endif 30 | 31 | // Use YCoCg dependently 32 | #if _USE_YCOCG_ 33 | #define GET_LUMA4(v) ((v).x) 34 | #else 35 | #define GET_LUMA4(v) dot(v, g_luma4Base) 36 | #endif 37 | 38 | //-------------------------------------------------------------------------------------- 39 | // Constants 40 | //-------------------------------------------------------------------------------------- 41 | static const uint g_historyBits = 4; 42 | static const uint g_historyMask = (1u << g_historyBits) - 1; 43 | static const float g_historyMax = g_historyMask; 44 | 45 | static const HALF3 g_luma4Base = { 1.0, 2.0, 1.0 }; 46 | static const int2 g_texOffsets[] = 47 | { 48 | int2(-1, 0), int2(1, 0), int2(0, -1), int2(0, 1), 49 | int2(-1, -1), int2(1, -1), int2(1, 1), int2(-1, 1) 50 | }; 51 | 52 | //-------------------------------------------------------------------------------------- 53 | // Texture and buffers 54 | //-------------------------------------------------------------------------------------- 55 | #ifdef _R11G11B10_ 56 | RWTexture2D g_rwRenderTarget; 57 | RWTexture2D g_rwMetaData; 58 | Texture2D g_txCurrent; 59 | Texture2D g_txHistory; 60 | Texture2D g_txVelocity; 61 | Texture2D g_txMasks; 62 | Texture2D g_txHistMeta; 63 | #else 64 | RWTexture2D g_rwRenderTarget; 65 | Texture2D g_txCurrent; 66 | Texture2D g_txHistory; 67 | Texture2D g_txVelocity; 68 | #endif 69 | 70 | //-------------------------------------------------------------------------------------- 71 | // Sampler 72 | //-------------------------------------------------------------------------------------- 73 | SamplerState g_smpLinear; 74 | 75 | //-------------------------------------------------------------------------------------- 76 | // RGB to YCgCo 77 | //-------------------------------------------------------------------------------------- 78 | HALF3 rgbToYCoCg(HALF3 rgb) 79 | { 80 | const HALF y = dot(rgb, HALF3(1.0, 2.0, 1.0)); 81 | const HALF co = dot(rgb, HALF3(2.0, 0.0, -2.0)); 82 | const HALF cg = dot(rgb, HALF3(-1.0, 2.0, -1.0)); 83 | 84 | return HALF3(y, co, cg); 85 | } 86 | 87 | //-------------------------------------------------------------------------------------- 88 | // YCgCo to RGB 89 | //-------------------------------------------------------------------------------------- 90 | HALF3 yCoCgToRGB(HALF3 yCoCg) 91 | { 92 | const HALF y = yCoCg.x * 0.25; 93 | const HALF co = yCoCg.y * 0.25; 94 | const HALF cg = yCoCg.z * 0.25; 95 | 96 | const HALF r = y + co - cg; 97 | const HALF g = y + cg; 98 | const HALF b = y - co - cg; 99 | 100 | return HALF3(r, g, b); 101 | } 102 | 103 | //-------------------------------------------------------------------------------------- 104 | // A fast invertible tone map that preserves color (Reinhard) 105 | //-------------------------------------------------------------------------------------- 106 | HALF3 TM(float3 hdr) 107 | { 108 | HALF3 color = HALF3(hdr); 109 | #if _USE_YCOCG_ 110 | color = rgbToYCoCg(color); 111 | #endif 112 | 113 | return color / (4.0 + GET_LUMA4(color)); 114 | } 115 | 116 | //-------------------------------------------------------------------------------------- 117 | // Inverse of preceding function 118 | //-------------------------------------------------------------------------------------- 119 | HALF3 ITM(HALF3 color) 120 | { 121 | color *= 4.0 / (1.0 - GET_LUMA4(color)); 122 | 123 | #if _USE_YCOCG_ 124 | return yCoCgToRGB(color); 125 | #else 126 | return color; 127 | #endif 128 | } 129 | 130 | //-------------------------------------------------------------------------------------- 131 | // Maxinum velocity of 3x3 132 | //-------------------------------------------------------------------------------------- 133 | HALF4 VelocityMax(int2 pos) 134 | { 135 | const float2 velocity = g_txVelocity[pos]; 136 | 137 | float2 velocities[NUM_NEIGHBORS_H]; 138 | [unroll] 139 | for (uint i = 0; i < NUM_NEIGHBORS_H; ++i) 140 | velocities[i] = g_txVelocity[pos + g_texOffsets[i + NUM_NEIGHBORS_H]]; 141 | 142 | HALF4 velocityMax = HALF2(velocity).xyxy; 143 | HALF speedSq = dot(velocityMax.xy, velocityMax.xy); 144 | //[unroll] 145 | for (i = 0; i < NUM_NEIGHBORS_H; ++i) 146 | { 147 | const HALF2 neighbor = HALF2(velocities[i]); 148 | #if 0 149 | velocityMax.xy = max(neighbor, velocityMax.xy); 150 | #else 151 | const HALF speedSqN = dot(neighbor, neighbor); 152 | if (speedSqN > speedSq) 153 | { 154 | velocityMax.xy = neighbor; 155 | speedSq = speedSqN; 156 | } 157 | #endif 158 | } 159 | 160 | return velocityMax; 161 | } 162 | 163 | //-------------------------------------------------------------------------------------- 164 | // Minimum and maxinum of the neighbor samples, returning Gaussian blurred color 165 | //-------------------------------------------------------------------------------------- 166 | HALF4 NeighborMinMax(out HALF4 neighborMin, out HALF4 neighborMax, 167 | HALF4 current, int2 pos, HALF gamma = 1.0) 168 | { 169 | static const HALF weights[] = 170 | { 171 | 0.5, 0.5, 0.5, 0.5, 172 | 0.25, 0.25, 0.25, 0.25 173 | }; 174 | 175 | float4 neighbors[NUM_NEIGHBORS]; 176 | [unroll] 177 | for (uint i = 0; i < NUM_NEIGHBORS; ++i) 178 | neighbors[i] = g_txCurrent[pos + g_texOffsets[i]]; 179 | 180 | HALF3 mu = current.xyz; 181 | #ifndef _ALPHA_AS_ID_ 182 | current.w = current.w < ALPHA_BOUND ? 0.0 : 1.0; 183 | #elif _VARIANCE_AABB_ && defined(_DENOISE_) 184 | const HALF alpha = current.w; 185 | #endif 186 | 187 | #if _VARIANCE_AABB_ 188 | #define m1 mu 189 | HALF3 m2 = m1 * m1; 190 | #else 191 | neighborMin.xyz = neighborMax.xyz = mu; 192 | #endif 193 | 194 | //[unroll] 195 | for (i = 0; i < NUM_NEIGHBORS; ++i) 196 | { 197 | HALF4 neighbor; 198 | neighbor.xyz = TM(neighbors[i].xyz); 199 | #ifdef _ALPHA_AS_ID_ 200 | neighbor.w = HALF(neighbors[i].w); 201 | #else 202 | neighbor.w = neighbors[i].w < ALPHA_BOUND ? 0.0 : 1.0; 203 | #endif 204 | current += neighbor * weights[i]; 205 | 206 | #if _VARIANCE_AABB_ 207 | m1 += neighbor.xyz; 208 | m2 += neighbor.xyz * neighbor.xyz; 209 | #else 210 | neighborMin.xyz = min(neighbor, neighborMin.xyz); 211 | neighborMax.xyz = max(neighbor, neighborMax.xyz); 212 | #endif 213 | } 214 | 215 | current /= 4.0; 216 | 217 | #if _VARIANCE_AABB_ 218 | #if defined(_DENOISE_) && defined(_ALPHA_AS_ID_) 219 | gamma = abs(alpha - current.w) < 1.0 / 255.0 ? gamma : 1.0; 220 | #endif 221 | mu /= NUM_SAMPLES; 222 | const HALF3 sigma = sqrt(abs(m2 / NUM_SAMPLES - mu * mu)); 223 | const HALF3 gsigma = gamma * sigma; 224 | neighborMin.xyz = mu - gsigma; 225 | neighborMax.xyz = mu + gsigma; 226 | neighborMin.xyz = min(neighborMin.xyz, current.xyz); 227 | neighborMax.xyz = max(neighborMax.xyz, current.xyz); 228 | neighborMin.w = GET_LUMA4(mu - sigma); 229 | neighborMax.w = GET_LUMA4(mu + sigma); 230 | #else 231 | neighborMin.w = GET_LUMA4(neighborMin.xyz); 232 | neighborMax.w = GET_LUMA4(neighborMax.xyz); 233 | #endif 234 | 235 | return current; 236 | } 237 | 238 | //-------------------------------------------------------------------------------------- 239 | // Clip color 240 | //-------------------------------------------------------------------------------------- 241 | HALF3 clipColor(HALF3 color, HALF3 minColor, HALF3 maxColor) 242 | { 243 | const HALF3 cent = 0.5 * (maxColor + minColor); 244 | const HALF3 dist = 0.5 * (maxColor - minColor); 245 | 246 | const HALF3 disp = color - cent; 247 | const HALF3 dir = abs(disp / dist); 248 | const HALF maxComp = max(dir.x, max(dir.y, dir.z)); 249 | 250 | if (maxComp > 1.0) return cent + disp / maxComp; 251 | else return color; 252 | } 253 | 254 | [numthreads(8, 8, 1)] 255 | void main(uint2 DTid : SV_DispatchThreadID) 256 | { 257 | float2 texSize; 258 | g_txHistory.GetDimensions(texSize.x, texSize.y); 259 | const float2 uv = (DTid + 0.5) / texSize; 260 | 261 | // Load G-buffers 262 | const float4 current = g_txCurrent[DTid]; 263 | const HALF4 velocity = VelocityMax(DTid); 264 | const float2 uvBack = uv - velocity.xy; 265 | float4 history = g_txHistory.SampleLevel(g_smpLinear, uvBack, 0); 266 | 267 | // Speed to history blur 268 | const float2 historyBlurAmp = 4.0 * texSize; 269 | const HALF2 historyBlurs = HALF2(abs(velocity.xy) * historyBlurAmp); 270 | HALF curHistoryBlur = historyBlurs.x + historyBlurs.y; 271 | 272 | // Evaluate history weight that indicates the convergence from metadata 273 | HALF historyBlur = HALF(1.0 - history.w); 274 | historyBlur = max(historyBlur, curHistoryBlur); 275 | history.w = history.w * g_historyMax + 1.0; 276 | 277 | // Compute color-space AABB 278 | HALF4 neighborMin, neighborMax; 279 | const HALF4 currentTM = HALF4(TM(current.xyz), current.w); 280 | #ifdef _DENOISE_ 281 | const HALF gamma = current.w <= 0.0 ? 1.0 : clamp(8.0 / historyBlur, 1.0, 32.0); 282 | #elif defined(_ALPHA_AS_ID_) 283 | const HALF gamma = historyBlur > 0.0 || current.w <= 0.0 ? 1.0 : 16.0; 284 | #else 285 | const HALF gamma = historyBlur > 0.0 || current.w < ALPHA_BOUND ? 1.0 : 16.0; 286 | #endif 287 | HALF4 filtered = NeighborMinMax(neighborMin, neighborMax, currentTM, DTid, gamma); 288 | 289 | // Saturate history blurs 290 | curHistoryBlur = saturate(curHistoryBlur); 291 | historyBlur = saturate(historyBlur); 292 | 293 | // Clip historical color 294 | HALF3 historyTM = TM(history.xyz); 295 | #if _USE_YCOCG_ 296 | historyTM = clamp(historyTM, neighborMin.xyz, neighborMax.xyz); 297 | #else 298 | historyTM = clipColor(historyTM, neighborMin.xyz, neighborMax.xyz); 299 | #endif 300 | const HALF contrast = neighborMax.w - neighborMin.w; 301 | 302 | // Add aliasing 303 | #if _USE_YCOCG_ 304 | static const HALF lumContrastFactor = 32.0 * 4.0; 305 | #else 306 | static const HALF lumContrastFactor = 32.0; 307 | #endif 308 | HALF addAlias = historyBlur * 0.5 + 0.25; 309 | addAlias = saturate(addAlias + 1.0 / (1.0 + contrast * lumContrastFactor)); 310 | filtered.xyz = lerp(filtered.xyz, currentTM.xyz, addAlias); 311 | 312 | // Calculate blend factor 313 | const HALF lumHist = GET_LUMA4(historyTM); 314 | const HALF distToClamp = min(abs(neighborMin.w - lumHist), abs(neighborMax.w - lumHist)); 315 | #if 0 316 | const float historyAmt = 1.0 / history.w + historyBlur / 8.0; 317 | const HALF historyFactor = HALF(distToClamp * historyAmt * (1.0 + historyBlur * historyAmt * 8.0)); 318 | HALF blend = historyFactor / (distToClamp + contrast); 319 | #else 320 | const HALF historyAmt = min(HALF(1.0 / history.w + historyBlur / 8.0), 1.0); 321 | HALF blend = 0.25 / lerp(8.0, distToClamp + contrast, historyAmt); 322 | #endif 323 | blend = min(blend, 0.25); 324 | blend = filtered.w > 0.0 ? blend : 1.0; 325 | 326 | HALF3 result = ITM(lerp(historyTM, filtered.xyz, blend)); 327 | result = any(isnan(result)) ? ITM(filtered.xyz) : result; 328 | history.w = min(history.w / g_historyMax, 1.0 - curHistoryBlur); 329 | 330 | #ifdef _R11G11B10_ 331 | g_rwRenderTarget[DTid] = result; 332 | g_rwMetaData[DTid] = history.w; 333 | #else 334 | g_rwRenderTarget[DTid] = float4(result, history.w); 335 | #endif 336 | } 337 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/FilterCommon.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #define PI 3.141592654 6 | 7 | static const float3 g_lumBase = { 0.25, 0.5, 0.25 }; 8 | static const float g_gammaRefl = 0.15; 9 | static const float g_gammaDiff = 0.15; 10 | 11 | //-------------------------------------------------------------------------------------- 12 | // A fast invertible tone map that preserves color (Reinhard) 13 | //-------------------------------------------------------------------------------------- 14 | float3 TM(float3 hdr) 15 | { 16 | const float3 rgb = float3(hdr); 17 | 18 | return rgb / (1.0 + dot(rgb, g_lumBase)); 19 | } 20 | 21 | //-------------------------------------------------------------------------------------- 22 | // Inverse of preceding function 23 | //-------------------------------------------------------------------------------------- 24 | float3 ITM(float3 rgb) 25 | { 26 | return rgb / (1.0 - dot(rgb, g_lumBase)); 27 | } 28 | 29 | float RadianceWeight(float3 radianceC, float3 radiance) 30 | { 31 | return max(exp(-0.65 * length(radianceC - radiance)), 1.0e-2); 32 | } 33 | 34 | float NormalWeight(float3 normC, float3 norm, float sigma) 35 | { 36 | return pow(max(dot(normC, norm), 0.0), sigma); 37 | } 38 | 39 | float DepthWeight(float depthC, float depth, float sigma) 40 | { 41 | return exp(-abs(depthC - depth) * depthC * sigma); 42 | } 43 | 44 | float RoughnessWeight(float roughC, float rough, float sigmaMin, float sigmaMax) 45 | { 46 | return 1.0 - smoothstep(sigmaMin, sigmaMax, abs(rough - roughC)); 47 | } 48 | 49 | int GaussianRadiusFromRoughness(float roughness, float2 viewport) 50 | { 51 | return clamp(0.1 * roughness * viewport.x, 0.0, viewport.y * 0.05); 52 | } 53 | 54 | float GaussianSigmaFromRadius(int radius) 55 | { 56 | return (radius + 1) / 3.0; 57 | } 58 | 59 | float Gaussian(float r, float sigma) 60 | { 61 | const float a = r / sigma; 62 | 63 | return exp(-0.5 * a * a); 64 | } 65 | 66 | float Gaussian(float r, int radius) 67 | { 68 | const float sigma = GaussianSigmaFromRadius(radius); 69 | 70 | return Gaussian(r, sigma); 71 | } 72 | 73 | float3 Denoise(float3 src, float3 mu, float roughness) 74 | { 75 | const float t = roughness; 76 | const float b = 1.0 - roughness * 2.0; 77 | float3 d = TM(src) - mu; 78 | d = max(abs(d) - t, 0.0) * sign(d); 79 | 80 | return mu + b * d; 81 | } 82 | 83 | //-------------------------------------------------------------------------------------- 84 | // Clip color 85 | //-------------------------------------------------------------------------------------- 86 | float3 clipColor(float3 color, float3 minColor, float3 maxColor) 87 | { 88 | const float3 cent = 0.5 * (maxColor + minColor); 89 | const float3 dist = 0.5 * (maxColor - minColor); 90 | 91 | const float3 disp = color - cent; 92 | const float3 dir = abs(disp / dist); 93 | const float maxComp = max(dir.x, max(dir.y, dir.z)); 94 | 95 | if (maxComp > 1.0) return cent + disp / maxComp; 96 | else return color; 97 | } 98 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/Material.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #define NUM_MESH 2 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Constant buffer 9 | //-------------------------------------------------------------------------------------- 10 | cbuffer cbPerObject : register (b0) 11 | { 12 | float4 g_baseColors[NUM_MESH]; 13 | float2 g_roughMetals[NUM_MESH]; 14 | }; 15 | 16 | float2 getUV(float3 norm, float3 pos, float3 scl) 17 | { 18 | float2 uv = abs(norm.x) * pos.yz * scl.yz; 19 | uv += abs(norm.y) * pos.zx * scl.zx; 20 | uv += abs(norm.z) * pos.xy * scl.xy; 21 | 22 | return uv * 0.5 + 0.5; 23 | } 24 | 25 | min16float4 getBaseColor(uint instanceIdx, float2 uv) 26 | { 27 | return min16float4(g_baseColors[instanceIdx]); 28 | } 29 | 30 | min16float getRoughness(uint instanceIdx, float2 uv, min16float roughness) 31 | { 32 | if (instanceIdx == 0) 33 | { 34 | uint2 p = uv * 5.0; 35 | p &= 0x1; 36 | roughness = p.x ^ p.y ? roughness * 0.25 : roughness; 37 | } 38 | 39 | return roughness; 40 | } 41 | 42 | min16float2 getRoughMetal(uint instanceIdx, float2 uv) 43 | { 44 | const float2 roughMetal = g_roughMetals[instanceIdx]; 45 | const min16float roughness = getRoughness(instanceIdx, uv, min16float(roughMetal.x)); 46 | 47 | return min16float2(roughness, roughMetal.y); 48 | } 49 | 50 | min16float getRoughness(uint instanceIdx, float2 uv) 51 | { 52 | const float roughness = g_roughMetals[instanceIdx].x; 53 | 54 | return getRoughness(instanceIdx, uv, min16float(roughness)); 55 | } 56 | 57 | min16float getMetallic(uint instanceIdx, float2 uv) 58 | { 59 | return min16float(g_roughMetals[instanceIdx].y); 60 | } 61 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/PSToneMap.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | //-------------------------------------------------------------------------------------- 6 | // Textures 7 | //-------------------------------------------------------------------------------------- 8 | Texture2D g_txSource; 9 | 10 | //-------------------------------------------------------------------------------------- 11 | // Pixel shader 12 | //-------------------------------------------------------------------------------------- 13 | min16float4 main(float4 Pos : SV_POSITION) : SV_TARGET 14 | { 15 | const uint2 pos = Pos.xy; 16 | 17 | const float4 center = g_txSource[pos]; 18 | const float3 left = g_txSource[uint2(pos.x - 1, pos.y)].xyz; 19 | const float3 right = g_txSource[uint2(pos.x + 1, pos.y)].xyz; 20 | const float3 up = g_txSource[uint2(pos.x, pos.y - 1)].xyz; 21 | const float3 down = g_txSource[uint2(pos.x, pos.y + 1)].xyz; 22 | 23 | min16float3 colors[5]; 24 | colors[0] = min16float3(center.xyz); 25 | colors[1] = min16float3(left); 26 | colors[2] = min16float3(right); 27 | colors[3] = min16float3(up); 28 | colors[4] = min16float3(down); 29 | 30 | // Tone mapping 31 | [unroll] 32 | for (uint i = 0; i < 5; ++i) colors[i] /= colors[i] + 0.5; 33 | 34 | // Unsharp 35 | min16float3 laplace = -4.0 * colors[0]; 36 | [unroll] for (i = 1; i < 5; ++i) laplace += colors[i]; 37 | 38 | colors[0] -= 0.2 * laplace; 39 | 40 | return min16float4(colors[0], center.w); 41 | } 42 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/PSVisibility.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #define PRIMITIVE_BITS 24 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Constant buffer 9 | //-------------------------------------------------------------------------------------- 10 | cbuffer cbPerObject 11 | { 12 | uint g_instanceIdx; 13 | }; 14 | 15 | //-------------------------------------------------------------------------------------- 16 | // Base visiblity-buffer pass 17 | //-------------------------------------------------------------------------------------- 18 | uint main(uint primitiveId : SV_PrimitiveID, bool isFrontFace : SV_IsFrontFace) : SV_TARGET 19 | { 20 | //const uint frontFaceBit = isFrontFace ? 1 : 0; 21 | 22 | //return ((frontFaceBit << 31) | (g_instanceIdx << PRIMITIVE_BITS) | primitiveId) + 1; 23 | return ((g_instanceIdx << PRIMITIVE_BITS) | primitiveId) + 1; 24 | } 25 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/SpatialFilter.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "FilterCommon.hlsli" 6 | 7 | #define THREADS_PER_WAVE 32 8 | #define RADIUS 16 9 | #define SAMPLE_COUNT (RADIUS * 2 + 1) 10 | #define SHARED_MEM_SIZE (THREADS_PER_WAVE + RADIUS * 2) 11 | 12 | #define SIGMA_G ((RADIUS + 0.5) / 3.0) 13 | #define SIGMA_Z 4.0 14 | 15 | static const float g_zNear = 1.0f; 16 | static const float g_zFar = 1000.0f; 17 | 18 | //-------------------------------------------------------------------------------------- 19 | // Texture 20 | //-------------------------------------------------------------------------------------- 21 | Texture2D g_txSource; 22 | 23 | //-------------------------------------------------------------------------------------- 24 | // Sampler 25 | //-------------------------------------------------------------------------------------- 26 | SamplerState g_sampler; 27 | 28 | uint2 pack(float3 f) 29 | { 30 | const uint3 u = f32tof16(f); 31 | 32 | return uint2(u.x | (u.y << 16), u.z); 33 | } 34 | 35 | uint2 pack(float4 f) 36 | { 37 | const uint4 u = f32tof16(f); 38 | 39 | return uint2(u.x | (u.y << 16), u.z | (u.w << 16)); 40 | } 41 | 42 | float4 unpack(uint2 u) 43 | { 44 | return f16tof32(uint4(u.x & 0xffff, u.x >> 16, u.y & 0xffff, u.y >> 16)); 45 | } 46 | 47 | //-------------------------------------------------------------------------------------- 48 | // Unproject and return z in viewing space 49 | //-------------------------------------------------------------------------------------- 50 | float UnprojectZ(float depth) 51 | { 52 | static const float3 unproj = { g_zNear - g_zFar, g_zFar, g_zNear * g_zFar }; 53 | 54 | return unproj.z / (depth * unproj.x + unproj.y); 55 | } 56 | 57 | float ReflectionWeight(float3 normC, float4 norm, float rghC, float rgh, 58 | float depthC, float depth, float radius, int blurRadius) 59 | { 60 | float w = norm.w > 0.0 ? 1.0 : 0.0; 61 | w *= Gaussian(radius, blurRadius); 62 | w *= NormalWeight(normC, norm.xyz, 512.0); 63 | w *= DepthWeight(depthC, depth, SIGMA_Z); 64 | w *= RoughnessWeight(rghC, rgh, 0.0, 0.5); 65 | 66 | return w; 67 | } 68 | 69 | float DiffuseWeight(float3 normC, float3 norm, float depthC, float depth) 70 | { 71 | float w = NormalWeight(normC, norm, 32.0); 72 | w *= DepthWeight(depthC, depth, SIGMA_Z); 73 | 74 | return w; 75 | } 76 | 77 | float DiffuseWeight(float3 normC, float4 norm, float depthC, float depth, float mtl) 78 | { 79 | float w = norm.w > 0.0 && mtl < 1.0 ? 1.0 : 0.0; 80 | w *= DiffuseWeight(normC, norm.xyz, depthC, depth); 81 | 82 | return w; 83 | } 84 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/VSScreenQuad.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | //-------------------------------------------------------------------------------------- 6 | // Vertex shader used for screen-space post-processing 7 | //-------------------------------------------------------------------------------------- 8 | float4 main(uint vid : SV_VERTEXID) : SV_POSITION 9 | { 10 | float2 uv = float2((vid << 1) & 2, vid & 2); 11 | 12 | return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 1.0.xx); 13 | } 14 | -------------------------------------------------------------------------------- /RayTracedGGX/Content/Shaders/VSVisibility.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | //-------------------------------------------------------------------------------------- 6 | // Struct 7 | //-------------------------------------------------------------------------------------- 8 | struct VSIn 9 | { 10 | float3 Pos : POSITION; 11 | float3 Nrm : NORMAL; 12 | }; 13 | 14 | //-------------------------------------------------------------------------------------- 15 | // Constant buffer 16 | //-------------------------------------------------------------------------------------- 17 | cbuffer cbPerObject 18 | { 19 | matrix g_worldViewProj; 20 | float2 g_projBias; 21 | }; 22 | 23 | //-------------------------------------------------------------------------------------- 24 | // Base geometry pass 25 | //-------------------------------------------------------------------------------------- 26 | float4 main(VSIn input) : SV_POSITION 27 | { 28 | float4 pos = mul(float4(input.Pos, 1.0), g_worldViewProj); 29 | pos.xy += g_projBias * pos.w; 30 | 31 | return pos; 32 | } 33 | -------------------------------------------------------------------------------- /RayTracedGGX/Main.cpp: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #include "RayTracedGGX.h" 13 | 14 | _Use_decl_annotations_ 15 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) 16 | { 17 | RayTracedGGX rayTracedGGX(1280, 720, L"XUSG Ray Tracing"); 18 | 19 | return Win32Application::Run(&rayTracedGGX, hInstance, nCmdShow); 20 | } 21 | -------------------------------------------------------------------------------- /RayTracedGGX/RayTracedGGX.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #pragma once 13 | 14 | #include "DXFramework.h" 15 | #include "StepTimer.h" 16 | #include "RayTracer.h" 17 | #include "Denoiser.h" 18 | 19 | using namespace DirectX; 20 | 21 | // Note that while ComPtr is used to manage the lifetime of resources on the CPU, 22 | // it has no understanding of the lifetime of resources on the GPU. Apps must account 23 | // for the GPU lifetime of resources to avoid destroying objects that may still be 24 | // referenced by the GPU. 25 | // An example of this can be found in the class method: OnDestroy(). 26 | 27 | class RayTracedGGX : public DXFramework 28 | { 29 | public: 30 | RayTracedGGX(uint32_t width, uint32_t height, std::wstring name); 31 | virtual ~RayTracedGGX(); 32 | 33 | virtual void OnInit(); 34 | virtual void OnUpdate(); 35 | virtual void OnRender(); 36 | virtual void OnDestroy(); 37 | 38 | virtual void OnKeyUp(uint8_t /*key*/); 39 | virtual void OnLButtonDown(float posX, float posY); 40 | virtual void OnLButtonUp(float posX, float posY); 41 | virtual void OnMouseMove(float posX, float posY); 42 | virtual void OnMouseWheel(float deltaZ, float posX, float posY); 43 | virtual void OnMouseLeave(); 44 | 45 | virtual void ParseCommandLineArgs(wchar_t* argv[], int argc); 46 | 47 | private: 48 | enum DeviceType : uint8_t 49 | { 50 | DEVICE_DISCRETE, 51 | DEVICE_UMA, 52 | DEVICE_WARP 53 | }; 54 | 55 | enum CommandType : uint8_t 56 | { 57 | UNIVERSAL, 58 | COMPUTE, 59 | 60 | COMMAND_TYPE_COUNT 61 | }; 62 | 63 | enum CommandAllocatorIndex : uint8_t 64 | { 65 | ALLOCATOR_UPDATE_AS, 66 | ALLOCATOR_GEOMETRY, 67 | ALLOCATOR_GRAPHICS, 68 | ALLOCATOR_COMPUTE, 69 | ALLOCATOR_IMAGE, 70 | 71 | COMMAND_ALLOCATOR_COUNT 72 | }; 73 | 74 | static const auto FrameCount = RayTracer::FrameCount; 75 | 76 | // Pipeline objects. 77 | XUSG::DescriptorTableLib::sptr m_descriptorTableLib; 78 | 79 | XUSG::Viewport m_viewport; 80 | XUSG::RectRange m_scissorRect; 81 | 82 | XUSG::SwapChain::uptr m_swapChain; 83 | XUSG::CommandAllocator::uptr m_commandAllocators[COMMAND_ALLOCATOR_COUNT][FrameCount]; 84 | XUSG::CommandQueue::uptr m_commandQueues[COMMAND_TYPE_COUNT]; 85 | 86 | bool m_isDxrSupported; 87 | 88 | XUSG::RayTracing::Device::uptr m_device; 89 | XUSG::RenderTarget::uptr m_renderTargets[FrameCount]; 90 | XUSG::RayTracing::CommandList::uptr m_commandLists[COMMAND_TYPE_COUNT]; 91 | 92 | // App resources. 93 | std::unique_ptr m_rayTracer; 94 | std::unique_ptr m_denoiser; 95 | XMFLOAT4X4 m_proj; 96 | XMFLOAT4X4 m_view; 97 | XMFLOAT3 m_focusPt; 98 | XMFLOAT3 m_eyePt; 99 | 100 | // Synchronization objects. 101 | uint8_t m_frameIndex; 102 | HANDLE m_fenceEvent; 103 | XUSG::Fence::uptr m_fence; 104 | uint64_t m_fenceValues[FrameCount]; 105 | 106 | XUSG::Semaphore m_semaphore; 107 | 108 | // Application state 109 | DeviceType m_deviceType; 110 | StepTimer m_timer; 111 | uint8_t m_asyncCompute; 112 | uint32_t m_currentMesh; 113 | float m_metallics[RayTracer::NUM_MESH]; 114 | bool m_useSharedMem; 115 | bool m_isPaused; 116 | 117 | // User camera interactions 118 | bool m_tracking; 119 | XMFLOAT2 m_mousePt; 120 | 121 | // User external settings 122 | std::wstring m_envFileName; 123 | std::string m_meshFileName; 124 | XMFLOAT4 m_meshPosScale; 125 | 126 | // Screen-shot helpers and state 127 | XUSG::Buffer::uptr m_readBuffer; 128 | uint32_t m_rowPitch; 129 | uint8_t m_screenShot; 130 | 131 | void LoadPipeline(); 132 | void LoadAssets(); 133 | void PopulateCommandList(); 134 | void PopulateUpdateASCommandList(CommandType commandType); 135 | void PopulateGeometryCommandList(CommandType commandType); 136 | void PopulateRayTraceCommandList(CommandType commandType); 137 | void PopulateImageCommandList(CommandType commandType); 138 | void WaitForGpu(); 139 | void MoveToNextFrame(); 140 | void SaveImage(char const* fileName, XUSG::Buffer* pImageBuffer, 141 | uint32_t w, uint32_t h, uint32_t rowPitch, uint8_t comp = 3); 142 | double CalculateFrameStats(float* fTimeStep = nullptr); 143 | 144 | // Ray tracing 145 | void EnableDirectXRaytracing(IDXGIAdapter1* adapter);; 146 | }; 147 | -------------------------------------------------------------------------------- /RayTracedGGX/RayTracedGGX.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | x64 7 | 8 | 9 | Release 10 | x64 11 | 12 | 13 | 14 | 15.0 15 | {12876612-F1E8-4F22-86F7-699505458AF8} 16 | DX12Test 17 | 10.0 18 | RayTracedGGX 19 | 20 | 21 | 22 | Application 23 | true 24 | v143 25 | Unicode 26 | 27 | 28 | Application 29 | false 30 | v143 31 | true 32 | Unicode 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | Level3 50 | Disabled 51 | true 52 | $(ProjectDir);$(ProjectDir)Content;$(ProjectDir)Common;$(ProjectDir)XUSG 53 | Use 54 | AdvancedVectorExtensions2 55 | Fast 56 | true 57 | 58 | 59 | d3d12.lib;dxgi.lib;d3dcompiler.lib;XUSG.lib;XUSGRayTracing.lib;%(AdditionalDependencies) 60 | $(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration) 61 | 62 | 63 | COPY /Y "$(OutDir)*.cso" "$(ProjectDir)..\Bin\" 64 | COPY /Y "$(OutDir)*.exe" "$(ProjectDir)..\Bin\" 65 | COPY /Y "$(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration)\*.dll" "$(ProjectDir)..\Bin\" 66 | 67 | 68 | 69 | $(ProjectDir)XUSG\Shaders 70 | 6.3 71 | true 72 | -Qembed_debug 73 | 74 | 75 | 76 | 77 | Level3 78 | MaxSpeed 79 | true 80 | true 81 | true 82 | $(ProjectDir);$(ProjectDir)Content;$(ProjectDir)Common;$(ProjectDir)XUSG 83 | Use 84 | AdvancedVectorExtensions2 85 | Fast 86 | true 87 | 88 | 89 | true 90 | true 91 | d3d12.lib;dxgi.lib;d3dcompiler.lib;XUSG.lib;XUSGRayTracing.lib;%(AdditionalDependencies) 92 | $(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration) 93 | 94 | 95 | COPY /Y "$(OutDir)*.cso" "$(ProjectDir)..\Bin\" 96 | COPY /Y "$(OutDir)*.exe" "$(ProjectDir)..\Bin\" 97 | COPY /Y "$(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration)\*.dll" "$(ProjectDir)..\Bin\" 98 | 99 | 100 | 101 | $(ProjectDir)XUSG\Shaders 102 | 6.3 103 | true 104 | 105 | 106 | 107 | 108 | stdafx.h 109 | stdafx.h 110 | 111 | 112 | stdafx.h 113 | stdafx.h 114 | 115 | 116 | stdafx.h 117 | stdafx.h 118 | 119 | 120 | stdafx.h 121 | stdafx.h 122 | 123 | 124 | stdafx.h 125 | stdafx.h 126 | 127 | 128 | stdafx.h 129 | stdafx.h 130 | 131 | 132 | stdafx.h 133 | stdafx.h 134 | 135 | 136 | Create 137 | Create 138 | 139 | 140 | stdafx.h 141 | stdafx.h 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | Compute 167 | Compute 168 | 169 | 170 | Compute 171 | Compute 172 | 173 | 174 | Compute 175 | Compute 176 | 177 | 178 | Compute 179 | Compute 180 | 181 | 182 | Compute 183 | Compute 184 | 185 | 186 | Compute 187 | Compute 188 | 189 | 190 | Compute 191 | Compute 192 | 193 | 194 | Compute 195 | Compute 196 | 197 | 198 | Pixel 199 | Pixel 200 | 201 | 202 | 203 | 204 | Library 205 | 206 | 207 | Library 208 | Document 209 | "$(ProjectDir)..\Bin\dxc.exe" /I "$(ProjectDir)XUSG\Shaders" /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" 210 | "$(ProjectDir)..\Bin\dxc.exe" /I "$(ProjectDir)XUSG\Shaders" /Zi /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" 211 | $(OutDir)%(Filename).cso 212 | $(OutDir)%(Filename).cso 213 | 214 | 215 | Compute 216 | Compute 217 | _DENOISE_;_ALPHA_AS_ID_ 218 | _DENOISE_;_ALPHA_AS_ID_ 219 | 220 | 221 | Pixel 222 | Pixel 223 | 224 | 225 | Vertex 226 | Vertex 227 | 228 | 229 | Vertex 230 | Vertex 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /RayTracedGGX/RayTracedGGX.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | {c7dcf06e-3792-45c8-b4b7-d0beb8f691c7} 18 | 19 | 20 | {4be7925a-b683-465a-a53f-42df43b1e44b} 21 | 22 | 23 | {f1836231-d177-4e3f-b087-6de0175144e8} 24 | 25 | 26 | {08d07ad3-d2bf-4b6d-98f9-a02af3447f31} 27 | 28 | 29 | {440b6ecd-3e27-4e4a-a2af-c8c7477dacdf} 30 | 31 | 32 | {f5f77362-2600-4645-924b-1913b86dc530} 33 | 34 | 35 | {459ae949-f6f1-483b-bfc0-7fc83ef5572d} 36 | 37 | 38 | {80ef64d9-0d59-4edb-97fe-7f72cb8aafb0} 39 | 40 | 41 | {574dc46a-7acf-457b-a063-078a7a0c553e} 42 | 43 | 44 | 45 | 46 | Source Files 47 | 48 | 49 | Source Files 50 | 51 | 52 | Common\Source Files 53 | 54 | 55 | Common\Source Files 56 | 57 | 58 | Source Files 59 | 60 | 61 | Source Files 62 | 63 | 64 | XUSG\Optional 65 | 66 | 67 | Source Files 68 | 69 | 70 | Common\Source Files 71 | 72 | 73 | 74 | 75 | Header Files 76 | 77 | 78 | Common\Header Files 79 | 80 | 81 | Common\Header Files 82 | 83 | 84 | Common\Header Files 85 | 86 | 87 | Common\Header Files 88 | 89 | 90 | Header Files 91 | 92 | 93 | Header Files 94 | 95 | 96 | XUSG\Optional 97 | 98 | 99 | Common\Header Files 100 | 101 | 102 | Header Files 103 | 104 | 105 | Common\Header Files 106 | 107 | 108 | XUSG 109 | 110 | 111 | XUSG 112 | 113 | 114 | XUSG 115 | 116 | 117 | Common\Header Files 118 | 119 | 120 | Common\Header Files 121 | 122 | 123 | Common\Header Files 124 | 125 | 126 | XUSG 127 | 128 | 129 | 130 | 131 | Shaders\Postprocess 132 | 133 | 134 | Shaders\Postprocess 135 | 136 | 137 | Shaders\Denoiser 138 | 139 | 140 | Shaders\Denoiser 141 | 142 | 143 | Shaders\Denoiser 144 | 145 | 146 | Shaders\Denoiser 147 | 148 | 149 | Shaders\Denoiser 150 | 151 | 152 | Shaders\Denoiser 153 | 154 | 155 | Shaders\Denoiser 156 | 157 | 158 | Shaders\Denoiser 159 | 160 | 161 | Shaders\Denoiser 162 | 163 | 164 | Shaders\Renderer 165 | 166 | 167 | Shaders\Renderer 168 | 169 | 170 | 171 | 172 | Shaders\Renderer 173 | 174 | 175 | Shaders\Renderer 176 | 177 | 178 | Shaders\Denoiser 179 | 180 | 181 | Shaders\Denoiser 182 | 183 | 184 | 185 | 186 | Shaders\Renderer 187 | 188 | 189 | -------------------------------------------------------------------------------- /RayTracedGGX/RayTracedGGX.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(ProjectDir)..\Bin\ 5 | WindowsLocalDebugger 6 | 7 | 8 | $(ProjectDir)..\Bin\ 9 | WindowsLocalDebugger 10 | 11 | -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.dll -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.lib -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSG.pdb -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.dll -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.lib -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Debug/XUSGRayTracing.pdb -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Release/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Release/XUSG.dll -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Release/XUSG.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Release/XUSG.lib -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Release/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Release/XUSGRayTracing.dll -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Bin/x64/Release/XUSGRayTracing.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedGGX/3a975799fb8ed08bd1ea09e671661d82240770b3/RayTracedGGX/XUSG/Bin/x64/Release/XUSGRayTracing.lib -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Optional/XUSGObjLoader.cpp: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "XUSGObjLoader.h" 6 | 7 | using namespace std; 8 | using namespace XUSG; 9 | 10 | ObjLoader::ObjLoader() 11 | { 12 | } 13 | 14 | ObjLoader::~ObjLoader() 15 | { 16 | } 17 | 18 | bool ObjLoader::Import(const char* pszFilename, bool needNorm, bool needAABB, bool forDX, bool swapYZ) 19 | { 20 | FILE* pFile; 21 | fopen_s(&pFile, pszFilename, "r"); 22 | 23 | if (!pFile) return false; 24 | 25 | m_stride = sizeof(float3); 26 | m_stride += needNorm ? sizeof(float3) : 0; 27 | 28 | // Import the OBJ file. 29 | uint32_t numTexc, numNorm; 30 | importGeometryFirstPass(pFile, numTexc, numNorm); 31 | rewind(pFile); 32 | importGeometrySecondPass(pFile, numTexc, numNorm, forDX, swapYZ); 33 | fclose(pFile); 34 | 35 | // Perform post import tasks. 36 | if (needNorm && !numNorm) recomputeNormals(); 37 | if (needAABB) computeAABB(); 38 | 39 | return true; 40 | } 41 | 42 | const uint32_t ObjLoader::GetNumVertices() const 43 | { 44 | return static_cast(m_vertices.size() / GetVertexStride()); 45 | } 46 | 47 | const uint32_t ObjLoader::GetNumIndices() const 48 | { 49 | return static_cast(m_indices.size()); 50 | } 51 | 52 | const uint32_t ObjLoader::GetVertexStride() const 53 | { 54 | return m_stride; 55 | } 56 | 57 | const uint8_t* ObjLoader::GetVertices() const 58 | { 59 | return m_vertices.data(); 60 | } 61 | 62 | const uint32_t* ObjLoader::GetIndices() const 63 | { 64 | return m_indices.data(); 65 | } 66 | 67 | const ObjLoader::AABB& ObjLoader::GetAABB() const 68 | { 69 | return m_aabb; 70 | } 71 | 72 | void ObjLoader::importGeometryFirstPass(FILE* pFile, uint32_t& numTexc, uint32_t& numNorm) 73 | { 74 | auto v = 0u; 75 | auto vt = 0u; 76 | auto vn = 0u; 77 | char buffer[256] = { 0 }; 78 | 79 | auto numVert = 0u; 80 | auto numTri = 0u; 81 | numTexc = 0; 82 | numNorm = 0; 83 | 84 | while (fscanf_s(pFile, "%s", buffer, static_cast(sizeof(buffer))) != EOF) 85 | { 86 | switch (buffer[0]) 87 | { 88 | case 'f': // v, v//vn, v/vt, v/vt/vn. 89 | fscanf_s(pFile, "%s", buffer, static_cast(sizeof(buffer))); 90 | 91 | if (strstr(buffer, "//")) // v//vn 92 | { 93 | sscanf_s(buffer, "%u//%u", &v, &vn); 94 | fscanf_s(pFile, "%u//%u", &v, &vn); 95 | fscanf_s(pFile, "%u//%u", &v, &vn); 96 | ++numTri; 97 | 98 | while (fscanf_s(pFile, "%u//%u", &v, &vn) > 0) ++numTri; 99 | } 100 | else if (sscanf_s(buffer, "%u/%u/%u", &v, &vt, &vn) == 3) // v/vt/vn 101 | { 102 | fscanf_s(pFile, "%u/%u/%u", &v, &vt, &vn); 103 | fscanf_s(pFile, "%u/%u/%u", &v, &vt, &vn); 104 | ++numTri; 105 | 106 | while (fscanf_s(pFile, "%u/%u/%u", &v, &vt, &vn) > 0) ++numTri; 107 | 108 | //m_hasTexcoord = true; 109 | } 110 | else if (sscanf_s(buffer, "%u/%u", &v, &vt) == 2) // v/vt 111 | { 112 | fscanf_s(pFile, "%u/%u", &v, &vt); 113 | fscanf_s(pFile, "%u/%u", &v, &vt); 114 | ++numTri; 115 | 116 | while (fscanf_s(pFile, "%u/%u", &v, &vt) > 0) ++numTri; 117 | 118 | //m_hasTexcoord = true; 119 | } 120 | else // v 121 | { 122 | fscanf_s(pFile, "%u", &v); 123 | fscanf_s(pFile, "%u", &v); 124 | ++numTri; 125 | 126 | while (fscanf_s(pFile, "%u", &v) > 0) 127 | ++numTri; 128 | } 129 | break; 130 | 131 | case 'v': // v, vt, or vn 132 | switch (buffer[1]) 133 | { 134 | case '\0': 135 | fgets(buffer, sizeof(buffer), pFile); 136 | ++numVert; 137 | break; 138 | case 't': 139 | fgets(buffer, sizeof(buffer), pFile); 140 | ++numTexc; 141 | break; 142 | case 'n': 143 | fgets(buffer, sizeof(buffer), pFile); 144 | ++numNorm; 145 | break; 146 | default: 147 | break; 148 | } 149 | break; 150 | 151 | default: 152 | fgets(buffer, sizeof(buffer), pFile); 153 | break; 154 | } 155 | } 156 | 157 | // Allocate memory for the OBJ model data. 158 | const auto numIdx = numTri * 3; 159 | m_stride += m_stride <= sizeof(float3) && numNorm ? sizeof(float3) : 0; 160 | m_stride += numTexc ? sizeof(float[2]) : 0; 161 | m_vertices.reserve(m_stride * (max)((max)(numVert, numTexc), numNorm)); 162 | m_vertices.resize(m_stride * numVert); 163 | m_indices.resize(numIdx); 164 | } 165 | 166 | void ObjLoader::importGeometrySecondPass(FILE* pFile, uint32_t numTexc, uint32_t numNorm, bool forDX, bool swapYZ) 167 | { 168 | auto numVert = 0u; 169 | auto numTri = 0u; 170 | char buffer[256] = { 0 }; 171 | 172 | vector normals; 173 | vector tIndices, nIndices; 174 | if (numTexc) tIndices.resize(m_indices.size()); 175 | if (numNorm) nIndices.resize(m_indices.size()); 176 | normals.reserve(numNorm); 177 | 178 | while (fscanf_s(pFile, "%s", buffer, static_cast(sizeof(buffer))) != EOF) 179 | { 180 | switch (buffer[0]) 181 | { 182 | case 'f': // v, v//vn, v/vt, or v/vt/vn. 183 | loadIndices(pFile, numTri, numTexc, numNorm, nIndices, tIndices); 184 | break; 185 | case 'v': // v, vn, or vt. 186 | switch (buffer[1]) 187 | { 188 | case '\0': // v 189 | { 190 | auto& p = getPosition(numVert++); 191 | fscanf_s(pFile, "%f %f %f", &p.x, &p.y, &p.z); 192 | if (swapYZ) 193 | { 194 | const auto tmp = p.y; 195 | p.y = p.z; 196 | p.z = tmp; 197 | } 198 | p.z = forDX ? -p.z : p.z; 199 | break; 200 | } 201 | case 'n': 202 | normals.emplace_back(); 203 | fscanf_s(pFile, "%f %f %f", 204 | &normals.back().x, 205 | &normals.back().y, 206 | &normals.back().z); 207 | if (swapYZ) 208 | { 209 | const auto tmp = normals.back().y; 210 | normals.back().y = normals.back().z; 211 | normals.back().z = tmp; 212 | } 213 | normals.back().z = forDX ? -normals.back().z : normals.back().z; 214 | default: 215 | break; 216 | } 217 | break; 218 | 219 | default: 220 | fgets(buffer, sizeof(buffer), pFile); 221 | break; 222 | } 223 | } 224 | 225 | computePerVertexNormals(normals, nIndices); 226 | 227 | if ((forDX && !swapYZ) || (!forDX && swapYZ)) reverse(m_indices.begin(), m_indices.end()); 228 | } 229 | 230 | void ObjLoader::loadIndices(FILE* pFile, uint32_t& numTri, uint32_t numTexc, 231 | uint32_t numNorm, vector& nIndices, vector& tIndices) 232 | { 233 | int64_t vi; 234 | uint32_t v[3] = { 0 }; 235 | uint32_t vt[3] = { 0 }; 236 | uint32_t vn[3] = { 0 }; 237 | 238 | const auto numVert = GetNumVertices(); 239 | 240 | for (uint8_t i = 0; i < 3; ++i) 241 | { 242 | fscanf_s(pFile, "%lld", &vi); 243 | v[i] = static_cast(vi < 0 ? vi + numVert : vi - 1); 244 | m_indices[numTri * 3 + i] = v[i]; 245 | 246 | if (tIndices.size() > 0) 247 | { 248 | fscanf_s(pFile, "/%lld", &vi); 249 | vt[i] = static_cast(vi < 0 ? vi + numTexc : vi - 1); 250 | tIndices[numTri * 3 + i] = vt[i]; 251 | } 252 | else if (nIndices.size() > 0) fscanf_s(pFile, "/"); 253 | 254 | if (nIndices.size() > 0) 255 | { 256 | fscanf_s(pFile, "/%lld", &vi); 257 | vn[i] = static_cast(vi < 0 ? vi + numNorm : vi - 1); 258 | nIndices[numTri * 3 + i] = vn[i]; 259 | } 260 | } 261 | ++numTri; 262 | 263 | v[1] = v[2]; 264 | vt[1] = vt[2]; 265 | vn[1] = vn[2]; 266 | 267 | while (fscanf_s(pFile, "%lld", &vi) > 0) 268 | { 269 | v[2] = static_cast(vi < 0 ? vi + numVert : vi - 1); 270 | m_indices[numTri * 3] = v[0]; 271 | m_indices[numTri * 3 + 1] = v[1]; 272 | m_indices[numTri * 3 + 2] = v[2]; 273 | v[1] = v[2]; 274 | 275 | if (tIndices.size() > 0) 276 | { 277 | fscanf_s(pFile, "/%lld", &vi); 278 | vt[2] = static_cast(vi < 0 ? vi + numTexc : vi - 1); 279 | tIndices[numTri * 3] = vt[0]; 280 | tIndices[numTri * 3 + 1] = vt[1]; 281 | tIndices[numTri * 3 + 2] = vt[2]; 282 | vt[1] = vt[2]; 283 | } 284 | else if (nIndices.size() > 0) fscanf_s(pFile, "/"); 285 | 286 | if (nIndices.size() > 0) 287 | { 288 | fscanf_s(pFile, "/%lld", &vi); 289 | vn[2] = static_cast(vi < 0 ? vi + numNorm : vi - 1); 290 | nIndices[numTri * 3] = vn[0]; 291 | nIndices[numTri * 3 + 1] = vn[1]; 292 | nIndices[numTri * 3 + 2] = vn[2]; 293 | vn[1] = vn[2]; 294 | } 295 | 296 | ++numTri; 297 | } 298 | } 299 | 300 | void ObjLoader::computePerVertexNormals(const vector& normals, const vector& nIndices) 301 | { 302 | if (normals.empty()) return; 303 | 304 | const auto stride = GetVertexStride(); 305 | vector vni(GetNumVertices(), UINT32_MAX); 306 | 307 | const auto numIdx = static_cast(m_indices.size()); 308 | for (auto i = 0u; i < numIdx; i++) 309 | { 310 | auto vi = m_indices[i]; 311 | if (vni[vi] == nIndices[i]) continue; 312 | 313 | if (vni[vi] < UINT32_MAX) 314 | { 315 | // Split vertex 316 | vi = GetNumVertices(); 317 | m_vertices.resize(m_vertices.size() + stride); 318 | const auto pDst = getVertex(vi); 319 | const auto pSrc = getVertex(m_indices[i]); 320 | memcpy(pDst, pSrc, stride); 321 | m_indices[i] = vi; 322 | } 323 | else vni[vi] = nIndices[i]; 324 | 325 | float3 n = normals[nIndices[i]]; 326 | const auto l = sqrt(n.x * n.x + n.y * n.y + n.z * n.z); 327 | n.x /= l; 328 | n.y /= l; 329 | n.z /= l; 330 | 331 | getNormal(vi) = n; 332 | } 333 | 334 | m_vertices.shrink_to_fit(); 335 | } 336 | 337 | void ObjLoader::recomputeNormals() 338 | { 339 | float3 e1, e2, n; 340 | 341 | const auto numTri = static_cast(m_indices.size()) / 3; 342 | for (auto i = 0u; i < numTri; i++) 343 | { 344 | const auto pv0 = &getPosition(m_indices[i * 3]); 345 | const auto pv1 = &getPosition(m_indices[i * 3 + 1]); 346 | const auto pv2 = &getPosition(m_indices[i * 3 + 2]); 347 | e1.x = pv1->x - pv0->x; 348 | e1.y = pv1->y - pv0->y; 349 | e1.z = pv1->z - pv0->z; 350 | e2.x = pv2->x - pv1->x; 351 | e2.y = pv2->y - pv1->y; 352 | e2.z = pv2->z - pv1->z; 353 | n.x = e1.y * e2.z - e1.z * e2.y; 354 | n.y = e1.z * e2.x - e1.x * e2.z; 355 | n.z = e1.x * e2.y - e1.y * e2.x; 356 | const auto l = sqrt(n.x * n.x + n.y * n.y + n.z * n.z); 357 | n.x /= l; 358 | n.y /= l; 359 | n.z /= l; 360 | 361 | const auto pVn0 = &getNormal(m_indices[i * 3]); 362 | const auto pVn1 = &getNormal(m_indices[i * 3 + 1]); 363 | const auto pVn2 = &getNormal(m_indices[i * 3 + 2]); 364 | pVn0->x += n.x; 365 | pVn0->y += n.y; 366 | pVn0->z += n.z; 367 | pVn1->x += n.x; 368 | pVn1->y += n.y; 369 | pVn1->z += n.z; 370 | pVn2->x += n.x; 371 | pVn2->y += n.y; 372 | pVn2->z += n.z; 373 | } 374 | 375 | const auto numVert = GetNumVertices(); 376 | for (auto i = 0u; i < numVert; ++i) 377 | { 378 | const auto pVn = &getNormal(i); 379 | const auto l = sqrt(pVn->x * pVn->x + pVn->y * pVn->y + pVn->z * pVn->z); 380 | pVn->x /= l; 381 | pVn->y /= l; 382 | pVn->z /= l; 383 | } 384 | } 385 | 386 | void ObjLoader::computeAABB() 387 | { 388 | float xMax, xMin, yMax, yMin, zMax, zMin; 389 | const auto& p = getPosition(0); 390 | xMax = xMin = p.x; 391 | yMax = yMin = p.y; 392 | zMax = zMin = p.z; 393 | 394 | auto x = 0.0f, y = 0.0f, z = 0.0f; 395 | 396 | const auto numVert = GetNumVertices(); 397 | for (auto i = 1u; i < numVert; ++i) 398 | { 399 | const auto& p = getPosition(i); 400 | x = p.x; 401 | y = p.y; 402 | z = p.z; 403 | 404 | if (x < xMin) xMin = x; 405 | else if (x > xMax) xMax = x; 406 | 407 | if (y < yMin) yMin = y; 408 | else if (y > yMax) yMax = y; 409 | 410 | if (z < zMin) zMin = z; 411 | else if (z > zMax) zMax = z; 412 | } 413 | 414 | m_aabb.Min = float3(xMin, yMin, zMin); 415 | m_aabb.Max = float3(xMax, yMax, zMax); 416 | } 417 | 418 | void* ObjLoader::getVertex(uint32_t i) 419 | { 420 | return &m_vertices[GetVertexStride() * i]; 421 | } 422 | 423 | ObjLoader::float3& ObjLoader::getPosition(uint32_t i) 424 | { 425 | return reinterpret_cast(getVertex(i))[0]; 426 | } 427 | 428 | ObjLoader::float3& ObjLoader::getNormal(uint32_t i) 429 | { 430 | return reinterpret_cast(getVertex(i))[1]; 431 | } 432 | -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Optional/XUSGObjLoader.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | namespace XUSG 8 | { 9 | class ObjLoader 10 | { 11 | public: 12 | struct float3 13 | { 14 | float x; 15 | float y; 16 | float z; 17 | 18 | float3() = default; 19 | constexpr float3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} 20 | explicit float3(const float* pArray) : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} 21 | 22 | float3& operator= (const float3& Float3) { x = Float3.x; y = Float3.y; z = Float3.z; return *this; } 23 | }; 24 | 25 | struct AABB 26 | { 27 | float3 Min; 28 | float3 Max; 29 | }; 30 | 31 | ObjLoader(); 32 | virtual ~ObjLoader(); 33 | 34 | bool Import(const char* pszFilename, bool needNorm = true, 35 | bool needAABB = true, bool forDX = true, bool swapYZ = false); 36 | 37 | const uint32_t GetNumVertices() const; 38 | const uint32_t GetNumIndices() const; 39 | const uint32_t GetVertexStride() const; 40 | const uint8_t* GetVertices() const; 41 | const uint32_t* GetIndices() const; 42 | 43 | const AABB& GetAABB() const; 44 | 45 | protected: 46 | void importGeometryFirstPass(FILE* pFile, uint32_t& numTexc, uint32_t& numNorm); 47 | void importGeometrySecondPass(FILE* pFile, uint32_t numTexc, uint32_t numNorm, bool forDX, bool swapYZ); 48 | void loadIndices(FILE* pFile, uint32_t& numTri, uint32_t numTexc, uint32_t numNorm, 49 | std::vector& nIndices, std::vector& tIndices); 50 | void computePerVertexNormals(const std::vector& normals, const std::vector& nIndices); 51 | void recomputeNormals(); 52 | void computeAABB(); 53 | 54 | void* getVertex(uint32_t i); 55 | float3& getPosition(uint32_t i); 56 | float3& getNormal(uint32_t i); 57 | 58 | std::vector m_vertices; 59 | std::vector m_indices; 60 | 61 | uint32_t m_stride; 62 | 63 | AABB m_aabb; 64 | }; 65 | } 66 | -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Shaders/SHIrradiance.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #ifndef PI 6 | #define PI 3.1415926535897 7 | #endif 8 | #define SH_NUM_COEFF (SH_ORDER * SH_ORDER) 9 | 10 | //-------------------------------------------------------------------------------------- 11 | // Load spherical harmonics 12 | //-------------------------------------------------------------------------------------- 13 | void LoadSH(out float3 shCoeffs[SH_NUM_COEFF], StructuredBuffer roSHCoeffs) 14 | { 15 | [unroll] 16 | for (uint i = 0; i < SH_NUM_COEFF; ++i) shCoeffs[i] = roSHCoeffs[i]; 17 | } 18 | 19 | //-------------------------------------------------------------------------------------- 20 | // Evaluate irradiance using spherical harmonics 21 | //-------------------------------------------------------------------------------------- 22 | #include "SHIrradianceTypeless.hlsli" 23 | #undef SH_COEFFS 24 | #undef T 25 | 26 | #define T float3 27 | #define SH_COEFFS shCoeffs[SH_NUM_COEFF] 28 | #include "SHIrradianceTypeless.hlsli" 29 | #undef SH_COEFFS 30 | #undef T 31 | -------------------------------------------------------------------------------- /RayTracedGGX/XUSG/Shaders/SHIrradianceTypeless.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #ifndef T 6 | #define T StructuredBuffer 7 | #endif 8 | 9 | #ifndef SH_COEFFS 10 | #define SH_COEFFS shCoeffs 11 | #endif 12 | 13 | //-------------------------------------------------------------------------------------- 14 | // SH irradiance evaluation using normal 15 | //-------------------------------------------------------------------------------------- 16 | float4 EvaluateSHIrradiance(T SH_COEFFS, float3 norm) 17 | { 18 | const float c1 = 0.42904276540489171563379376569857; // 4 * A2 * Y22 = 1/16 * sqrt(15PI)/PI * PI = 1/16 * sqrt(15PI) 19 | const float c2 = 0.51166335397324424423977581244463; // 1/2 * A1 * Y10 = 1/2 * sqrt(PI/3)/PI * PI = 1/2 * sqrt(PI/3) 20 | const float c3 = 0.24770795610037568833406429782001; // A2 * Y20 = 1/16 * sqrt(5PI)/PI * PI = 1/16 * sqrt(5PI) 21 | const float c4 = 0.88622692545275801364908374167057; // A0 * Y00 = 1/2 * sqrt(PI)/PI * PI = 1/2 * sqrt(PI) 22 | 23 | const float x = -norm.x; 24 | const float y = -norm.y; 25 | const float z = norm.z; 26 | 27 | const float3 irradiance = max(0.0, 28 | (c1 * (x * x - y * y)) * shCoeffs[8] // c1 * L22.(x^2 - y^2) 29 | + (c3 * (3.0 * z * z - 1.0)) * shCoeffs[6] // c3 * L20.(3z^2 - 1) 30 | + c4 * shCoeffs[0] // c4 * L00 31 | + 2.0 * c1 * (shCoeffs[4] * x * y + shCoeffs[7] * x * z + shCoeffs[5] * y * z) // 2c1(L2-2.xy + L21.xz + L2-1.yz) 32 | + 2.0 * c2 * (shCoeffs[3] * x + shCoeffs[1] * y + shCoeffs[2] * z)); // 2c2(L11.x + L1-1.y + L10.z) 33 | 34 | const float avgLum = dot(shCoeffs[0], float3(0.25, 0.5, 0.25)); 35 | 36 | return float4(irradiance, avgLum); 37 | } 38 | 39 | //-------------------------------------------------------------------------------------- 40 | // SH irradiance evaluation using tangent for hair 41 | //-------------------------------------------------------------------------------------- 42 | float4 EvaluateHairSHIrradiance(T SH_COEFFS, float3 tan) 43 | { 44 | const float c1 = 0.67393879993592845307140549769869; // 4 * A2.Y22 = 1/16 * sqrt(15PI)/PI * PI^2/2 = PI/32 * sqrt(15PI) 45 | const float c2 = 0.80371891697672903141037740805026; // 1/2 * A1.Y10 = 1/2 * sqrt(PI/3)/PI * PI^2/2 = PI/4 * sqrt(PI/3) 46 | const float c3 = 0.38909874756034163531575854238775; // A2 * Y20 = 1/16 * sqrt(5PI)/PI * PI^2/2 = PI/32 * sqrt(5PI) 47 | const float c4 = 1.3920819992079269613212044955297; // A0 * Y00 = 1/2 * sqrt(PI)/PI * PI^2/2 = PI/4 * sqrt(PI) 48 | 49 | const float x = -tan.x; 50 | const float y = -tan.y; 51 | const float z = tan.z; 52 | 53 | const float3 irradiance = max(0.0, 54 | (c1 * (x * x - y * y)) * shCoeffs[8] // c1 * L22.(x^2 - y^2) 55 | + (c3 * (3.0 * z * z - 1.0)) * shCoeffs[6] // c3 * L20.(3z^2 - 1) 56 | + c4 * shCoeffs[0] // c4 * L00 57 | + 2.0 * c1 * (shCoeffs[4] * x * y + shCoeffs[7] * x * z + shCoeffs[5] * y * z) // 2c1(L2-2.xy + L21.xz + L2-1.yz) 58 | + 2.0 * c2 * (shCoeffs[3] * x + shCoeffs[1] * y + shCoeffs[2] * z)); // 2c2(L11.x + L1-1.y + L10.z) 59 | 60 | const float avgLum = dot(shCoeffs[0], float3(0.25, 0.5, 0.25)); 61 | 62 | return float4(irradiance, avgLum); 63 | } 64 | -------------------------------------------------------------------------------- /RayTracedGGX/dxc/LICENCE-MIT.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Corporation. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /RayTracedGGX/dxc/LICENSE-LLVM.txt: -------------------------------------------------------------------------------- 1 | ============================================================================== 2 | LLVM Release License 3 | ============================================================================== 4 | University of Illinois/NCSA 5 | Open Source License 6 | 7 | Copyright (c) 2003-2015 University of Illinois at Urbana-Champaign. 8 | All rights reserved. 9 | 10 | Developed by: 11 | 12 | LLVM Team 13 | 14 | University of Illinois at Urbana-Champaign 15 | 16 | http://llvm.org 17 | 18 | Permission is hereby granted, free of charge, to any person obtaining a copy of 19 | this software and associated documentation files (the "Software"), to deal with 20 | the Software without restriction, including without limitation the rights to 21 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 22 | of the Software, and to permit persons to whom the Software is furnished to do 23 | so, subject to the following conditions: 24 | 25 | * Redistributions of source code must retain the above copyright notice, 26 | this list of conditions and the following disclaimers. 27 | 28 | * Redistributions in binary form must reproduce the above copyright notice, 29 | this list of conditions and the following disclaimers in the 30 | documentation and/or other materials provided with the distribution. 31 | 32 | * Neither the names of the LLVM Team, University of Illinois at 33 | Urbana-Champaign, nor the names of its contributors may be used to 34 | endorse or promote products derived from this Software without specific 35 | prior written permission. 36 | 37 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 38 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 39 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 40 | CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 41 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 42 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE 43 | SOFTWARE. 44 | -------------------------------------------------------------------------------- /RayTracedGGX/dxc/LICENSE-MS.txt: -------------------------------------------------------------------------------- 1 | MICROSOFT SOFTWARE LICENSE TERMS 2 | 3 | MICROSOFT DIRECTX SHADER COMPILER 4 | 5 | These license terms are an agreement between you and Microsoft 6 | Corporation (or one of its affiliates). They apply to the software named 7 | above and any Microsoft services or software updates (except to the 8 | extent such services or updates are accompanied by new or additional 9 | terms, in which case those different terms apply prospectively and do 10 | not alter your or Microsoft’s rights relating to pre-updated software or 11 | services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS 12 | BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. 13 | 14 | INSTALLATION AND USE RIGHTS. 15 | 16 | General. Subject to the terms of this agreement, you may install and use any number of copies of the software, and solely for use on Windows. 17 | 18 | Included Microsoft Applications. The software may include other Microsoft applications. These license terms apply to those included applications, if any, unless other license terms are provided with the other Microsoft applications. 19 | 20 | Microsoft Platforms. The software may include components from Microsoft Windows. These components are governed by separate agreements and their own product support policies, as described in the license terms found in the installation directory for that component or in the “Licenses” folder accompanying the software. 21 | 22 | Third Party Components. The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) accompanying the software. 23 | 24 | DATA. 25 | 26 | Data Collection. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may opt-out of many of these scenarios, but not all, as described in the product documentation.  There are also some features in the software that may enable you to collect data from users of your applications. If you use these features to enable data collection in your applications, you must comply with applicable law, including providing appropriate notices to users of your applications. You can learn more about data collection and use in the help documentation and the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to these practices. 27 | 28 | Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. 29 | 30 | DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make available for third parties) in applications you develop, as described in this Section. 31 | 32 | Distribution Rights. The code and test files described below are distributable if included with the software. 33 | 34 | Distributables. You may copy and distribute the object code form of the software listed in the distributables file list in the software; and 35 | 36 | Third Party Distribution. You may permit distributors of your applications to copy and distribute any of this distributable code you elect to distribute with your applications. 37 | 38 | Distribution Requirements. For any code you distribute, you must: 39 | 40 | add significant primary functionality to it in your applications; 41 | 42 | i. require distributors and external end users to agree to terms that protect it and Microsoft at least as much as this agreement; and 43 | 44 | ii. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified distributable code. 45 | 46 | Distribution Restrictions. You may not: 47 | 48 | use Microsoft’s trademarks or trade dress in your application in any way that suggests your application comes from or is endorsed by Microsoft; or modify or distribute the source code of any distributable code so that any part of it becomes subject to any license that requires that the distributable code, any other part of the software, or any of Microsoft’s other intellectual property be disclosed or distributed in source code form, or that others have the right to modify it. 49 | 50 | SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to): 51 | 52 | work around any technical limitations in the software that only allow you to use it in certain ways; 53 | 54 | reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software; 55 | 56 | remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software; 57 | 58 | use the software in any way that is against the law or to create or propagate malware; or 59 | 60 | share, publish, distribute, or lease the software (except for any distributable code, subject to the terms above), provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party. 61 | 62 | EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit https://aka.ms/exporting. 63 | 64 | SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind. 65 | 66 | UPDATES. The software may periodically check for updates, and download and install them for you. You may obtain updates only from Microsoft or authorized sources. Microsoft may need to update your system to provide you with updates. You agree to receive these automatic updates without any additional notice. Updates may not include or support all existing software features, services, or peripheral devices. 67 | 68 | ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software. 69 | 70 | APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court. 71 | 72 | CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you: 73 | 74 | a. Australia. You have statutory guarantees under the Australian 75 | Consumer Law and nothing in this agreement is intended to affect 76 | those rights. 77 | 78 | b. Canada. If you acquired this software in Canada, you may stop 79 | receiving updates by turning off the automatic update feature, 80 | disconnecting your device from the Internet (if and when you 81 | re-connect to the Internet, however, the software will resume 82 | checking for and installing updates), or uninstalling the software. 83 | The product documentation, if any, may also specify how to turn off 84 | updates for your specific device or software. 85 | 86 | c. Germany and Austria. 87 | 88 | i. Warranty. The properly licensed software will perform substantially 89 | as described in any Microsoft materials that accompany the software. 90 | However, Microsoft gives no contractual guarantee in relation to the 91 | licensed software. 92 | 93 | ii. Limitation of Liability. In case of intentional conduct, gross 94 | negligence, claims based on the Product Liability Act, as well as, in 95 | case of death or personal or physical injury, Microsoft is liable 96 | according to the statutory law. 97 | 98 | Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence. 99 | 100 | DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. 101 | 102 | LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT, OR INCIDENTAL DAMAGES. 103 | 104 | This limitation applies to (a) anything related to the software, 105 | services, content (including code) on third party Internet sites, or 106 | third party applications; and (b) claims for breach of contract, 107 | warranty, guarantee, or condition; strict liability, negligence, or 108 | other tort; or any other claim; in each case to the extent permitted by 109 | applicable law. 110 | 111 | It also applies even if Microsoft knew or should have known about the 112 | possibility of the damages. The above limitation or exclusion may not 113 | apply to you because your state, province, or country may not allow the 114 | exclusion or limitation of incidental, consequential, or other damages. 115 | 116 | Please note: As this software is distributed in Canada, some of the 117 | clauses in this agreement are provided below in French. 118 | 119 | Remarque: Ce logiciel étant distribué au Canada, certaines des clauses 120 | dans ce contrat sont fournies ci-dessous en français. 121 | 122 | EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « 123 | tel quel ». Toute utilisation de ce logiciel est à votre seule risque et 124 | péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez 125 | bénéficier de droits additionnels en vertu du droit local sur la 126 | protection des consommateurs, que ce contrat ne peut modifier. La ou 127 | elles sont permises par le droit locale, les garanties implicites de 128 | qualité marchande, d’adéquation à un usage particulier et d’absence de 129 | contrefaçon sont exclues. 130 | 131 | LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES 132 | DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une 133 | indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ 134 | US. Vous ne pouvez prétendre à aucune indemnisation pour les autres 135 | dommages, y compris les dommages spéciaux, indirects ou accessoires et 136 | pertes de bénéfices. 137 | 138 | Cette limitation concerne: 139 | 140 | • tout ce qui est relié au logiciel, aux services ou au contenu (y 141 | compris le code) figurant sur des sites Internet tiers ou dans des 142 | programmes tiers; et 143 | 144 | • les réclamations au titre de violation de contrat ou de garantie, ou 145 | au titre de responsabilité stricte, de négligence ou d’une autre faute 146 | dans la limite autorisée par la loi en vigueur. 147 | 148 | Elle s’applique également, même si Microsoft connaissait ou devrait 149 | connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas 150 | l’exclusion ou la limitation de responsabilité pour les dommages 151 | indirects, accessoires ou de quelque nature que ce soit, il se peut que 152 | la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre 153 | égard. 154 | 155 | EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. 156 | Vous pourriez avoir d’autres droits prévus par les lois de votre pays. 157 | Le présent contrat ne modifie pas les droits que vous confèrent les lois 158 | de votre pays si celles-ci ne le permettent pas. 159 | -------------------------------------------------------------------------------- /RayTracedGGX/stdafx.cpp: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | #include "stdafx.h" 13 | -------------------------------------------------------------------------------- /RayTracedGGX/stdafx.h: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // 3 | // Copyright (c) Microsoft. All rights reserved. 4 | // This code is licensed under the MIT License (MIT). 5 | // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 6 | // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 7 | // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 8 | // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 9 | // 10 | //********************************************************* 11 | 12 | // stdafx.h : include file for standard system include files, 13 | // or project specific include files that are used frequently, but 14 | // are changed infrequently. 15 | 16 | #pragma once 17 | 18 | #ifndef WIN32_LEAN_AND_MEAN 19 | #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers. 20 | #endif 21 | 22 | #define XUSG_INTERFACE __declspec(dllimport) 23 | 24 | #include 25 | 26 | #include "d3d12.h" 27 | #include 28 | #include 29 | #include 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #if _HAS_CXX17 37 | #include 38 | #else 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #endif 45 | #include 46 | #include 47 | #include 48 | 49 | #include "D3D12RaytracingFallback.h" 50 | 51 | #if defined(DEBUG) | defined(_DEBUG) 52 | #ifndef DBG_NEW 53 | #define DBG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__) 54 | #define new DBG_NEW 55 | #endif 56 | #endif // _DEBUG 57 | --------------------------------------------------------------------------------