├── .gitattributes ├── .gitignore ├── Bin ├── CSIntegrate.cso ├── PSDrawParticles.cso ├── RTDensity.cso ├── RTForce.cso ├── RayTracedSPH.exe ├── VSDrawParticles.cso ├── WinPixEventRuntime.dll ├── XUSG-EZ.dll ├── XUSG.dll ├── XUSGRayTracing-EZ.dll ├── XUSGRayTracing.dll ├── dxcompiler.dll ├── dxil.dll └── dxrfallbackcompiler.dll ├── LICENSE ├── README.md ├── RayTracedSPH.sln └── RayTracedSPH ├── 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 ├── FluidEZ.cpp ├── FluidEZ.h ├── Shaders │ ├── CSIntegrate.hlsl │ ├── Common.hlsli │ ├── PSDrawParticles.hlsl │ ├── RTCommon.hlsli │ ├── RTDensity.hlsl │ ├── RTForce.hlsl │ └── VSDrawParticles.hlsl └── SharedConst.h ├── Main.cpp ├── RayTracedSPH.cpp ├── RayTracedSPH.h ├── RayTracedSPH.vcxproj ├── RayTracedSPH.vcxproj.filters ├── RayTracedSPH.vcxproj.user ├── XUSG ├── Bin │ └── x64 │ │ ├── Debug │ │ ├── XUSG-EZ.dll │ │ ├── XUSG-EZ.lib │ │ ├── XUSG-EZ.pdb │ │ ├── XUSG.dll │ │ ├── XUSG.lib │ │ ├── XUSG.pdb │ │ ├── XUSGRayTracing-EZ.dll │ │ ├── XUSGRayTracing-EZ.lib │ │ ├── XUSGRayTracing-EZ.pdb │ │ ├── XUSGRayTracing.dll │ │ ├── XUSGRayTracing.lib │ │ └── XUSGRayTracing.pdb │ │ └── Release │ │ ├── XUSG-EZ.dll │ │ ├── XUSG-EZ.lib │ │ ├── XUSG.dll │ │ ├── XUSG.lib │ │ ├── XUSGRayTracing-EZ.dll │ │ ├── XUSGRayTracing-EZ.lib │ │ ├── XUSGRayTracing.dll │ │ └── XUSGRayTracing.lib ├── Core │ └── XUSG.h ├── Helper │ ├── XUSG-EZ.h │ ├── XUSGRayTracing-EZ.h │ └── XUSGUltimate-EZ.h ├── RayTracing │ └── XUSGRayTracing.h └── 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 | -------------------------------------------------------------------------------- /.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/CSIntegrate.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/CSIntegrate.cso -------------------------------------------------------------------------------- /Bin/PSDrawParticles.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/PSDrawParticles.cso -------------------------------------------------------------------------------- /Bin/RTDensity.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/RTDensity.cso -------------------------------------------------------------------------------- /Bin/RTForce.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/RTForce.cso -------------------------------------------------------------------------------- /Bin/RayTracedSPH.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/RayTracedSPH.exe -------------------------------------------------------------------------------- /Bin/VSDrawParticles.cso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/VSDrawParticles.cso -------------------------------------------------------------------------------- /Bin/WinPixEventRuntime.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/WinPixEventRuntime.dll -------------------------------------------------------------------------------- /Bin/XUSG-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/XUSG-EZ.dll -------------------------------------------------------------------------------- /Bin/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/XUSG.dll -------------------------------------------------------------------------------- /Bin/XUSGRayTracing-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/XUSGRayTracing-EZ.dll -------------------------------------------------------------------------------- /Bin/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/XUSGRayTracing.dll -------------------------------------------------------------------------------- /Bin/dxcompiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/dxcompiler.dll -------------------------------------------------------------------------------- /Bin/dxil.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/dxil.dll -------------------------------------------------------------------------------- /Bin/dxrfallbackcompiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/Bin/dxrfallbackcompiler.dll -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 StarsX 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RayTracedSPH 2 | Real-time fluid simulation using smoothed particle hydrodynamics (SPH) by taking advantage of GPU hardware ray tracing for particle neighbor search. A Zero-length ray represents a particle point and a particle AABB represent the impact range determined by the position and smoothing radius. Procerual mode of GPU ray tracing pipeline with any hit shader is leveraged to implement the neighbor search algorithm based on the sparse grid scheme of BVH. 3 | 4 | DXR fallback layer was expected to be supported for the legacy generations of GPUs, but it seems IgnoreHit() has some bug in the any hit shader on DXR fallback layer unfortunately. 5 | 6 | Hot keys: 7 | 8 | [F1] show/hide FPS 9 | 10 | [Space] pause/play animation 11 | 12 | Prerequisite: https://github.com/StarsX/XUSG 13 | -------------------------------------------------------------------------------- /RayTracedSPH.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.32413.511 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RayTracedSPH", "RayTracedSPH\RayTracedSPH.vcxproj", "{20AD8700-447F-4B0B-9A95-0E1C646F3878}" 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 | {20AD8700-447F-4B0B-9A95-0E1C646F3878}.Debug|x64.ActiveCfg = Debug|x64 15 | {20AD8700-447F-4B0B-9A95-0E1C646F3878}.Debug|x64.Build.0 = Debug|x64 16 | {20AD8700-447F-4B0B-9A95-0E1C646F3878}.Release|x64.ActiveCfg = Release|x64 17 | {20AD8700-447F-4B0B-9A95-0E1C646F3878}.Release|x64.Build.0 = Release|x64 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C9B991C8-D5EB-434A-A63E-923AA3006A5F} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /RayTracedSPH/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); -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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. -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/FluidEZ.cpp: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "FluidEZ.h" 6 | #include "SharedConst.h" 7 | 8 | using namespace std; 9 | using namespace DirectX; 10 | using namespace XUSG; 11 | using namespace XUSG::RayTracing; 12 | 13 | const wchar_t* FluidEZ::HitGroupName = L"hitGroup"; 14 | const wchar_t* FluidEZ::RaygenShaderName = L"raygenMain"; 15 | const wchar_t* FluidEZ::IntersectionShaderName = L"intersectionMain"; 16 | const wchar_t* FluidEZ::AnyHitShaderName = L"anyHitMain"; 17 | const wchar_t* FluidEZ::MissShaderName = L"missMain"; 18 | 19 | const float POOL_VOLUME_DIM = 1.0f; 20 | const float POOL_SPACE_DIVISION = 50.0f; 21 | const float INIT_PARTICLE_VOLUME_DIM = 0.6f; 22 | const float INIT_PARTICLE_VOLUME_CENTER[] = 23 | { 24 | -0.45f * (POOL_VOLUME_DIM - INIT_PARTICLE_VOLUME_DIM), 25 | POOL_VOLUME_DIM - INIT_PARTICLE_VOLUME_DIM * 0.5f, 26 | 0.45f * (POOL_VOLUME_DIM - INIT_PARTICLE_VOLUME_DIM) 27 | }; 28 | const float PARTICLE_REST_DENSITY = 1000.0f; 29 | const float PARTICLE_SMOOTH_RADIUS = POOL_VOLUME_DIM / POOL_SPACE_DIVISION; 30 | 31 | struct CBSimulation 32 | { 33 | float SmoothRadius; 34 | float PressureStiffness; 35 | float RestDensity; 36 | float DensityCoef; 37 | float PressureGradCoef; 38 | float ViscosityLaplaceCoef; 39 | float WallStiffness; 40 | uint32_t NumParticles; // Padding 41 | XMFLOAT4 Planes[6]; 42 | }; 43 | 44 | struct CBVisualization 45 | { 46 | XMFLOAT4X4 ViewProj; 47 | }; 48 | 49 | struct CBPerFrame 50 | { 51 | float TimeStep; 52 | XMFLOAT3 Gravity; 53 | }; 54 | 55 | struct Particle 56 | { 57 | XMFLOAT3 Pos; 58 | XMFLOAT3 Velocity; 59 | }; 60 | 61 | struct ParticleAABB 62 | { 63 | XMFLOAT3 Min; 64 | XMFLOAT3 Max; 65 | }; 66 | 67 | FluidEZ::FluidEZ() : 68 | m_instances() 69 | { 70 | m_shaderLib = ShaderLib::MakeUnique(); 71 | } 72 | 73 | FluidEZ::~FluidEZ() 74 | { 75 | } 76 | 77 | bool FluidEZ::Init(RayTracing::EZ::CommandList* pCommandList, uint32_t width, uint32_t height, 78 | vector& uploaders, uint32_t numParticles) 79 | { 80 | const auto pDevice = pCommandList->GetRTDevice(); 81 | 82 | m_viewport.x = static_cast(width); 83 | m_viewport.y = static_cast(height); 84 | m_numParticles = numParticles; 85 | 86 | // Create resources with data upload 87 | createParticleBuffers(pCommandList, uploaders); 88 | createConstBuffers(pCommandList, uploaders); 89 | 90 | // Create density buffer 91 | m_densityBuffer = TypedBuffer::MakeUnique(); 92 | XUSG_N_RETURN(m_densityBuffer->Create(pDevice, m_numParticles, sizeof(float), Format::R32_FLOAT, 93 | ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT), false); 94 | 95 | // Create particle Acceleration buffer 96 | m_accelerationBuffer = TypedBuffer::MakeUnique(); 97 | XUSG_N_RETURN(m_accelerationBuffer->Create(pDevice, m_numParticles, sizeof(uint16_t[4]), Format::R16G16B16A16_FLOAT, 98 | ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT), false); 99 | 100 | XUSG_N_RETURN(buildAccelerationStructures(pCommandList), false); 101 | XUSG_N_RETURN(pCommandList->CreatePipelineLayouts(nullptr, nullptr, 102 | nullptr, nullptr, nullptr, nullptr, nullptr, 103 | nullptr, nullptr, nullptr, 1, 1), false); 104 | 105 | return createShaders(); 106 | } 107 | 108 | void FluidEZ::UpdateFrame(uint8_t frameIndex, float timeStep, CXMMATRIX viewProj, CXMVECTOR viewY) 109 | { 110 | const auto gravity = -9.8f * viewY; 111 | const auto pCbPerFrame = static_cast(m_cbPerFrame->Map(frameIndex)); 112 | pCbPerFrame->TimeStep = timeStep; 113 | XMStoreFloat3(&pCbPerFrame->Gravity, gravity); 114 | 115 | const auto pCbVisualization = static_cast(m_cbVisualization->Map(frameIndex)); 116 | XMStoreFloat4x4(&pCbVisualization->ViewProj, XMMatrixTranspose(viewProj)); 117 | } 118 | 119 | void FluidEZ::Render(RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex, 120 | RenderTarget* pRenderTarget, DepthStencil* pDepthStencil) 121 | { 122 | Simulate(pCommandList, frameIndex); 123 | Visualize(pCommandList, frameIndex, pRenderTarget, pDepthStencil); 124 | } 125 | 126 | void FluidEZ::Simulate(RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex) 127 | { 128 | pCommandList->BuildBLAS(m_bottomLevelAS.get()); 129 | pCommandList->BuildTLAS(m_topLevelAS.get(), m_instances.get()); 130 | 131 | // Set TLAS 132 | pCommandList->SetTopLevelAccelerationStructure(0, m_topLevelAS.get()); 133 | 134 | // Set CBV 135 | const XUSG::EZ::ResourceView cbvs[] = 136 | { 137 | XUSG::EZ::GetCBV(m_cbSimulation.get()), 138 | XUSG::EZ::GetCBV(m_cbPerFrame.get(), frameIndex) 139 | }; 140 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::CBV, 0, static_cast(size(cbvs)), cbvs); 141 | 142 | computeDensity(pCommandList); 143 | computeAcceleration(pCommandList); 144 | integrate(pCommandList); 145 | } 146 | 147 | void FluidEZ::Visualize(RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex, 148 | RenderTarget* pRenderTarget, DepthStencil* pDepthStencil) 149 | { 150 | // Set pipeline state 151 | pCommandList->SetGraphicsShader(Shader::Stage::VS, m_shaders[VS_DRAW_PARTICLES]); 152 | pCommandList->SetGraphicsShader(Shader::Stage::PS, m_shaders[PS_DRAW_PARTICLES]); 153 | pCommandList->DSSetState(XUSG::Graphics::DepthStencilPreset::DEFAULT_LESS); 154 | 155 | // Set render target 156 | const auto rtv = XUSG::EZ::GetRTV(pRenderTarget); 157 | const auto dsv = XUSG::EZ::GetDSV(pDepthStencil); 158 | pCommandList->OMSetRenderTargets(1, &rtv, &dsv); 159 | 160 | // Set CBV 161 | const auto cbv = XUSG::EZ::GetCBV(m_cbVisualization.get(), frameIndex); 162 | pCommandList->SetResources(Shader::Stage::VS, DescriptorType::CBV, 0, 1, &cbv); 163 | 164 | // Set SRV 165 | const auto srv = XUSG::EZ::GetSRV(m_particleBuffer.get()); 166 | pCommandList->SetResources(Shader::Stage::VS, DescriptorType::SRV, 0, 1, &srv); 167 | 168 | // Set viewport 169 | Viewport viewport(0.0f, 0.0f, m_viewport.x, m_viewport.y); 170 | RectRange scissorRect(0, 0, static_cast(m_viewport.x), static_cast(m_viewport.y)); 171 | pCommandList->RSSetViewports(1, &viewport); 172 | pCommandList->RSSetScissorRects(1, &scissorRect); 173 | 174 | // Set IA 175 | pCommandList->IASetPrimitiveTopology(PrimitiveTopology::POINTLIST); 176 | 177 | // Draw Command 178 | pCommandList->Draw(m_numParticles, 1, 0, 0); 179 | } 180 | 181 | bool FluidEZ::createParticleBuffers(RayTracing::EZ::CommandList* pCommandList, vector& uploaders) 182 | { 183 | const auto pDevice = pCommandList->GetDevice(); 184 | 185 | // Init data 186 | vector particles(m_numParticles); 187 | vector particleAABBs(m_numParticles); 188 | 189 | const auto smoothRadius = PARTICLE_SMOOTH_RADIUS; 190 | const auto dimSize = static_cast(ceil(std::cbrt(m_numParticles))); 191 | const auto slcSize = dimSize * dimSize; 192 | for (auto i = 0u; i < m_numParticles; ++i) 193 | { 194 | const auto n = i % slcSize; 195 | auto x = (n % dimSize) / static_cast(dimSize); 196 | auto y = (n / dimSize) / static_cast(dimSize); 197 | auto z = (i / slcSize) / static_cast(dimSize); 198 | x = INIT_PARTICLE_VOLUME_DIM * (x - 0.5f) + INIT_PARTICLE_VOLUME_CENTER[0]; 199 | y = INIT_PARTICLE_VOLUME_DIM * (y - 0.5f) + INIT_PARTICLE_VOLUME_CENTER[1]; 200 | z = INIT_PARTICLE_VOLUME_DIM * (z - 0.5f) + INIT_PARTICLE_VOLUME_CENTER[2]; 201 | 202 | particles[i].Pos = XMFLOAT3(x, y, z); 203 | particles[i].Velocity = XMFLOAT3(0.0f, 0.0f, 0.0f); 204 | 205 | // AABB 206 | particleAABBs[i].Min.x = x - smoothRadius; 207 | particleAABBs[i].Max.x = x + smoothRadius; 208 | particleAABBs[i].Min.y = y - smoothRadius; 209 | particleAABBs[i].Max.y = y + smoothRadius; 210 | #if POINT_QUERY 211 | particleAABBs[i].Min.z = z - smoothRadius; 212 | particleAABBs[i].Max.z = z + smoothRadius; 213 | #else 214 | particleAABBs[i].Min.z = z - smoothRadius * 0.5f; 215 | particleAABBs[i].Max.z = z + smoothRadius * 0.5f; 216 | #endif 217 | } 218 | 219 | // Create particle buffer 220 | m_particleBuffer = StructuredBuffer::MakeUnique(); 221 | XUSG_N_RETURN(m_particleBuffer->Create(pDevice, m_numParticles, sizeof(Particle), 222 | ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT), false); 223 | uploaders.emplace_back(Resource::MakeUnique()); 224 | 225 | // upload data to the particle buffer 226 | XUSG_N_RETURN(m_particleBuffer->Upload(pCommandList->AsCommandList(), uploaders.back().get(), particles.data(), 227 | sizeof(Particle) * m_numParticles), false); 228 | 229 | // Create particle AABB buffer 230 | m_particleAABBBuffer = VertexBuffer::MakeUnique(); 231 | XUSG_N_RETURN(m_particleAABBBuffer->Create(pDevice, m_numParticles, sizeof(ParticleAABB), 232 | ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT, 1, nullptr, 233 | 1, nullptr, 1, nullptr, MemoryFlag::NONE, L"ParticleAABBs"), false); 234 | uploaders.emplace_back(Resource::MakeUnique()); 235 | 236 | // upload data to the AABB buffer 237 | XUSG_N_RETURN(m_particleAABBBuffer->Upload(pCommandList->AsCommandList(), uploaders.back().get(), particleAABBs.data(), 238 | sizeof(ParticleAABB) * m_numParticles, 0, ResourceState::NON_PIXEL_SHADER_RESOURCE), false); 239 | 240 | return true; 241 | } 242 | 243 | bool FluidEZ::createConstBuffers(RayTracing::EZ::CommandList* pCommandList, vector& uploaders) 244 | { 245 | const auto pDevice = pCommandList->GetDevice(); 246 | 247 | // Create constant buffers 248 | m_cbSimulation = ConstantBuffer::MakeUnique(); 249 | XUSG_N_RETURN(m_cbSimulation->Create(pDevice, sizeof(CBSimulation), 1, nullptr, MemoryType::DEFAULT), false); 250 | 251 | m_cbPerFrame = ConstantBuffer::MakeUnique(); 252 | XUSG_N_RETURN(m_cbPerFrame->Create(pDevice, sizeof(CBPerFrame[FrameCount]), FrameCount), false); 253 | 254 | m_cbVisualization = ConstantBuffer::MakeUnique(); 255 | XUSG_N_RETURN(m_cbVisualization->Create(pDevice, sizeof(CBVisualization[FrameCount]), FrameCount), false); 256 | 257 | // Init constant data 258 | CBSimulation cbSimulation; 259 | { 260 | cbSimulation.SmoothRadius = PARTICLE_SMOOTH_RADIUS; 261 | cbSimulation.PressureStiffness = 200.0f; 262 | cbSimulation.RestDensity = PARTICLE_REST_DENSITY; 263 | cbSimulation.WallStiffness = 3000.0f; 264 | cbSimulation.NumParticles = m_numParticles; 265 | cbSimulation.Planes[0] = XMFLOAT4(0.0f, 1.0f, 0.0f, 0.0f); 266 | cbSimulation.Planes[1] = XMFLOAT4(0.0f, -1.0f, 0.0f, POOL_VOLUME_DIM); 267 | cbSimulation.Planes[2] = XMFLOAT4(1.0f, 0.0f, 0.0f, 0.5f * POOL_VOLUME_DIM); 268 | cbSimulation.Planes[3] = XMFLOAT4(-1.0f, 0.0f, 0.0f, 0.5f * POOL_VOLUME_DIM); 269 | cbSimulation.Planes[4] = XMFLOAT4(0.0f, 0.0f, 1.0f, 0.5f * POOL_VOLUME_DIM); 270 | cbSimulation.Planes[5] = XMFLOAT4(0.0f, 0.0f, -1.0f, 0.5f * POOL_VOLUME_DIM); 271 | 272 | const float initVolume = INIT_PARTICLE_VOLUME_DIM * INIT_PARTICLE_VOLUME_DIM * INIT_PARTICLE_VOLUME_DIM; 273 | const float mass = cbSimulation.RestDensity * initVolume / m_numParticles; 274 | const float viscosity = 0.4f; 275 | cbSimulation.DensityCoef = mass * 315.0f / (64.0f * XM_PI * pow(cbSimulation.SmoothRadius, 9.0f)); 276 | cbSimulation.PressureGradCoef = mass * -45.0f / (XM_PI * pow(cbSimulation.SmoothRadius, 6.0f)); 277 | cbSimulation.ViscosityLaplaceCoef = mass * viscosity * 45.0f / (XM_PI * pow(cbSimulation.SmoothRadius, 6.0f)); 278 | } 279 | 280 | // Upload data to cbuffer 281 | uploaders.emplace_back(Resource::MakeUnique()); 282 | 283 | return m_cbSimulation->Upload(pCommandList->AsCommandList(), 284 | uploaders.back().get(), &cbSimulation, sizeof(cbSimulation)); 285 | } 286 | 287 | bool FluidEZ::createShaders() 288 | { 289 | auto vsIndex = 0u; 290 | auto psIndex = 0u; 291 | auto csIndex = 0u; 292 | 293 | XUSG_X_RETURN(m_shaders[RT_DENSITY], m_shaderLib->CreateShader( 294 | Shader::Stage::CS, csIndex++, L"RTDensity.cso"), false); 295 | XUSG_X_RETURN(m_shaders[RT_FORCE], m_shaderLib->CreateShader( 296 | Shader::Stage::CS, csIndex++, L"RTForce.cso"), false); 297 | XUSG_X_RETURN(m_shaders[CS_INTEGRATE], m_shaderLib->CreateShader( 298 | Shader::Stage::CS, csIndex++, L"CSIntegrate.cso"), false); 299 | 300 | XUSG_X_RETURN(m_shaders[VS_DRAW_PARTICLES], m_shaderLib->CreateShader( 301 | Shader::Stage::VS, vsIndex++, L"VSDrawParticles.cso"), false); 302 | XUSG_X_RETURN(m_shaders[PS_DRAW_PARTICLES], m_shaderLib->CreateShader( 303 | Shader::Stage::PS, psIndex++, L"PSDrawParticles.cso"), false); 304 | 305 | return true; 306 | } 307 | 308 | bool FluidEZ::buildAccelerationStructures(RayTracing::EZ::CommandList* pCommandList) 309 | { 310 | // Set geometries 311 | GeometryFlag geometryFlag = GeometryFlag::NONE; // Any hit needs non-opaque (the default flag is opaque only) 312 | BottomLevelAS::SetAABBGeometries(m_geometry, 1, &m_particleAABBBuffer->GetVBV(), &geometryFlag); 313 | 314 | // Prebuild 315 | m_bottomLevelAS = BottomLevelAS::MakeUnique(); 316 | m_topLevelAS = TopLevelAS::MakeUnique(); 317 | XUSG_N_RETURN(pCommandList->PrebuildBLAS(m_bottomLevelAS.get(), 1, m_geometry, BuildFlag::NONE), false); 318 | XUSG_N_RETURN(pCommandList->PrebuildTLAS(m_topLevelAS.get(), 1), false); 319 | 320 | // Allocate AS buffers 321 | XUSG_N_RETURN(pCommandList->AllocateAccelerationStructure(m_bottomLevelAS.get()), false); 322 | XUSG_N_RETURN(pCommandList->AllocateAccelerationStructure(m_topLevelAS.get()), false); 323 | 324 | // Set instance 325 | XMFLOAT3X4 matrix; 326 | XMStoreFloat3x4(&matrix, XMMatrixIdentity()); 327 | float* const pTransform[] = { reinterpret_cast(&matrix) }; 328 | m_instances = Buffer::MakeUnique(); 329 | const BottomLevelAS* const ppBottomLevelAS[] = { m_bottomLevelAS.get() }; 330 | TopLevelAS::SetInstances(pCommandList->GetRTDevice(), m_instances.get(), 1, &ppBottomLevelAS[0], &pTransform[0]); 331 | 332 | // Build bottom level ASs 333 | pCommandList->BuildBLAS(m_bottomLevelAS.get()); 334 | 335 | // Build top level AS 336 | pCommandList->BuildTLAS(m_topLevelAS.get(), m_instances.get()); 337 | 338 | return true; 339 | } 340 | 341 | void FluidEZ::computeDensity(RayTracing::EZ::CommandList* pCommandList) 342 | { 343 | // Set pipeline state 344 | static const wchar_t* shaderNames[] = { RaygenShaderName, IntersectionShaderName, AnyHitShaderName, MissShaderName }; 345 | pCommandList->RTSetShaderLibrary(0, m_shaders[RT_DENSITY], static_cast(size(shaderNames)), shaderNames); 346 | pCommandList->RTSetHitGroup(0, HitGroupName, nullptr, AnyHitShaderName, IntersectionShaderName, HitGroupType::PROCEDURAL); 347 | pCommandList->RTSetShaderConfig(sizeof(float), sizeof(float)); 348 | pCommandList->RTSetMaxRecursionDepth(1); 349 | 350 | // Set UAV 351 | const auto uav = XUSG::EZ::GetUAV(m_densityBuffer.get()); 352 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::UAV, 0, 1, &uav); 353 | 354 | // Set SRV 355 | const auto srv = XUSG::EZ::GetSRV(m_particleBuffer.get()); 356 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::SRV, 0, 1, &srv); 357 | 358 | // Dispatch command 359 | pCommandList->DispatchRays(m_numParticles, 1, 1, RaygenShaderName, &MissShaderName, 1); 360 | } 361 | 362 | void FluidEZ::computeAcceleration(RayTracing::EZ::CommandList* pCommandList) 363 | { 364 | // Set pipeline state 365 | static const void* shaders[] = { RaygenShaderName, IntersectionShaderName, AnyHitShaderName, MissShaderName }; 366 | pCommandList->RTSetShaderLibrary(0, m_shaders[RT_FORCE]);//, static_cast(size(shaders)), shaders); 367 | pCommandList->RTSetHitGroup(0, HitGroupName, nullptr, AnyHitShaderName, IntersectionShaderName, HitGroupType::PROCEDURAL); 368 | pCommandList->RTSetShaderConfig(sizeof(XMFLOAT4[2]), sizeof(XMFLOAT4)); 369 | pCommandList->RTSetMaxRecursionDepth(1); 370 | 371 | // Set UAV 372 | const auto uav = XUSG::EZ::GetUAV(m_accelerationBuffer.get()); 373 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::UAV, 0, 1, &uav); 374 | 375 | // Set SRVs 376 | const XUSG::EZ::ResourceView srvs[] = 377 | { 378 | XUSG::EZ::GetSRV(m_particleBuffer.get()), 379 | XUSG::EZ::GetSRV(m_densityBuffer.get()) 380 | }; 381 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::SRV, 0, static_cast(size(srvs)), srvs); 382 | 383 | // Dispatch command 384 | pCommandList->DispatchRays(m_numParticles, 1, 1, RaygenShaderName, &MissShaderName, 1); 385 | } 386 | 387 | void FluidEZ::integrate(RayTracing::EZ::CommandList* pCommandList) 388 | { 389 | // Set pipeline state 390 | pCommandList->SetComputeShader(m_shaders[CS_INTEGRATE]); 391 | 392 | // Set UAVs 393 | const XUSG::EZ::ResourceView uavs[] = 394 | { 395 | XUSG::EZ::GetUAV(m_particleBuffer.get()), 396 | XUSG::EZ::GetUAV(m_particleAABBBuffer.get()) 397 | }; 398 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::UAV, 0, static_cast(size(uavs)), uavs); 399 | 400 | // Set SRV 401 | const auto srv = XUSG::EZ::GetSRV(m_accelerationBuffer.get()); 402 | pCommandList->SetResources(Shader::Stage::CS, DescriptorType::SRV, 0, 1, &srv); 403 | 404 | // Dispatch command 405 | pCommandList->Dispatch(XUSG_DIV_UP(m_numParticles, GROUP_SIZE), 1, 1); 406 | } 407 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/FluidEZ.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "Core/XUSG.h" 8 | #include "Helper/XUSGRayTracing-EZ.h" 9 | #include "RayTracing/XUSGRayTracing.h" 10 | 11 | class FluidEZ 12 | { 13 | public: 14 | FluidEZ(); 15 | virtual ~FluidEZ(); 16 | 17 | bool Init(XUSG::RayTracing::EZ::CommandList* pCommandList, uint32_t width, uint32_t height, 18 | std::vector& uploaders, uint32_t numParticles = 65536); 19 | 20 | void UpdateFrame(uint8_t frameIndex, float timeStep, DirectX::CXMMATRIX viewProj, DirectX::CXMVECTOR viewY); 21 | void Render(XUSG::RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex, 22 | XUSG::RenderTarget* pRenderTarget, XUSG::DepthStencil* pDepthStencil); 23 | void Simulate(XUSG::RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex); 24 | void Visualize(XUSG::RayTracing::EZ::CommandList* pCommandList, uint8_t frameIndex, 25 | XUSG::RenderTarget* pRenderTarget, XUSG::DepthStencil* pDepthStencil); 26 | 27 | static const uint8_t FrameCount = 3; 28 | 29 | protected: 30 | bool createParticleBuffers(XUSG::RayTracing::EZ::CommandList* pCommandList, std::vector& uploaders); 31 | bool createConstBuffers(XUSG::RayTracing::EZ::CommandList* pCommandList, std::vector& uploaders); 32 | bool createShaders(); 33 | bool buildAccelerationStructures(XUSG::RayTracing::EZ::CommandList* pCommandList); 34 | 35 | void computeDensity(XUSG::RayTracing::EZ::CommandList* pCommandList); 36 | void computeAcceleration(XUSG::RayTracing::EZ::CommandList* pCommandList); 37 | void integrate(XUSG::RayTracing::EZ::CommandList* pCommandList); 38 | 39 | XUSG::RayTracing::BottomLevelAS::uptr m_bottomLevelAS; 40 | XUSG::RayTracing::TopLevelAS::uptr m_topLevelAS; 41 | 42 | XUSG::StructuredBuffer::uptr m_particleBuffer; 43 | XUSG::VertexBuffer::uptr m_particleAABBBuffer; 44 | XUSG::TypedBuffer::uptr m_densityBuffer; 45 | XUSG::TypedBuffer::uptr m_accelerationBuffer; 46 | XUSG::ConstantBuffer::uptr m_cbSimulation; 47 | XUSG::ConstantBuffer::uptr m_cbPerFrame; 48 | XUSG::ConstantBuffer::uptr m_cbVisualization; 49 | 50 | XUSG::RayTracing::GeometryBuffer m_geometry; 51 | XUSG::Buffer::uptr m_instances; 52 | 53 | // Shader tables 54 | static const wchar_t* HitGroupName; 55 | static const wchar_t* RaygenShaderName; 56 | static const wchar_t* IntersectionShaderName; 57 | static const wchar_t* AnyHitShaderName; 58 | static const wchar_t* MissShaderName; 59 | 60 | enum ShaderIndex : uint8_t 61 | { 62 | RT_DENSITY, 63 | RT_FORCE, 64 | CS_INTEGRATE, 65 | VS_DRAW_PARTICLES, 66 | PS_DRAW_PARTICLES, 67 | 68 | NUM_SHADER 69 | }; 70 | 71 | XUSG::ShaderLib::uptr m_shaderLib; 72 | XUSG::Blob m_shaders[NUM_SHADER]; 73 | 74 | DirectX::XMFLOAT2 m_viewport; 75 | 76 | uint32_t m_numParticles; 77 | }; 78 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/CSIntegrate.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "Common.hlsli" 6 | #include "SharedConst.h" 7 | 8 | //-------------------------------------------------------------------------------------- 9 | // Constant buffer 10 | //-------------------------------------------------------------------------------------- 11 | cbuffer cbPerFrame : register (b1) 12 | { 13 | float g_timeStep; 14 | float3 g_gravity; 15 | }; 16 | 17 | //-------------------------------------------------------------------------------------- 18 | // Buffers 19 | //-------------------------------------------------------------------------------------- 20 | RWStructuredBuffer g_rwParticles : register (u0); 21 | RWStructuredBuffer g_rwParticleAABBs : register (u1); 22 | Buffer g_roAccelerations : register (t0); 23 | 24 | [numthreads(GROUP_SIZE, 1, 1)] 25 | void main(uint DTid : SV_DispatchThreadID) 26 | { 27 | Particle particle = g_rwParticles[DTid]; 28 | float3 acceleration = g_roAccelerations[DTid]; 29 | 30 | // Apply the forces from the map walls 31 | [unroll] 32 | for (uint i = 0; i < 6; ++i) 33 | { 34 | float dist = dot(float4(particle.Pos, 1.0), g_planes[i]); 35 | acceleration += min(dist, 0) * -g_wallStiffness * g_planes[i].xyz; 36 | } 37 | 38 | // Apply gravity 39 | acceleration += g_gravity; 40 | 41 | // Integrate 42 | particle.Velocity += g_timeStep * acceleration; 43 | particle.Pos += g_timeStep * particle.Velocity; 44 | 45 | ParticleAABB aabb; 46 | aabb.Min = particle.Pos - g_smoothRadius; 47 | aabb.Max = particle.Pos + g_smoothRadius; 48 | 49 | // Update 50 | g_rwParticles[DTid] = particle; 51 | g_rwParticleAABBs[DTid] = aabb; 52 | } 53 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/Common.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | //-------------------------------------------------------------------------------------- 6 | // Structs 7 | //-------------------------------------------------------------------------------------- 8 | struct Particle 9 | { 10 | float3 Pos; 11 | float3 Velocity; 12 | }; 13 | 14 | struct ParticleAABB 15 | { 16 | float3 Min; 17 | float3 Max; 18 | }; 19 | 20 | //-------------------------------------------------------------------------------------- 21 | // Constant buffer 22 | //-------------------------------------------------------------------------------------- 23 | cbuffer cbSimulation : register (b0) 24 | { 25 | float g_smoothRadius; 26 | float g_pressureStiffness; 27 | float g_restDensity; 28 | float g_densityCoef; 29 | float g_pressureGradCoef; 30 | float g_viscosityLaplaceCoef; 31 | float g_wallStiffness; 32 | uint g_numParticles; 33 | 34 | float4 g_planes[6]; 35 | }; 36 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/PSDrawParticles.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | min16float4 main() : SV_TARGET 6 | { 7 | return min16float4(0.0, 0.5, 1.0, 1.0); 8 | } 9 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/RTCommon.hlsli: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "Common.hlsli" 6 | #include "SharedConst.h" 7 | 8 | typedef RaytracingAccelerationStructure RaytracingAS; 9 | 10 | //-------------------------------------------------------------------------------------- 11 | // Buffers 12 | //-------------------------------------------------------------------------------------- 13 | StructuredBuffer g_roParticles : register (t0); 14 | RaytracingAS g_bvhParticles : register (t0, space1); 15 | 16 | //-------------------------------------------------------------------------------------- 17 | // Generate ray 18 | //-------------------------------------------------------------------------------------- 19 | RayDesc GenerateRay(Particle particle) 20 | { 21 | RayDesc ray; 22 | ray.Origin = particle.Pos; 23 | ray.Direction = float3(0.0.xx, 1.0); 24 | ray.TMin = 0.0; 25 | #if POINT_QUERY 26 | // 0-length ray for point query 27 | ray.TMax = 0.0; 28 | #else 29 | // z-oriented ray segment with g_smoothRadius length 30 | ray.Origin.z -= g_smoothRadius * 0.5; 31 | ray.TMax = g_smoothRadius; 32 | #endif 33 | 34 | return ray; 35 | } 36 | 37 | //-------------------------------------------------------------------------------------- 38 | // Get THit 39 | //-------------------------------------------------------------------------------------- 40 | float GetTHit() 41 | { 42 | #if POINT_QUERY 43 | // 0-length ray for point query 44 | return 0.0; 45 | #else 46 | // z-oriented ray segment with g_smoothRadius length 47 | return g_smoothRadius * 0.5; 48 | #endif 49 | } 50 | 51 | //-------------------------------------------------------------------------------------- 52 | // Calculate displacement between 2 particles 53 | //-------------------------------------------------------------------------------------- 54 | float3 CalculateParticleDisplacement(float thit) 55 | { 56 | const Particle hitParticle = g_roParticles[PrimitiveIndex()]; 57 | 58 | float3 rayPos = WorldRayOrigin(); 59 | rayPos.z += thit; 60 | 61 | return hitParticle.Pos - rayPos; 62 | } 63 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/RTDensity.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "RTCommon.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Structs 9 | //-------------------------------------------------------------------------------------- 10 | struct RayPayload 11 | { 12 | float Density; 13 | }; 14 | 15 | struct HitAttributes 16 | { 17 | float R_sq; 18 | }; 19 | 20 | //-------------------------------------------------------------------------------------- 21 | // Buffer 22 | //-------------------------------------------------------------------------------------- 23 | RWBuffer g_rwDensities : register (u0); 24 | 25 | //-------------------------------------------------------------------------------------- 26 | // Ray generation 27 | //-------------------------------------------------------------------------------------- 28 | [shader("raygeneration")] 29 | void raygenMain() 30 | { 31 | const uint index = DispatchRaysIndex().x; 32 | const Particle particle = g_roParticles[index]; 33 | const RayDesc ray = GenerateRay(particle); 34 | 35 | // Trace the ray. 36 | RayPayload payload; 37 | payload.Density = 0.0; 38 | TraceRay(g_bvhParticles, RAY_FLAG_SKIP_CLOSEST_HIT_SHADER, ~0, 0, 1, 0, ray, payload); 39 | 40 | g_rwDensities[index] = payload.Density; 41 | } 42 | 43 | //-------------------------------------------------------------------------------------- 44 | // Ray intersection 45 | //-------------------------------------------------------------------------------------- 46 | [shader("intersection")] 47 | void intersectionMain() 48 | { 49 | const float thit = GetTHit(); 50 | const float3 disp = CalculateParticleDisplacement(thit); 51 | const float r_sq = dot(disp, disp); 52 | 53 | if (r_sq < g_smoothRadius * g_smoothRadius) 54 | { 55 | const HitAttributes attr = { r_sq }; 56 | ReportHit(thit, /*hitKind*/ 0, attr); 57 | } 58 | } 59 | 60 | //-------------------------------------------------------------------------------------- 61 | // Density calculation 62 | //-------------------------------------------------------------------------------------- 63 | float CalculateDensity(float r_sq) 64 | { 65 | // Implements this equation: 66 | // W_poly6(r, h) = 315 / (64 * pi * h^9) * (h^2 - r^2)^3 67 | // g_densityCoef = particleMass * 315.0f / (64.0f * PI * g_smoothRadius^9) 68 | const float d_sq = g_smoothRadius * g_smoothRadius - r_sq; 69 | 70 | return g_densityCoef * d_sq * d_sq * d_sq; 71 | } 72 | 73 | //-------------------------------------------------------------------------------------- 74 | // Ray any hit 75 | //-------------------------------------------------------------------------------------- 76 | [shader("anyhit")] 77 | void anyHitMain(inout RayPayload payload, HitAttributes attr) 78 | { 79 | payload.Density += CalculateDensity(attr.R_sq); 80 | 81 | IgnoreHit(); 82 | } 83 | 84 | //-------------------------------------------------------------------------------------- 85 | // Ray miss 86 | //-------------------------------------------------------------------------------------- 87 | [shader("miss")] 88 | void missMain(inout RayPayload payload) 89 | { 90 | } 91 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/RTForce.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "RTCommon.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Structs 9 | //-------------------------------------------------------------------------------------- 10 | struct RayPayload 11 | { 12 | float Pressure; 13 | float3 Force; 14 | float3 Velocity; 15 | }; 16 | 17 | struct HitAttributes 18 | { 19 | float3 Disp; 20 | float R_sq; 21 | }; 22 | 23 | //-------------------------------------------------------------------------------------- 24 | // Buffer 25 | //-------------------------------------------------------------------------------------- 26 | RWBuffer g_rwAccelerations : register (u0); 27 | Buffer g_roDensities : register (t1); 28 | 29 | //-------------------------------------------------------------------------------------- 30 | // Pressure calculation 31 | //-------------------------------------------------------------------------------------- 32 | float CalculatePressure(float density) 33 | { 34 | // Implements this equation: 35 | // Pressure = B * ((rho / rho_0)^y - 1) 36 | const float rhoRatio = density / g_restDensity; 37 | 38 | return g_pressureStiffness * max(rhoRatio * rhoRatio * rhoRatio - 1.0, 0.0); 39 | } 40 | 41 | //-------------------------------------------------------------------------------------- 42 | // Ray generation 43 | //-------------------------------------------------------------------------------------- 44 | [shader("raygeneration")] 45 | void raygenMain() 46 | { 47 | const uint index = DispatchRaysIndex().x; 48 | const Particle particle = g_roParticles[index]; 49 | const float density = g_roDensities[index]; 50 | const RayDesc ray = GenerateRay(particle); 51 | 52 | // Trace the ray. 53 | RayPayload payload; 54 | payload.Pressure = CalculatePressure(density); 55 | payload.Velocity = particle.Velocity; 56 | payload.Force = 0.0; 57 | TraceRay(g_bvhParticles, RAY_FLAG_SKIP_CLOSEST_HIT_SHADER, ~0, 0, 1, 0, ray, payload); 58 | 59 | g_rwAccelerations[index] = density > 0.0 ? payload.Force / density : 0.0; 60 | } 61 | 62 | //-------------------------------------------------------------------------------------- 63 | // Ray intersection 64 | //-------------------------------------------------------------------------------------- 65 | [shader("intersection")] 66 | void intersectionMain() 67 | { 68 | const float thit = GetTHit(); 69 | const float3 disp = CalculateParticleDisplacement(thit); 70 | const float r_sq = dot(disp, disp); 71 | const uint hitIndex = PrimitiveIndex(); 72 | const uint index = DispatchRaysIndex().x; 73 | 74 | if (r_sq < g_smoothRadius * g_smoothRadius 75 | && index != hitIndex) 76 | { 77 | const HitAttributes attr = { disp, r_sq }; 78 | ReportHit(thit, /*hitKind*/ 0, attr); 79 | } 80 | } 81 | 82 | //-------------------------------------------------------------------------------------- 83 | // Pressure gradient calculation 84 | //-------------------------------------------------------------------------------------- 85 | float3 CalculateGradPressure(float r, float d, float pressure, float adjPressure, float adjDensity, float3 disp) 86 | { 87 | const float avgPressure = 0.5 * (adjPressure + pressure); 88 | // Implements this equation: 89 | // W_spkiey(r, h) = 15 / (pi * h^6) * (h - r)^3 90 | // GRAD(W_spikey(r, h)) = -45 / (pi * h^6) * (h - r)^2 91 | // g_pressureGradCoef = particleMass * -45.0f / (PI * g_smoothRadius^6) 92 | 93 | return g_pressureGradCoef * avgPressure * d * d * disp / (adjDensity * r); 94 | } 95 | 96 | //-------------------------------------------------------------------------------------- 97 | // Velocity Laplacian calculation 98 | //-------------------------------------------------------------------------------------- 99 | float3 CalculateVelocityLaplace(float d, float3 velocity, float3 adjVelocity, float adjDensity) 100 | { 101 | float3 velDisp = (adjVelocity - velocity); 102 | // Implements this equation: 103 | // W_viscosity(r, h) = 15 / (2 * pi * h^3) * (-r^3 / (2 * h^3) + r^2 / h^2 + h / (2 * r) - 1) 104 | // LAPLACIAN(W_viscosity(r, h)) = 45 / (pi * h^6) * (h - r) 105 | // g_viscosityLaplaceCoef = particleMass * viscosity * 45.0f / (PI * g_smoothRadius^6) 106 | 107 | return g_viscosityLaplaceCoef * d * velDisp / adjDensity; 108 | } 109 | 110 | //-------------------------------------------------------------------------------------- 111 | // Ray any hit 112 | //-------------------------------------------------------------------------------------- 113 | [shader("anyhit")] 114 | void anyHitMain(inout RayPayload payload, HitAttributes attr) 115 | { 116 | const uint hitIndex = PrimitiveIndex(); 117 | const Particle hitParticle = g_roParticles[hitIndex]; 118 | 119 | const float r = sqrt(attr.R_sq); 120 | const float d = g_smoothRadius - r; 121 | const float hitDensity = g_roDensities[hitIndex]; 122 | const float hitPressure = CalculatePressure(hitDensity); 123 | 124 | // Pressure term 125 | payload.Force += CalculateGradPressure(r, d, payload.Pressure, hitPressure, hitDensity, attr.Disp); 126 | 127 | // Viscosity term 128 | payload.Force += CalculateVelocityLaplace(d, payload.Velocity, hitParticle.Velocity, hitDensity); 129 | 130 | IgnoreHit(); 131 | } 132 | 133 | //-------------------------------------------------------------------------------------- 134 | // Ray miss 135 | //-------------------------------------------------------------------------------------- 136 | [shader("miss")] 137 | void missMain(inout RayPayload payload) 138 | { 139 | } 140 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/Shaders/VSDrawParticles.hlsl: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #include "Common.hlsli" 6 | 7 | //-------------------------------------------------------------------------------------- 8 | // Buffers 9 | //-------------------------------------------------------------------------------------- 10 | StructuredBuffer g_roParticles : register (t0); 11 | 12 | cbuffer cbVisualization : register (b0) 13 | { 14 | matrix g_viewProj; 15 | } 16 | 17 | float4 main(uint vid : SV_VERTEXID) : SV_POSITION 18 | { 19 | const Particle particle = g_roParticles[vid]; 20 | 21 | return mul(float4(particle.Pos, 1.0), g_viewProj); 22 | } 23 | -------------------------------------------------------------------------------- /RayTracedSPH/Content/SharedConst.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #define POINT_QUERY 1 6 | #define GROUP_SIZE 64 7 | -------------------------------------------------------------------------------- /RayTracedSPH/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 "RayTracedSPH.h" 13 | 14 | _Use_decl_annotations_ 15 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) 16 | { 17 | RayTracedSPH rayTracedSPH(1280, 720, L"DirectX 12 particle-based fluid by ray-tracing EZ"); 18 | 19 | return Win32Application::Run(&rayTracedSPH, hInstance, nCmdShow); 20 | } 21 | -------------------------------------------------------------------------------- /RayTracedSPH/RayTracedSPH.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 "FluidEZ.h" 17 | 18 | using namespace DirectX; 19 | 20 | // Note that while ComPtr is used to manage the lifetime of resources on the CPU, 21 | // it has no understanding of the lifetime of resources on the GPU. Apps must account 22 | // for the GPU lifetime of resources to avoid destroying objects that may still be 23 | // referenced by the GPU. 24 | // An example of this can be found in the class method: OnDestroy(). 25 | 26 | class RayTracedSPH : public DXFramework 27 | { 28 | public: 29 | RayTracedSPH(uint32_t width, uint32_t height, std::wstring name); 30 | virtual ~RayTracedSPH(); 31 | 32 | virtual void OnInit(); 33 | virtual void OnUpdate(); 34 | virtual void OnRender(); 35 | virtual void OnDestroy(); 36 | 37 | virtual void OnKeyUp(uint8_t /*key*/); 38 | virtual void OnLButtonDown(float posX, float posY); 39 | virtual void OnLButtonUp(float posX, float posY); 40 | virtual void OnMouseMove(float posX, float posY); 41 | virtual void OnMouseWheel(float deltaZ, float posX, float posY); 42 | virtual void OnMouseLeave(); 43 | 44 | virtual void ParseCommandLineArgs(wchar_t* argv[], int argc); 45 | 46 | private: 47 | enum DeviceType : uint8_t 48 | { 49 | DEVICE_DISCRETE, 50 | DEVICE_UMA, 51 | DEVICE_WARP 52 | }; 53 | 54 | static const uint8_t FrameCount = FluidEZ::FrameCount; 55 | 56 | // Pipeline objects. 57 | XUSG::Viewport m_viewport; 58 | XUSG::RectRange m_scissorRect; 59 | 60 | XUSG::SwapChain::uptr m_swapChain; 61 | XUSG::CommandAllocator::uptr m_commandAllocators[FrameCount]; 62 | XUSG::CommandQueue::uptr m_commandQueue; 63 | 64 | bool m_isDxrSupported; 65 | 66 | XUSG::RayTracing::Device::uptr m_device; 67 | XUSG::RenderTarget::uptr m_renderTargets[FrameCount]; 68 | XUSG::RayTracing::EZ::CommandList::uptr m_commandListEZ; 69 | 70 | // App resources. 71 | std::unique_ptr m_fluid; 72 | XUSG::DepthStencil::uptr m_depth; 73 | XMFLOAT4X4 m_proj; 74 | XMFLOAT4X4 m_view; 75 | XMFLOAT3 m_focusPt; 76 | XMFLOAT3 m_eyePt; 77 | 78 | // Synchronization objects. 79 | uint32_t m_frameIndex; 80 | HANDLE m_fenceEvent; 81 | XUSG::Fence::uptr m_fence; 82 | uint64_t m_fenceValues[FrameCount]; 83 | 84 | // Application state 85 | DeviceType m_deviceType; 86 | StepTimer m_timer; 87 | bool m_showFPS; 88 | bool m_isPaused; 89 | 90 | // User camera interactions 91 | bool m_tracking; 92 | XMFLOAT2 m_mousePt; 93 | 94 | // Screen-shot helpers and state 95 | XUSG::Buffer::uptr m_readBuffer; 96 | uint32_t m_rowPitch; 97 | uint8_t m_screenShot; 98 | 99 | void LoadPipeline(); 100 | void LoadAssets(); 101 | void PopulateCommandList(); 102 | void WaitForGpu(); 103 | void MoveToNextFrame(); 104 | void SaveImage(char const* fileName, XUSG::Buffer* pImageBuffer, 105 | uint32_t w, uint32_t h, uint32_t rowPitch, uint8_t comp = 3); 106 | double CalculateFrameStats(float* fTimeStep = nullptr); 107 | 108 | // Ray tracing 109 | void EnableDirectXRaytracing(IDXGIAdapter1* adapter); 110 | }; 111 | -------------------------------------------------------------------------------- /RayTracedSPH/RayTracedSPH.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | x64 7 | 8 | 9 | Release 10 | x64 11 | 12 | 13 | 14 | 15.0 15 | {20AD8700-447F-4B0B-9A95-0E1C646F3878} 16 | DXRVoxelizer 17 | 18 | 19 | 20 | Application 21 | true 22 | Unicode 23 | v143 24 | 25 | 26 | Application 27 | false 28 | true 29 | Unicode 30 | v143 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | Level3 48 | Disabled 49 | true 50 | Use 51 | $(ProjectDir);$(ProjectDir)Content;$(ProjectDir)Common;$(ProjectDir)XUSG 52 | AdvancedVectorExtensions2 53 | Fast 54 | true 55 | 56 | 57 | COPY /Y "$(OutDir)*.cso" "$(ProjectDir)..\Bin\" 58 | 59 | COPY /Y "$(OutDir)*.exe" "$(ProjectDir)..\Bin\" 60 | 61 | COPY /Y "$(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration)\*.dll" "$(ProjectDir)..\Bin\" 62 | 63 | 64 | 65 | d3d12.lib;dxgi.lib;d3dcompiler.lib;dxguid.lib;XUSG.lib;XUSGRayTracing.lib;XUSG-EZ.lib;XUSGRayTracing-EZ.lib;%(AdditionalDependencies) 66 | $(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration) 67 | 68 | 69 | $(ProjectDir)Content\Shaders;$(ProjectDir)Content;$(ProjectDir)XUSG\Shaders;$(ProjectDir)XUSG;$(ProjectDir) 70 | 71 | 72 | 73 | 74 | Level3 75 | MaxSpeed 76 | true 77 | true 78 | true 79 | Use 80 | $(ProjectDir);$(ProjectDir)Content;$(ProjectDir)Common;$(ProjectDir)XUSG 81 | AdvancedVectorExtensions2 82 | Fast 83 | true 84 | 85 | 86 | true 87 | true 88 | d3d12.lib;dxgi.lib;d3dcompiler.lib;dxguid.lib;XUSG.lib;XUSGRayTracing.lib;XUSG-EZ.lib;XUSGRayTracing-EZ.lib;%(AdditionalDependencies) 89 | $(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration) 90 | 91 | 92 | COPY /Y "$(OutDir)*.cso" "$(ProjectDir)..\Bin\" 93 | 94 | COPY /Y "$(OutDir)*.exe" "$(ProjectDir)..\Bin\" 95 | 96 | COPY /Y "$(ProjectDir)XUSG\Bin\$(Platform)\$(Configuration)\*.dll" "$(ProjectDir)..\Bin\" 97 | 98 | 99 | 100 | $(ProjectDir)Content\Shaders;$(ProjectDir)Content;$(ProjectDir)XUSG\Shaders;$(ProjectDir)XUSG;$(ProjectDir) 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | stdafx.h 127 | stdafx.h 128 | 129 | 130 | stdafx.h 131 | stdafx.h 132 | 133 | 134 | stdafx.h 135 | stdafx.h 136 | 137 | 138 | stdafx.h 139 | stdafx.h 140 | 141 | 142 | stdafx.h 143 | stdafx.h 144 | 145 | 146 | stdafx.h 147 | stdafx.h 148 | 149 | 150 | Create 151 | Create 152 | 153 | 154 | 155 | 156 | Compute 157 | 5.0 158 | Compute 159 | 5.0 160 | 161 | 162 | Pixel 163 | Pixel 164 | 5.0 165 | 5.0 166 | 167 | 168 | Library 169 | 6.3 170 | Library 171 | 6.3 172 | 173 | 174 | 175 | 176 | Document 177 | "$(ProjectDir)..\Bin\dxc.exe" /Zi /Od /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" /I "$(ProjectDir)Content" 178 | $(OutDir)%(Filename).cso 179 | "$(ProjectDir)..\Bin\dxc.exe" /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" /I "$(ProjectDir)Content" 180 | $(OutDir)%(Filename).cso 181 | true 182 | true 183 | 184 | 185 | 6.3 186 | true 187 | 6.3 188 | true 189 | Library 190 | Library 191 | 192 | 193 | 194 | 195 | Document 196 | "$(ProjectDir)..\Bin\dxc.exe" /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" /I "$(ProjectDir)Content" 197 | $(OutDir)%(Filename).cso 198 | $(OutDir)%(Filename).cso 199 | "$(ProjectDir)..\Bin\dxc.exe" /Zi /Od /Fo"$(OutDir)%(Filename).cso" /T"lib_6_3" /nologo "%(FullPath)" /I "$(ProjectDir)Content" 200 | 201 | 202 | Vertex 203 | Vertex 204 | 5.0 205 | 5.0 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | -------------------------------------------------------------------------------- /RayTracedSPH/RayTracedSPH.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 | {5791b192-b485-437c-b002-bc57216fb455} 18 | 19 | 20 | {0b7df9f8-419c-4d6d-b182-9b8e31a22cae} 21 | 22 | 23 | {34416045-60ca-45d6-b1b5-5b35886ab7dd} 24 | 25 | 26 | {6a52f70c-ef14-46fa-b0ad-a6038a19fdae} 27 | 28 | 29 | {70b20d20-b909-4147-9345-d3a9a3756ff1} 30 | 31 | 32 | 33 | 34 | Header Files 35 | 36 | 37 | Common\Header Files 38 | 39 | 40 | Common\Header Files 41 | 42 | 43 | Common\Header Files 44 | 45 | 46 | Common\Header Files 47 | 48 | 49 | Header Files 50 | 51 | 52 | Header Files 53 | 54 | 55 | Common\Header Files 56 | 57 | 58 | Common\Header Files 59 | 60 | 61 | Header Files 62 | 63 | 64 | XUSG 65 | 66 | 67 | XUSG 68 | 69 | 70 | XUSG 71 | 72 | 73 | XUSG 74 | 75 | 76 | XUSG 77 | 78 | 79 | XUSG 80 | 81 | 82 | Common\Header Files 83 | 84 | 85 | Common\Header Files 86 | 87 | 88 | Common\Header Files 89 | 90 | 91 | 92 | 93 | Source Files 94 | 95 | 96 | Source Files 97 | 98 | 99 | Common\Source Files 100 | 101 | 102 | Common\Source Files 103 | 104 | 105 | Source Files 106 | 107 | 108 | Source Files 109 | 110 | 111 | Common\Source Files 112 | 113 | 114 | 115 | 116 | Shaders 117 | 118 | 119 | Shaders 120 | 121 | 122 | 123 | 124 | Shaders 125 | 126 | 127 | Shaders 128 | 129 | 130 | Shaders 131 | 132 | 133 | Shaders 134 | 135 | 136 | Shaders 137 | 138 | 139 | -------------------------------------------------------------------------------- /RayTracedSPH/RayTracedSPH.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(ProjectDir)..\Bin\ 5 | WindowsLocalDebugger 6 | 7 | 8 | $(ProjectDir)..\Bin\ 9 | WindowsLocalDebugger 10 | 11 | -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG-EZ.pdb -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSG.pdb -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing-EZ.pdb -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Debug/XUSGRayTracing.pdb -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSG-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSG-EZ.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSG-EZ.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSG-EZ.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSG.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSG.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSG.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSG.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing-EZ.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing-EZ.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing-EZ.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing-EZ.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing.dll -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StarsX/RayTracedSPH/7d033f9e060b62555c79a0cf1932eba25b71cf55/RayTracedSPH/XUSG/Bin/x64/Release/XUSGRayTracing.lib -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Helper/XUSG-EZ.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "Core/XUSG.h" 8 | 9 | namespace XUSG 10 | { 11 | namespace EZ 12 | { 13 | // Resource views 14 | struct ResourceView 15 | { 16 | Resource* pResource; 17 | Descriptor View; 18 | std::vector Subresources; 19 | ResourceState DstState; 20 | Resource* pCounter; 21 | }; 22 | 23 | struct VertexBufferView 24 | { 25 | VertexBuffer* pResource; 26 | const XUSG::VertexBufferView* pView; 27 | ResourceState DstState; 28 | }; 29 | 30 | struct IndexBufferView 31 | { 32 | IndexBuffer* pResource; 33 | const XUSG::IndexBufferView* pView; 34 | ResourceState DstState; 35 | }; 36 | 37 | XUSG_INTERFACE void CalcSubresources(std::vector& subresources, const Texture* pResource, uint8_t mipSlice, uint8_t planeSlice = 0); 38 | 39 | // Resource view generation helpers coupled for XUSG resources 40 | XUSG_INTERFACE ResourceView GetCBV(ConstantBuffer* pResource, uint32_t index = 0); 41 | XUSG_INTERFACE ResourceView GetSRV(Buffer* pResource, uint32_t index = 0, 42 | ResourceState dstState = ResourceState::ALL_SHADER_RESOURCE); 43 | XUSG_INTERFACE ResourceView GetSRV(VertexBuffer* pResource, uint32_t index = 0, 44 | ResourceState dstState = ResourceState::ALL_SHADER_RESOURCE | ResourceState::VERTEX_AND_CONSTANT_BUFFER); 45 | XUSG_INTERFACE ResourceView GetSRV(IndexBuffer* pResource, uint32_t index = 0, 46 | ResourceState dstState = ResourceState::ALL_SHADER_RESOURCE | ResourceState::INDEX_BUFFER); 47 | XUSG_INTERFACE ResourceView GetSRV(Texture* pResource, uint8_t firstLevel = 0, 48 | bool singleLevel = false, ResourceState dstState = ResourceState::ALL_SHADER_RESOURCE); 49 | XUSG_INTERFACE ResourceView GetSRV(Texture3D* pResource, uint8_t firstLevel = 0, 50 | bool singleLevel = false, ResourceState dstState = ResourceState::ALL_SHADER_RESOURCE); 51 | XUSG_INTERFACE ResourceView GetUAV(Buffer* pResource, uint32_t index = 0); 52 | XUSG_INTERFACE ResourceView GetUAV(Texture* pResource, uint8_t level = 0, Format format = Format::UNKNOWN); 53 | XUSG_INTERFACE ResourceView GetUAV(Texture3D* pResource, uint8_t level = 0, Format format = Format::UNKNOWN); 54 | XUSG_INTERFACE ResourceView GetUAV(TypedBuffer* pResource, uint32_t index = 0, Format format = Format::UNKNOWN); 55 | XUSG_INTERFACE ResourceView GetRTV(RenderTarget* pResource, uint16_t slice = 0, uint8_t mipLevel = 0); // slice = UINT16_MAX for array RTV 56 | XUSG_INTERFACE ResourceView GetDSV(DepthStencil* pResource, uint16_t slice = 0, uint8_t mipLevel = 0); // slice = UINT16_MAX for array DSV 57 | XUSG_INTERFACE ResourceView GetReadOnlyDSV(DepthStencil* pResource, uint16_t slice = 0, 58 | uint8_t mipLevel = 0, ResourceState dstSrvState = ResourceState::ALL_SHADER_RESOURCE); 59 | XUSG_INTERFACE ResourceView GetStencilSRV(DepthStencil* pResource, 60 | ResourceState dstSrvState = ResourceState::ALL_SHADER_RESOURCE); 61 | 62 | XUSG_INTERFACE VertexBufferView GetVBV(VertexBuffer* pResource, uint32_t index = 0, 63 | ResourceState dstSrvState = ResourceState::ALL_SHADER_RESOURCE); 64 | 65 | XUSG_INTERFACE IndexBufferView GetIBV(IndexBuffer* pResource, uint32_t index = 0, 66 | ResourceState dstSrvState = ResourceState::ALL_SHADER_RESOURCE); 67 | 68 | //-------------------------------------------------------------------------------------- 69 | // Command list 70 | //-------------------------------------------------------------------------------------- 71 | class XUSG_INTERFACE CommandList 72 | { 73 | public: 74 | //CommandList(); 75 | virtual ~CommandList() {} 76 | 77 | // By default maxSamplers[stage] = 16, maxCbvsEachSpace[stage] = 14, maxSrvsEachSpace[stage] = 32, and maxUavsEachSpace[stage] = 16 78 | virtual bool Create(XUSG::CommandList* pCommandList, 79 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 80 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 81 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 82 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 83 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 84 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 85 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 86 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 87 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 88 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 89 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 90 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE) = 0; 91 | virtual bool Create(const Device* pDevice, void* pHandle, 92 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 93 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 94 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 95 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 96 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 97 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 98 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 99 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 100 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 101 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 102 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 103 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 104 | const wchar_t* name = nullptr) = 0; 105 | virtual bool Close(RenderTarget* pBackBuffer = nullptr) = 0; 106 | virtual bool Reset(const CommandAllocator* pAllocator, const Pipeline& initialState) = 0; 107 | 108 | virtual void ClearState(const Pipeline& initialState) const = 0; 109 | virtual void Draw( 110 | uint32_t vertexCountPerInstance, 111 | uint32_t instanceCount, 112 | uint32_t startVertexLocation, 113 | uint32_t startInstanceLocation) = 0; 114 | virtual void DrawIndexed( 115 | uint32_t indexCountPerInstance, 116 | uint32_t instanceCount, 117 | uint32_t startIndexLocation, 118 | int32_t baseVertexLocation, 119 | uint32_t startInstanceLocation) = 0; 120 | virtual void DrawIndirect(const CommandLayout* pCommandlayout, 121 | uint32_t maxCommandCount, 122 | Resource* pArgumentBuffer, 123 | uint64_t argumentBufferOffset = 0, 124 | Resource* pCountBuffer = nullptr, 125 | uint64_t countBufferOffset = 0) = 0; 126 | virtual void Dispatch( 127 | uint32_t threadGroupCountX, 128 | uint32_t threadGroupCountY, 129 | uint32_t threadGroupCountZ) = 0; 130 | virtual void DispatchIndirect(const CommandLayout* pCommandlayout, 131 | uint32_t maxCommandCount, 132 | Resource* pArgumentBuffer, 133 | uint64_t argumentBufferOffset = 0, 134 | Resource* pCountBuffer = nullptr, 135 | uint64_t countBufferOffset = 0) = 0; 136 | virtual void CopyBufferRegion(Resource* pDstBuffer, uint64_t dstOffset, 137 | Resource* pSrcBuffer, uint64_t srcOffset, uint64_t numBytes) = 0; 138 | virtual void CopyTextureRegion(const TextureCopyLocation& dst, 139 | uint32_t dstX, uint32_t dstY, uint32_t dstZ, 140 | const TextureCopyLocation& src, const BoxRange* pSrcBox = nullptr) = 0; 141 | virtual void CopyResource(Resource* pDstResource, Resource* pSrcResource) = 0; 142 | virtual void CopyTiles(Resource* pTiledResource, const TiledResourceCoord* pTileRegionStartCoord, 143 | const TileRegionSize* pTileRegionSize, const Resource* pBuffer, uint64_t bufferStartOffsetInBytes, 144 | TileCopyFlag flags) = 0; 145 | virtual void ResolveSubresource(Resource* pDstResource, uint32_t dstSubresource, 146 | Resource* pSrcResource, uint32_t srcSubresource, Format format) = 0; 147 | virtual void IASetInputLayout(const InputLayout* pLayout) = 0; 148 | virtual void IASetIndexBufferStripCutValue(IBStripCutValue ibStripCutValue) = 0; 149 | virtual void RSSetState(const Graphics::Rasterizer* pRasterizer) = 0; 150 | virtual void RSSetState(Graphics::RasterizerPreset preset) = 0; 151 | virtual void RSSetViewports(uint32_t numViewports, const Viewport* pViewports) const = 0; 152 | virtual void RSSetScissorRects(uint32_t numRects, const RectRange* pRects) const = 0; 153 | virtual void OMSetBlendState(const Graphics::Blend* pBlend, uint32_t sampleMask = UINT_MAX) = 0; 154 | virtual void OMSetBlendState(Graphics::BlendPreset preset, 155 | uint8_t numColorRTs = 1, uint32_t sampleMask = UINT_MAX) = 0; 156 | virtual void OMSetBlendFactor(const float blendFactor[4]) const = 0; 157 | virtual void OMSetStencilRef(uint32_t stencilRef) const = 0; 158 | virtual void OMSetSample(uint8_t count, uint8_t quality = 0) = 0; 159 | virtual void DSSetState(const Graphics::DepthStencil* pDepthStencil) = 0; 160 | virtual void DSSetState(Graphics::DepthStencilPreset preset) = 0; 161 | virtual void SetGraphicsShader(Shader::Stage stage, const Blob& shader) = 0; 162 | virtual void SetGraphicsNodeMask(uint32_t nodeMask) = 0; 163 | virtual void SetComputeShader(const Blob& shader) = 0; 164 | virtual void SetComputeNodeMask(uint32_t nodeMask) = 0; 165 | virtual void SetGraphicsPipelineState(const Pipeline& pipelineState, const Graphics::State* pState = nullptr) = 0; 166 | virtual void SetComputePipelineState(const Pipeline& pipelineState, const Compute::State* pState = nullptr) = 0; 167 | virtual void ExecuteBundle(const XUSG::CommandList* pCommandList) const = 0; 168 | virtual void SetSamplers(Shader::Stage stage, uint32_t startBinding, 169 | uint32_t numSamplers, const Sampler* const* pSamplers) = 0; 170 | virtual void SetSamplerStates(Shader::Stage stage, uint32_t startBinding, 171 | uint32_t numSamplers, const SamplerPreset* pSamplerPresets) = 0; 172 | virtual void SetResources(Shader::Stage stage, DescriptorType descriptorType, uint32_t startBinding, 173 | uint32_t numResources, const ResourceView* pResourceViews, uint32_t space = 0) = 0; 174 | virtual void SetGraphicsDescriptorTable(Shader::Stage stage, DescriptorType descriptorType, const DescriptorTable& descriptorTable, uint32_t space) = 0; 175 | virtual void SetComputeDescriptorTable(DescriptorType descriptorType, const DescriptorTable& descriptorTable, uint32_t space) = 0; 176 | virtual void SetGraphics32BitConstant(Shader::Stage stage, uint32_t srcData, uint32_t destOffsetIn32BitValues = 0) = 0; 177 | virtual void SetCompute32BitConstant(uint32_t srcData, uint32_t destOffsetIn32BitValues = 0) = 0; 178 | virtual void SetGraphics32BitConstants(Shader::Stage stage, uint32_t num32BitValuesToSet, const void* pSrcData, uint32_t destOffsetIn32BitValues = 0) = 0; 179 | virtual void SetCompute32BitConstants(uint32_t num32BitValuesToSet, const void* pSrcData, uint32_t destOffsetIn32BitValues = 0) = 0; 180 | 181 | virtual void IASetPrimitiveTopology(PrimitiveTopology primitiveTopology) = 0; 182 | virtual void IASetIndexBuffer(const IndexBufferView& view) = 0; 183 | virtual void IASetVertexBuffers(uint32_t startSlot, uint32_t numViews, const VertexBufferView* pViews) = 0; 184 | virtual void SOSetTargets(uint32_t startSlot, uint32_t numViews, const StreamOutBufferView* pViews, Resource* const* ppResources) = 0; 185 | virtual void OMSetRenderTargets( 186 | uint32_t numRenderTargets, 187 | const ResourceView* pRenderTargetViews, 188 | const ResourceView* pDepthStencilView = nullptr) = 0; 189 | virtual void ClearDepthStencilView(const ResourceView& depthStencilView, ClearFlag clearFlags, 190 | float depth, uint8_t stencil = 0, uint32_t numRects = 0, const RectRange* pRects = nullptr) = 0; 191 | virtual void ClearRenderTargetView(const ResourceView& renderTargetView, const float colorRGBA[4], 192 | uint32_t numRects = 0, const RectRange* pRects = nullptr) = 0; 193 | virtual void ClearUnorderedAccessViewUint(const ResourceView& unorderedAccessView, const uint32_t values[4], 194 | uint32_t numRects = 0, const RectRange* pRects = nullptr) = 0; 195 | virtual void ClearUnorderedAccessViewFloat(const ResourceView& unorderedAccessView, const float values[4], 196 | uint32_t numRects = 0, const RectRange* pRects = nullptr) = 0; 197 | virtual void DiscardResource(const Resource* pResource, uint32_t numRects, const RectRange* pRects, 198 | uint32_t firstSubresource, uint32_t numSubresources) = 0; 199 | virtual void BeginQuery(const QueryHeap& queryHeap, QueryType type, uint32_t index) const = 0; 200 | virtual void EndQuery(const QueryHeap& queryHeap, QueryType type, uint32_t index) const = 0; 201 | virtual void ResolveQueryData(const QueryHeap& queryHeap, QueryType type, uint32_t startIndex, 202 | uint32_t numQueries, const Resource* pDstBuffer, uint64_t alignedDstBufferOffset) const = 0; 203 | virtual void SetPredication(const Resource* pBuffer, uint64_t alignedBufferOffset, bool opEqualZero) const = 0; 204 | virtual void SetMarker(uint32_t metaData, const void* pData, uint32_t size) const = 0; 205 | virtual void BeginEvent(uint32_t metaData, const void* pData, uint32_t size) const = 0; 206 | virtual void EndEvent() = 0; 207 | 208 | virtual void Resize() = 0; 209 | 210 | virtual void Blit(Texture* pDstResource, Texture* pSrcResource, SamplerPreset sampler, 211 | const Blob& customShader = nullptr, uint32_t dstMip = 0, uint32_t srcMip = 0) = 0; 212 | virtual void Blit(Texture3D* pDstResource, Texture* pSrcResource, SamplerPreset sampler, 213 | const Blob& customShader = nullptr, uint32_t dstMip = 0, uint32_t srcMip = 0) = 0; 214 | 215 | virtual void GenerateMips(Texture* pResource, SamplerPreset sampler, const Blob& customShader = nullptr) = 0; 216 | virtual void GenerateMips(Texture3D* pResource, SamplerPreset sampler, const Blob& customShader = nullptr) = 0; 217 | 218 | virtual const Graphics::Blend* GetBlend(Graphics::BlendPreset preset, uint8_t numColorRTs = 1) = 0; 219 | virtual const Graphics::Rasterizer* GetRasterizer(Graphics::RasterizerPreset preset) = 0; 220 | virtual const Graphics::DepthStencil* GetDepthStencil(Graphics::DepthStencilPreset preset) = 0; 221 | 222 | virtual DescriptorTableLib* GetDescriptorTableLib() const = 0; 223 | 224 | virtual const XUSG::PipelineLayout& GetGraphicsPipelineLayout() const = 0; 225 | virtual const XUSG::PipelineLayout& GetComputePipelineLayout() const = 0; 226 | 227 | virtual uint32_t GetGraphicsConstantParamIndex(Shader::Stage stage) const = 0; 228 | virtual uint32_t GetComputeConstantParamIndex() const = 0; 229 | 230 | virtual void* GetHandle() const = 0; 231 | virtual void* GetDeviceHandle() const = 0; 232 | 233 | virtual const Device* GetDevice() const = 0; 234 | virtual XUSG::CommandList* AsCommandList() = 0; 235 | 236 | using uptr = std::unique_ptr; 237 | using sptr = std::shared_ptr; 238 | 239 | static uptr MakeUnique(API api = API::DIRECTX_12); 240 | static sptr MakeShared(API api = API::DIRECTX_12); 241 | static uptr MakeUnique(XUSG::CommandList* pCommandList, 242 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 243 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 244 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 245 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 246 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 247 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 248 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 249 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 250 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 251 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 252 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 253 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 254 | API api = API::DIRECTX_12); 255 | static sptr MakeShared(XUSG::CommandList* pCommandList, 256 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 257 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 258 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 259 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 260 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 261 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 262 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 263 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 264 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 265 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 266 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 267 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 268 | API api = API::DIRECTX_12); 269 | }; 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Helper/XUSGRayTracing-EZ.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "XUSGUltimate-EZ.h" 8 | #include "RayTracing/XUSGRayTracing.h" 9 | 10 | namespace XUSG 11 | { 12 | namespace RayTracing 13 | { 14 | namespace EZ 15 | { 16 | XUSG_INTERFACE XUSG::EZ::ResourceView GetSRV(TopLevelAS* pTLAS); 17 | 18 | //-------------------------------------------------------------------------------------- 19 | // RayTracing command list 20 | //-------------------------------------------------------------------------------------- 21 | class XUSG_INTERFACE CommandList : 22 | public virtual Ultimate::EZ::CommandList 23 | { 24 | public: 25 | //CommandList(); 26 | virtual ~CommandList() {} 27 | 28 | using uptr = std::unique_ptr; 29 | using sptr = std::shared_ptr; 30 | 31 | virtual bool Create(RayTracing::CommandList* pCommandList, 32 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize) = 0; 33 | virtual bool Create(const RayTracing::Device* pDevice, void* pHandle, uint32_t samplerHeapSize, 34 | uint32_t cbvSrvUavHeapSize, const wchar_t* name = nullptr) = 0; 35 | // Must be called after all acceleration structures allocated 36 | // By default maxCbvsEachSpace[stage] = 14 for graphics or 12 for ray tracing and compute 37 | // maxSamplers[stage] = 16, maxSrvsEachSpace[stage] = 32, and maxUavsEachSpace[stage] = 16 38 | virtual bool CreatePipelineLayouts( 39 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 40 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 41 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 42 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 43 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 44 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 45 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 46 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 47 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 48 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 49 | uint32_t maxTLASSrvs = 0, uint32_t spaceTLAS = 0, 50 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE) = 0; 51 | virtual bool Reset(const CommandAllocator* pAllocator, const Pipeline& initialState) = 0; 52 | virtual bool PrebuildBLAS(BottomLevelAS* pBLAS, uint32_t numGeometries, const GeometryBuffer& geometries, 53 | BuildFlag flags = BuildFlag::PREFER_FAST_TRACE) = 0; 54 | virtual bool PrebuildTLAS(TopLevelAS* pTLAS, uint32_t numInstances, 55 | BuildFlag flags = BuildFlag::PREFER_FAST_TRACE) = 0; 56 | 57 | // Auto allocate a buffer with byteWidth = GetResultDataMaxByteSize() when setting byteWidth = 0 58 | virtual bool AllocateAccelerationStructure(AccelerationStructure* pAccelerationStructure, size_t byteWidth = 0) = 0; 59 | 60 | virtual void SetTriangleGeometries(GeometryBuffer& geometries, uint32_t numGeometries, Format vertexFormat, 61 | XUSG::EZ::VertexBufferView* pVBs, XUSG::EZ::IndexBufferView* pIBs = nullptr, 62 | const GeometryFlag* pGeometryFlags = nullptr, const ResourceView* pTransforms = nullptr) = 0; 63 | virtual void SetAABBGeometries(GeometryBuffer& geometries, uint32_t numGeometries, 64 | XUSG::EZ::VertexBufferView* pVBs, const GeometryFlag* pGeometryFlags = nullptr) = 0; 65 | virtual void SetBLASDestination(BottomLevelAS* pBLAS, const Buffer::sptr destBuffer, 66 | uintptr_t byteOffset, uint32_t uavIndex) = 0; 67 | virtual void SetTLASDestination(TopLevelAS* pTLAS, const Buffer::sptr destBuffer, 68 | uintptr_t byteOffset, uint32_t uavIndex, uint32_t srvIndex) = 0; 69 | virtual void BuildBLAS(BottomLevelAS* pBLAS, const BottomLevelAS* pSource = nullptr, 70 | uint8_t numPostbuildInfoDescs = 0, const PostbuildInfoType* pPostbuildInfoTypes = nullptr) = 0; 71 | virtual void BuildTLAS(TopLevelAS* pTLAS, const Resource* pInstanceDescs, const TopLevelAS* pSource = nullptr, 72 | uint8_t numPostbuildInfoDescs = 0, const PostbuildInfoType* pPostbuildInfoTypes = nullptr) = 0; 73 | virtual void CopyRaytracingAccelerationStructure(const AccelerationStructure* pDst, 74 | const AccelerationStructure* pSrc, CopyMode mode) = 0; 75 | virtual void SetTopLevelAccelerationStructure(uint32_t binding, const TopLevelAS* pTopLevelAS) const = 0; 76 | virtual void RTSetShaderLibrary(uint32_t index, const Blob& shaderLib, 77 | uint32_t numShaders = 0, const wchar_t** pShaderNames = nullptr) = 0; 78 | virtual void RTSetHitGroup(uint32_t index, const wchar_t* hitGroupName, const wchar_t* closestHitShaderName, 79 | const wchar_t* anyHitShaderName = nullptr, const wchar_t* intersectionShaderName = nullptr, 80 | HitGroupType type = HitGroupType::TRIANGLES) = 0; 81 | virtual void RTSetShaderConfig(uint32_t maxPayloadSize, uint32_t maxAttributeSize = sizeof(float[2])) = 0; 82 | virtual void RTSetMaxRecursionDepth(uint32_t depth) = 0; 83 | virtual void RTSetPipelineState(const Pipeline& pipelineState, RayTracing::State* pState = nullptr) = 0; 84 | virtual void DispatchRays(uint32_t width, uint32_t height, uint32_t depth, const wchar_t* rayGenShaderName, 85 | const wchar_t* const* pMissShaderNames, uint32_t numMissShaders) = 0; 86 | virtual void DispatchRaysIndirect(const CommandLayout* pCommandlayout, 87 | uint32_t maxCommandCount, 88 | const wchar_t* rayGenShaderName, 89 | const wchar_t* const* pMissShaderNames, 90 | uint32_t numMissShaders, 91 | Resource* pArgumentBuffer, 92 | uint64_t argumentBufferOffset = 0, 93 | Resource* pCountBuffer = nullptr, 94 | uint64_t countBufferOffset = 0) = 0; 95 | 96 | virtual size_t GetDispatchRaysArgReservedOffset() const = 0; 97 | 98 | virtual const Device* GetRTDevice() const = 0; 99 | virtual RayTracing::CommandList* AsRTCommandList() = 0; 100 | 101 | static uptr MakeUnique(API api = API::DIRECTX_12); 102 | static sptr MakeShared(API api = API::DIRECTX_12); 103 | static uptr MakeUnique(RayTracing::CommandList* pCommandList, uint32_t samplerHeapSize, 104 | uint32_t cbvSrvUavHeapSize, API api = API::DIRECTX_12); 105 | static sptr MakeShared(RayTracing::CommandList* pCommandList, uint32_t samplerHeapSize, 106 | uint32_t cbvSrvUavHeapSize, API api = API::DIRECTX_12); 107 | }; 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/Helper/XUSGUltimate-EZ.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "XUSG-EZ.h" 8 | #include "Ultimate/XUSGUltimate.h" 9 | 10 | namespace XUSG 11 | { 12 | namespace Ultimate 13 | { 14 | namespace EZ 15 | { 16 | XUSG_INTERFACE XUSG::EZ::ResourceView GetUAV(SamplerFeedBack* pResource); 17 | 18 | //-------------------------------------------------------------------------------------- 19 | // Ultimate command list 20 | //-------------------------------------------------------------------------------------- 21 | class XUSG_INTERFACE CommandList : 22 | public virtual XUSG::EZ::CommandList 23 | { 24 | public: 25 | //CommandList(); 26 | virtual ~CommandList() {} 27 | 28 | using uptr = std::unique_ptr; 29 | using sptr = std::shared_ptr; 30 | 31 | // By default maxSamplers[stage] = 16, maxCbvsEachSpace[stage] = 14, maxSrvsEachSpace[stage] = 32, and maxUavsEachSpace[stage] = 16 32 | virtual bool Create(Ultimate::CommandList* pCommandList, 33 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 34 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 35 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 36 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 37 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 38 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 39 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 40 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 41 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 42 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 43 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 44 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE) = 0; 45 | virtual bool Create(const Device* pDevice, void* pHandle, 46 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 47 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 48 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 49 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 50 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 51 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 52 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 53 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 54 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 55 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 56 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 57 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 58 | const wchar_t* name = nullptr) = 0; 59 | 60 | virtual void SetSamplePositions(uint8_t numSamplesPerPixel, uint8_t numPixels, SamplePosition* pPositions) const = 0; 61 | virtual void ResolveSubresourceRegion(Resource* pDstResource, uint32_t dstSubresource, 62 | uint32_t dstX, uint32_t dstY, Resource* pSrcResource, uint32_t srcSubresource, 63 | const RectRange& srcRect, Format format, ResolveMode resolveMode) = 0; 64 | 65 | virtual void RSSetShadingRate(ShadingRate baseShadingRate, const ShadingRateCombiner* pCombiners) const = 0; 66 | virtual void RSSetShadingRateImage(Resource* pShadingRateImage) = 0; 67 | 68 | using XUSG::EZ::CommandList::SetGraphicsPipelineState; 69 | virtual void SetGraphicsPipelineState(const Pipeline& pipelineState, const State* pState = nullptr) = 0; 70 | virtual void OMSetBlendState(const Graphics::Blend* pBlend, uint32_t sampleMask = UINT_MAX) = 0; 71 | virtual void OMSetBlendState(Graphics::BlendPreset preset, uint8_t numColorRTs = 1, uint32_t sampleMask = UINT_MAX) = 0; 72 | virtual void OMSetSample(uint8_t count, uint8_t quality = 0) = 0; 73 | virtual void RSSetState(const Graphics::Rasterizer* pRasterizer) = 0; 74 | virtual void RSSetState(Graphics::RasterizerPreset preset) = 0; 75 | virtual void DSSetState(const Graphics::DepthStencil* pDepthStencil) = 0; 76 | virtual void DSSetState(Graphics::DepthStencilPreset preset) = 0; 77 | virtual void SetGraphicsShader(Shader::Stage stage, const Blob& shader) = 0; 78 | virtual void MSSetGraphicsShader(Shader::Stage stage, const Blob& shader) = 0; 79 | virtual void SetGraphicsNodeMask(uint32_t nodeMask) = 0; 80 | virtual void DispatchMesh(uint32_t ThreadGroupCountX, uint32_t ThreadGroupCountY, uint32_t ThreadGroupCountZ) = 0; 81 | virtual void DispatchMeshIndirect(const CommandLayout* pCommandlayout, 82 | uint32_t maxCommandCount, 83 | Resource* pArgumentBuffer, 84 | uint64_t argumentBufferOffset = 0, 85 | Resource* pCountBuffer = nullptr, 86 | uint64_t countBufferOffset = 0) = 0; 87 | virtual void OMSetRenderTargets( 88 | uint32_t numRenderTargets, 89 | const XUSG::EZ::ResourceView* pRenderTargetViews, 90 | const XUSG::EZ::ResourceView* pDepthStencilView = nullptr) = 0; 91 | virtual void WGSetShaderLibrary(uint32_t index, const Blob& shaderLib, 92 | uint32_t numShaders = 0, const wchar_t** pShaderNames = nullptr) = 0; 93 | virtual void WGSetProgramName(const wchar_t* name) = 0; 94 | virtual void WGOverrideDispatchGrid(const wchar_t* shaderName, uint32_t x, uint32_t y, uint32_t z, 95 | WorkGraph::BoolOverride isEntry = WorkGraph::BoolOverride::IS_NULL) = 0; 96 | virtual void WGOverrideMaxDispatchGrid(const wchar_t* shaderName, uint32_t x, uint32_t y, uint32_t z, 97 | WorkGraph::BoolOverride isEntry = WorkGraph::BoolOverride::IS_NULL) = 0; 98 | virtual void DispatchGraph(uint32_t numNodeInputs, const NodeCPUInput* pNodeInputs, uint64_t nodeInputByteStride = 0) = 0; 99 | virtual void DispatchGraph(uint64_t nodeGPUInputAddress, bool isMultiNodes = false) = 0; 100 | 101 | virtual const XUSG::PipelineLayout& GetMSPipelineLayout() const = 0; 102 | 103 | virtual uint32_t GetMSConstantParamIndex(Shader::Stage stage) const = 0; 104 | 105 | virtual uint32_t WGGetIndex() = 0; 106 | virtual uint32_t WGGetNumNodes() = 0; 107 | virtual uint32_t WGGetNodeIndex(const WorkGraph::NodeID& nodeID) = 0; 108 | virtual uint32_t WGGetNumEntrypoints() = 0; 109 | virtual uint32_t WGGetEntrypointIndex(const WorkGraph::NodeID& nodeID) = 0; 110 | virtual uint32_t WGGetEntrypointRecordSizeInBytes(uint32_t entryPointIndex) = 0; 111 | 112 | virtual WorkGraph::NodeID WGGetNodeID(uint32_t nodeIndex) = 0; 113 | virtual WorkGraph::NodeID WGGetEntrypointID(uint32_t entryPointIndex) = 0; 114 | 115 | static uptr MakeUnique(API api = API::DIRECTX_12); 116 | static sptr MakeShared(API api = API::DIRECTX_12); 117 | static uptr MakeUnique(Ultimate::CommandList* pCommandList, 118 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 119 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE] = nullptr, 120 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 121 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 122 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 123 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 124 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 125 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 126 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 127 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 128 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 129 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 130 | API api = API::DIRECTX_12); 131 | static sptr MakeShared(Ultimate::CommandList* pCommandList, 132 | uint32_t samplerHeapSize, uint32_t cbvSrvUavHeapSize, 133 | const uint32_t maxSamplers[Shader::Stage::NUM_STAGE], 134 | const uint32_t* pMaxCbvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 135 | const uint32_t* pMaxSrvsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 136 | const uint32_t* pMaxUavsEachSpace[Shader::Stage::NUM_STAGE] = nullptr, 137 | const uint32_t maxCbvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 138 | const uint32_t maxSrvSpaces[Shader::Stage::NUM_STAGE] = nullptr, 139 | const uint32_t maxUavSpaces[Shader::Stage::NUM_STAGE] = nullptr, 140 | const uint32_t max32BitConstants[Shader::Stage::NUM_STAGE] = nullptr, 141 | const uint32_t constantSlots[Shader::Stage::NUM_STAGE] = nullptr, 142 | const uint32_t constantSpaces[Shader::Stage::NUM_STAGE] = nullptr, 143 | uint32_t slotExt = 0, uint32_t spaceExt = 0x7FFF0ADE, 144 | API api = API::DIRECTX_12); 145 | }; 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /RayTracedSPH/XUSG/RayTracing/XUSGRayTracing.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // Copyright (c) XU, Tianchen. All rights reserved. 3 | //-------------------------------------------------------------------------------------- 4 | 5 | #pragma once 6 | 7 | #include "Ultimate/XUSGUltimate.h" 8 | 9 | namespace XUSG 10 | { 11 | namespace RayTracing 12 | { 13 | enum class BuildFlag 14 | { 15 | NONE = 0, 16 | ALLOW_UPDATE = (1 << 0), 17 | ALLOW_COMPACTION = (1 << 1), 18 | PREFER_FAST_TRACE = (1 << 2), 19 | PREFER_FAST_BUILD = (1 << 3), 20 | MINIMIZE_MEMORY = (1 << 4), 21 | PERFORM_UPDATE = (1 << 5) 22 | }; 23 | 24 | XUSG_DEF_ENUM_FLAG_OPERATORS(BuildFlag); 25 | 26 | enum class GeometryFlag 27 | { 28 | NONE = 0, 29 | FULL_OPAQUE = (1 << 0), 30 | NO_DUPLICATE_ANYHIT_INVOCATION = (1 << 1) 31 | }; 32 | 33 | XUSG_DEF_ENUM_FLAG_OPERATORS(GeometryFlag); 34 | 35 | enum class InstanceFlag { 36 | NONE = 0, 37 | TRIANGLE_CULL_DISABLE = (1 << 0), 38 | TRIANGLE_FRONT_COUNTERCLOCKWISE = (1 << 1), 39 | FORCE_OPAQUE = (1 << 2), 40 | FORCE_NON_OPAQUE = (1 << 3) 41 | }; 42 | 43 | XUSG_DEF_ENUM_FLAG_OPERATORS(InstanceFlag); 44 | 45 | enum class HitGroupType : uint8_t 46 | { 47 | TRIANGLES, 48 | PROCEDURAL 49 | }; 50 | 51 | enum class PostbuildInfoType : uint8_t 52 | { 53 | COMPACTED_SIZE, 54 | TOOLS_VISUALIZATION, 55 | SERIALIZATION, 56 | CURRENT_SIZE 57 | }; 58 | 59 | enum class CopyMode : uint8_t 60 | { 61 | CLONE, 62 | COMPACT, 63 | VISUALIZATION_DECODE_FOR_TOOLS, 64 | SERIALIZE, 65 | DESERIALIZE 66 | }; 67 | 68 | using BuildDesc = void; 69 | using GeometryBuffer = std::vector; 70 | 71 | struct PrebuildInfo 72 | { 73 | uint64_t ResultDataMaxByteSize; 74 | uint64_t ScratchDataByteSize; 75 | uint64_t UpdateScratchDataByteSize; 76 | }; 77 | 78 | struct PostbuildInfo 79 | { 80 | uint64_t DestBuffer; 81 | PostbuildInfoType InfoType; 82 | }; 83 | 84 | struct ResourceView 85 | { 86 | const Resource* pResource; 87 | uint64_t Offset; 88 | }; 89 | 90 | //-------------------------------------------------------------------------------------- 91 | // Device 92 | //-------------------------------------------------------------------------------------- 93 | class XUSG_INTERFACE Device : 94 | public virtual XUSG::Device 95 | { 96 | public: 97 | //Device(); 98 | virtual ~Device() {}; 99 | 100 | virtual bool CreateInterface(uint8_t flags = 0) = 0; 101 | 102 | virtual void* GetRTHandle() const = 0; 103 | 104 | using uptr = std::unique_ptr; 105 | using sptr = std::shared_ptr; 106 | 107 | static uptr MakeUnique(API api = API::DIRECTX_12); 108 | static sptr MakeShared(API api = API::DIRECTX_12); 109 | }; 110 | 111 | //-------------------------------------------------------------------------------------- 112 | // Acceleration structure 113 | //-------------------------------------------------------------------------------------- 114 | class CommandList; 115 | 116 | class XUSG_INTERFACE AccelerationStructure 117 | { 118 | public: 119 | //AccelerationStructure(); 120 | virtual ~AccelerationStructure() {} 121 | 122 | // Auto allocate a buffer with byteWidth = GetResultDataMaxByteSize() when setting byteWidth = 0 123 | virtual bool Allocate(const Device* pDevice, DescriptorTableLib* pDescriptorTableLib, size_t byteWidth = 0, 124 | MemoryFlag memoryFlags = MemoryFlag::NONE, const wchar_t* name = nullptr, uint32_t maxThreads = 1) = 0; 125 | 126 | virtual void SetDestination(const Device* pDevice, const Buffer::sptr destBuffer, 127 | uintptr_t byteOffset, uint32_t uavIndex, DescriptorTableLib* pDescriptorTableLib) = 0; 128 | 129 | virtual uint32_t SetBarrier(ResourceBarrier* pBarriers, uint32_t numBarriers = 0) = 0; 130 | 131 | virtual const PrebuildInfo& GetPrebuildInfo() const = 0; 132 | 133 | virtual Buffer* GetPostbuildInfo() const = 0; 134 | 135 | virtual size_t GetResultDataMaxByteSize(bool isAligned = true) const = 0; 136 | virtual size_t GetScratchDataByteSize() const = 0; 137 | virtual size_t GetUpdateScratchDataByteSize() const = 0; 138 | virtual size_t GetCompactedByteSize(bool isAligned = true) const = 0; 139 | 140 | virtual uint64_t GetVirtualAddress() const = 0; 141 | virtual uint64_t GetResourcePointer() const = 0; 142 | 143 | static bool AllocateDestBuffer(const Device* pDevice, Buffer* pDestBuffer, size_t byteWidth, 144 | uint32_t numSRVs = 1, const uintptr_t* firstSrvElements = nullptr, 145 | uint32_t numUAVs = 1, const uintptr_t* firstUavElements = nullptr, 146 | MemoryFlag memoryFlags = MemoryFlag::NONE, const wchar_t* name = nullptr, 147 | uint32_t maxThreads = 1, API api = API::DIRECTX_12); 148 | static bool AllocateUAVBuffer(const Device* pDevice, Buffer* pBuffer, size_t byteWidth, 149 | ResourceState dstState = ResourceState::COMMON, MemoryFlag memoryFlags = MemoryFlag::NONE, 150 | const wchar_t* name = nullptr, 151 | uint32_t maxThreads = 1); 152 | static bool AllocateUploadBuffer(const Device* pDevice, Buffer* pBuffer, size_t byteWidth, 153 | void* pData, MemoryFlag memoryFlags = MemoryFlag::NONE, const wchar_t* name = nullptr); 154 | 155 | static uint32_t SetBarrier(ResourceBarrier* pBarriers, Resource* pResource, uint32_t numBarriers = 0); 156 | 157 | static size_t Align(size_t byteSize, API api = API::DIRECTX_12); 158 | }; 159 | 160 | //-------------------------------------------------------------------------------------- 161 | // Bottom-level acceleration structure 162 | //-------------------------------------------------------------------------------------- 163 | class XUSG_INTERFACE BottomLevelAS : 164 | public virtual AccelerationStructure 165 | { 166 | public: 167 | //BottomLevelAS(); 168 | virtual ~BottomLevelAS() {} 169 | 170 | virtual bool Prebuild(const Device* pDevice, uint32_t numGeometries, const GeometryBuffer& geometries, 171 | BuildFlag flags = BuildFlag::PREFER_FAST_TRACE) = 0; 172 | 173 | virtual void Build(CommandList* pCommandList, const Resource* pScratch, 174 | const BottomLevelAS* pSource = nullptr, uint8_t numPostbuildInfoDescs = 0, 175 | const PostbuildInfoType* pPostbuildInfoTypes = nullptr) = 0; 176 | 177 | static void SetTriangleGeometries(GeometryBuffer& geometries, uint32_t numGeometries, Format vertexFormat, 178 | const VertexBufferView* pVBs, const IndexBufferView* pIBs = nullptr, 179 | const GeometryFlag* pGeometryFlags = nullptr, const ResourceView* pTransforms = nullptr, 180 | API api = API::DIRECTX_12); 181 | static void SetAABBGeometries(GeometryBuffer& geometries, uint32_t numGeometries, 182 | const VertexBufferView* pVBs, const GeometryFlag* pGeometryFlags = nullptr, 183 | API api = API::DIRECTX_12); 184 | 185 | using uptr = std::unique_ptr; 186 | using sptr = std::shared_ptr; 187 | 188 | static uptr MakeUnique(API api = API::DIRECTX_12); 189 | static sptr MakeShared(API api = API::DIRECTX_12); 190 | }; 191 | 192 | //-------------------------------------------------------------------------------------- 193 | // Top-level acceleration structure 194 | //-------------------------------------------------------------------------------------- 195 | class XUSG_INTERFACE TopLevelAS : 196 | public virtual AccelerationStructure 197 | { 198 | public: 199 | struct InstanceDesc 200 | { 201 | const float* pTransform; 202 | unsigned int InstanceID : 24; 203 | unsigned int InstanceMask : 8; 204 | unsigned int InstanceContributionToHitGroupIndex : 24; 205 | unsigned int Flags : 8; 206 | const BottomLevelAS* pBottomLevelAS; 207 | }; 208 | 209 | //TopLevelAS(); 210 | virtual ~TopLevelAS() {} 211 | 212 | virtual bool Prebuild(const Device* pDevice, uint32_t numInstances, 213 | BuildFlag flags = BuildFlag::PREFER_FAST_TRACE) = 0; 214 | 215 | virtual void SetDestination(const Device* pDevice, const Buffer::sptr destBuffer, uintptr_t byteOffset, 216 | uint32_t uavIndex, uint32_t srvIndex, DescriptorTableLib* pDescriptorTableLib) = 0; 217 | virtual void Build(CommandList* pCommandList, const Resource* pScratch, 218 | const Resource* pInstanceDescs, const DescriptorHeap& descriptorHeap, 219 | const TopLevelAS* pSource = nullptr, uint8_t numPostbuildInfoDescs = 0, 220 | const PostbuildInfoType* pPostbuildInfoTypes = nullptr) = 0; 221 | 222 | virtual const Descriptor& GetSRV() const = 0; 223 | 224 | static void SetInstances(const Device* pDevice, Buffer* pInstances, uint32_t numInstances, 225 | const BottomLevelAS* const* ppBottomLevelASs, const float* const* transforms, 226 | MemoryFlag memoryFlags = MemoryFlag::NONE, const wchar_t* instanceName = nullptr, 227 | API api = API::DIRECTX_12); 228 | static void SetInstances(const Device* pDevice, Buffer* pInstances, uint32_t numInstances, 229 | const InstanceDesc* pInstanceDescs, MemoryFlag memoryFlags = MemoryFlag::NONE, 230 | const wchar_t* instanceName = nullptr, API api = API::DIRECTX_12); 231 | 232 | using uptr = std::unique_ptr; 233 | using sptr = std::shared_ptr; 234 | 235 | static uptr MakeUnique(API api = API::DIRECTX_12); 236 | static sptr MakeShared(API api = API::DIRECTX_12); 237 | }; 238 | 239 | //-------------------------------------------------------------------------------------- 240 | // Shader record 241 | //-------------------------------------------------------------------------------------- 242 | class XUSG_INTERFACE ShaderRecord 243 | { 244 | public: 245 | //ShaderRecord(const void* pShaderIdentifier, uint32_t shaderIdentifierSize, 246 | //const void* pLocalDescriptorArgs = nullptr, uint32_t localDescriptorArgSize = 0); 247 | //ShaderRecord(const Device* pDevice, const Pipeline& pipeline, const wchar_t* shaderName, 248 | //const void* pLocalDescriptorArgs = nullptr, uint32_t localDescriptorArgSize = 0); 249 | virtual ~ShaderRecord() {} 250 | 251 | virtual void CopyTo(void* dest) const = 0; 252 | 253 | static const void* GetShaderIdentifier(const Pipeline& pipeline, const wchar_t* shaderName, API api = API::DIRECTX_12); 254 | 255 | static uint32_t GetShaderIdentifierSize(const Device* pDevice, API api = API::DIRECTX_12); 256 | 257 | using uptr = std::unique_ptr; 258 | using sptr = std::shared_ptr; 259 | 260 | static uptr MakeUnique(void* pShaderIdentifier, uint32_t shaderIdentifierSize, const void* pLocalDescriptorArgs = nullptr, 261 | uint32_t localDescriptorArgSize = 0, API api = API::DIRECTX_12); 262 | static sptr MakeShared(void* pShaderIdentifier, uint32_t shaderIdentifierSize, const void* pLocalDescriptorArgs = nullptr, 263 | uint32_t localDescriptorArgSize = 0, API api = API::DIRECTX_12); 264 | static uptr MakeUnique(const Device* pDevice, const Pipeline& pipeline, const wchar_t* shaderName, 265 | const void* pLocalDescriptorArgs = nullptr, uint32_t localDescriptorArgSize = 0, 266 | API api = API::DIRECTX_12); // shader - shader name for DX12 267 | static sptr MakeShared(const Device* pDevice, const Pipeline& pipeline, const wchar_t* shaderName, 268 | const void* pLocalDescriptorArgs = nullptr, uint32_t localDescriptorArgSize = 0, 269 | API api = API::DIRECTX_12); // shader - shader name for DX12 270 | 271 | static size_t Align(uint32_t byteSize, API api = API::DIRECTX_12); 272 | }; 273 | 274 | //-------------------------------------------------------------------------------------- 275 | // Shader table 276 | //-------------------------------------------------------------------------------------- 277 | class XUSG_INTERFACE ShaderTable 278 | { 279 | public: 280 | //ShaderTable(); 281 | virtual ~ShaderTable() {} 282 | 283 | virtual bool Create(const XUSG::Device* pDevice, uint32_t numShaderRecords, uint32_t shaderRecordSize, 284 | MemoryFlag memoryFlags = MemoryFlag::NONE, const wchar_t* name = nullptr) = 0; 285 | 286 | virtual void Create(Buffer::sptr resource, uint32_t shaderRecordSize, uintptr_t byteOffset) = 0; 287 | virtual void AddShaderRecord(const ShaderRecord* pShaderRecord) = 0; 288 | virtual void Reset() = 0; 289 | 290 | virtual uint64_t GetVirtualAddress() const = 0; 291 | virtual size_t GetByteSize() const = 0; 292 | virtual size_t GetByteStride() const = 0; 293 | 294 | using uptr = std::unique_ptr; 295 | using sptr = std::shared_ptr; 296 | 297 | static uptr MakeUnique(API api = API::DIRECTX_12); 298 | static sptr MakeShared(API api = API::DIRECTX_12); 299 | 300 | static size_t Align(size_t byteSize, API api = API::DIRECTX_12); 301 | }; 302 | 303 | //-------------------------------------------------------------------------------------- 304 | // Command list 305 | //-------------------------------------------------------------------------------------- 306 | class XUSG_INTERFACE CommandList : 307 | public virtual Ultimate::CommandList 308 | { 309 | public: 310 | //CommandList(); 311 | virtual ~CommandList() {} 312 | 313 | virtual bool CreateInterface() = 0; 314 | 315 | virtual void BuildRaytracingAccelerationStructure(const BuildDesc* pDesc, 316 | uint32_t numPostbuildInfoDescs, const PostbuildInfo* pPostbuildInfoDescs, 317 | const DescriptorHeap* pDescriptorHeap = nullptr) = 0; 318 | virtual void EmitRaytracingAccelerationStructurePostbuildInfo(const PostbuildInfo* pDesc, 319 | uint32_t numAccelerationStructures, const uint64_t* pAccelerationStructureData) const = 0; 320 | virtual void CopyRaytracingAccelerationStructure(const AccelerationStructure* pDst, 321 | const AccelerationStructure* pSrc, CopyMode mode, 322 | const DescriptorHeap* pDescriptorHeap = nullptr) = 0; 323 | 324 | virtual void SetDescriptorHeaps(uint32_t numDescriptorHeaps, const DescriptorHeap* pDescriptorHeaps) = 0; 325 | virtual void SetTopLevelAccelerationStructure(uint32_t index, const TopLevelAS* pTopLevelAS) const = 0; 326 | virtual void SetTopLevelAccelerationStructure(uint32_t index, uint64_t topLevelASPtr) const = 0; 327 | virtual void SetRayTracingPipeline(const Pipeline& pipeline) const = 0; 328 | virtual void DispatchRays(uint32_t width, uint32_t height, uint32_t depth, 329 | const ShaderTable* pRayGen, const ShaderTable* pHitGroup, const ShaderTable* pMiss, 330 | const ShaderTable* pCallable = nullptr) const = 0; 331 | 332 | virtual const Device* GetRTDevice() const = 0; 333 | 334 | using uptr = std::unique_ptr; 335 | using sptr = std::shared_ptr; 336 | 337 | static uptr MakeUnique(API api = API::DIRECTX_12); 338 | static sptr MakeShared(API api = API::DIRECTX_12); 339 | static uptr MakeUnique(XUSG::CommandList* pCommandList, const RayTracing::Device* pDevice, API api = API::DIRECTX_12); 340 | static sptr MakeShared(XUSG::CommandList* pCommandList, const RayTracing::Device* pDevice, API api = API::DIRECTX_12); 341 | }; 342 | 343 | //-------------------------------------------------------------------------------------- 344 | // Pipeline layout 345 | //-------------------------------------------------------------------------------------- 346 | class XUSG_INTERFACE PipelineLayout : 347 | public virtual Util::PipelineLayout 348 | { 349 | public: 350 | //PipelineLayout(); 351 | virtual ~PipelineLayout() {} 352 | 353 | virtual XUSG::PipelineLayout CreatePipelineLayout(const Device* pDevice, PipelineLayoutLib* pPipelineLayoutLib, 354 | PipelineLayoutFlag flags, const wchar_t* name = nullptr) = 0; 355 | virtual XUSG::PipelineLayout GetPipelineLayout(const Device* pDevice, PipelineLayoutLib* pPipelineLayoutLib, 356 | PipelineLayoutFlag flags, const wchar_t* name = nullptr) = 0; 357 | 358 | using uptr = std::unique_ptr; 359 | using sptr = std::shared_ptr; 360 | 361 | static uptr MakeUnique(API api = API::DIRECTX_12); 362 | static sptr MakeShared(API api = API::DIRECTX_12); 363 | }; 364 | 365 | //-------------------------------------------------------------------------------------- 366 | // Pipeline state 367 | //-------------------------------------------------------------------------------------- 368 | class PipelineLib; 369 | 370 | class XUSG_INTERFACE State 371 | { 372 | public: 373 | //State(); 374 | virtual ~State() {} 375 | 376 | virtual void SetShaderLibrary(uint32_t index, const Blob& shaderLib, 377 | uint32_t numShaders = 0, const wchar_t** pShaderNames = nullptr) = 0; 378 | virtual void SetHitGroup(uint32_t index, const wchar_t* hitGroupName, const wchar_t* closestHitShaderName, 379 | const wchar_t* anyHitShaderName = nullptr, const wchar_t* intersectionShaderName = nullptr, 380 | HitGroupType type = HitGroupType::TRIANGLES) = 0; 381 | virtual void SetShaderConfig(uint32_t maxPayloadSize, uint32_t maxAttributeSize) = 0; 382 | virtual void SetLocalPipelineLayout(uint32_t index, const XUSG::PipelineLayout& layout, 383 | uint32_t numShaders, const wchar_t** pShaderNames) = 0; 384 | virtual void SetGlobalPipelineLayout(const XUSG::PipelineLayout& layout) = 0; 385 | virtual void SetMaxRecursionDepth(uint32_t depth) = 0; 386 | virtual void SetNodeMask(uint32_t nodeMask) = 0; 387 | 388 | virtual Pipeline CreatePipeline(PipelineLib* pPipelineCache, const wchar_t* name = nullptr) = 0; 389 | virtual Pipeline GetPipeline(PipelineLib* pPipelineCache, const wchar_t* name = nullptr) = 0; 390 | 391 | virtual const wchar_t* GetHitGroupName(uint32_t index) = 0; 392 | virtual uint32_t GetNumHitGroups() = 0; 393 | 394 | using uptr = std::unique_ptr; 395 | using sptr = std::shared_ptr; 396 | 397 | static uptr MakeUnique(API api = API::DIRECTX_12); 398 | static sptr MakeShared(API api = API::DIRECTX_12); 399 | }; 400 | 401 | class XUSG_INTERFACE PipelineLib 402 | { 403 | public: 404 | //PipelineLib(); 405 | //PipelineLib(const Device* pDevice); 406 | virtual ~PipelineLib() {} 407 | 408 | virtual void SetDevice(const Device* pDevice) = 0; 409 | virtual void SetPipeline(State* pState, const Pipeline& pipeline) = 0; 410 | 411 | virtual Pipeline CreatePipeline(State* pState, const wchar_t* name = nullptr) = 0; 412 | virtual Pipeline GetPipeline(State* pState, const wchar_t* name = nullptr) = 0; 413 | 414 | using uptr = std::unique_ptr; 415 | using sptr = std::shared_ptr; 416 | 417 | static uptr MakeUnique(API api = API::DIRECTX_12); 418 | static sptr MakeShared(API api = API::DIRECTX_12); 419 | static uptr MakeUnique(const Device* pDevice, API api = API::DIRECTX_12); 420 | static sptr MakeShared(const Device* pDevice, API api = API::DIRECTX_12); 421 | }; 422 | } 423 | } 424 | -------------------------------------------------------------------------------- /RayTracedSPH/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. -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | -------------------------------------------------------------------------------- /RayTracedSPH/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 | 35 | #if _HAS_CXX17 36 | #include 37 | #else 38 | #include 39 | #include 40 | #include 41 | #include 42 | #endif 43 | #include 44 | #include 45 | #include 46 | 47 | #include "D3D12RaytracingFallback.h" 48 | 49 | #if defined(DEBUG) | defined(_DEBUG) 50 | #ifndef DBG_NEW 51 | #define DBG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__) 52 | #define new DBG_NEW 53 | #endif 54 | #endif // _DEBUG 55 | --------------------------------------------------------------------------------