RayTracingPass.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Atom/Feature/RayTracing/RayTracingPass.h>
  9. #include <Atom/Feature/RayTracing/RayTracingPassData.h>
  10. #include <Atom/RHI/CommandList.h>
  11. #include <Atom/RHI/DeviceDispatchRaysItem.h>
  12. #include <Atom/RHI/DevicePipelineState.h>
  13. #include <Atom/RHI/DispatchRaysItem.h>
  14. #include <Atom/RHI/Factory.h>
  15. #include <Atom/RHI/FrameScheduler.h>
  16. #include <Atom/RHI/RHISystemInterface.h>
  17. #include <Atom/RHI/RHIUtils.h>
  18. #include <Atom/RPI.Public/Base.h>
  19. #include <Atom/RPI.Public/Pass/PassUtils.h>
  20. #include <Atom/RPI.Public/RPIUtils.h>
  21. #include <Atom/RPI.Public/RenderPipeline.h>
  22. #include <Atom/RPI.Public/Scene.h>
  23. #include <Atom/RPI.Public/View.h>
  24. #include <Atom/RPI.Reflect/Pass/PassTemplate.h>
  25. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  26. #include <AzCore/Asset/AssetCommon.h>
  27. #include <AzCore/Asset/AssetManagerBus.h>
  28. #include <RayTracing/RayTracingFeatureProcessor.h>
  29. using uint = uint32_t;
  30. using uint4 = uint[4];
  31. #include "../../../Feature/Common/Assets/ShaderLib/Atom/Features/IndirectRendering.azsli"
  32. namespace AZ
  33. {
  34. namespace Render
  35. {
  36. RPI::Ptr<RayTracingPass> RayTracingPass::Create(const RPI::PassDescriptor& descriptor)
  37. {
  38. RPI::Ptr<RayTracingPass> pass = aznew RayTracingPass(descriptor);
  39. return pass;
  40. }
  41. RayTracingPass::RayTracingPass(const RPI::PassDescriptor& descriptor)
  42. : RenderPass(descriptor)
  43. , m_passDescriptor(descriptor)
  44. , m_dispatchRaysItem(RHI::RHISystemInterface::Get()->GetRayTracingSupport())
  45. {
  46. m_flags.m_canBecomeASubpass = false;
  47. if (RHI::RHISystemInterface::Get()->GetRayTracingSupport() == RHI::MultiDevice::NoDevices)
  48. {
  49. // raytracing is not supported on this platform
  50. SetEnabled(false);
  51. return;
  52. }
  53. m_passData = RPI::PassUtils::GetPassData<RayTracingPassData>(m_passDescriptor);
  54. if (m_passData == nullptr)
  55. {
  56. AZ_Error("PassSystem", false, "RayTracingPass [%s]: Invalid RayTracingPassData", GetPathName().GetCStr());
  57. return;
  58. }
  59. m_indirectDispatch = m_passData->m_indirectDispatch;
  60. m_indirectDispatchBufferSlotName = m_passData->m_indirectDispatchBufferSlotName;
  61. m_fullscreenDispatch = m_passData->m_fullscreenDispatch;
  62. m_fullscreenSizeSourceSlotName = m_passData->m_fullscreenSizeSourceSlotName;
  63. AZ_Assert(
  64. !(m_indirectDispatch && m_fullscreenDispatch),
  65. "[RaytracingPass '%s']: Only one of the dispatch options (indirect, fullscreen) can be active",
  66. GetPathName().GetCStr());
  67. m_defaultShaderAttachmentStage = RHI::ScopeAttachmentStage::RayTracingShader;
  68. CreatePipelineState();
  69. }
  70. RayTracingPass::~RayTracingPass()
  71. {
  72. RPI::ShaderReloadNotificationBus::MultiHandler::BusDisconnect();
  73. }
  74. void RayTracingPass::CreatePipelineState()
  75. {
  76. m_rayTracingShaderTable.reset();
  77. m_maxRayLengthInputIndex.Reset();
  78. struct RTShaderLib
  79. {
  80. AZ::Data::AssetId m_shaderAssetId;
  81. AZ::Data::Instance<AZ::RPI::Shader> m_shader;
  82. AZ::RHI::PipelineStateDescriptorForRayTracing m_pipelineStateDescriptor;
  83. AZ::Name m_rayGenerationShaderName;
  84. AZ::Name m_missShaderName;
  85. AZ::Name m_closestHitShaderName;
  86. AZ::Name m_closestHitProceduralShaderName;
  87. };
  88. AZStd::fixed_vector<RTShaderLib, 4> shaderLibs;
  89. auto loadRayTracingShader = [&](auto& assetReference, const AZ::Name& supervariantName = AZ::Name("")) -> RTShaderLib&
  90. {
  91. auto it = std::find_if(
  92. shaderLibs.begin(),
  93. shaderLibs.end(),
  94. [&](auto& entry)
  95. {
  96. return entry.m_shaderAssetId == assetReference.m_assetId;
  97. });
  98. if (it != shaderLibs.end())
  99. {
  100. return *it;
  101. }
  102. auto shaderAsset{ AZ::RPI::FindShaderAsset(assetReference.m_assetId, assetReference.m_filePath) };
  103. AZ_Assert(shaderAsset.IsReady(), "Failed to load shader %s", assetReference.m_filePath.c_str());
  104. auto shader{ AZ::RPI::Shader::FindOrCreate(shaderAsset, supervariantName) };
  105. auto shaderVariant{ shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId) };
  106. AZ::RHI::PipelineStateDescriptorForRayTracing pipelineStateDescriptor;
  107. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor, shader->GetDefaultShaderOptions());
  108. auto& shaderLib = shaderLibs.emplace_back();
  109. shaderLib.m_shaderAssetId = assetReference.m_assetId;
  110. shaderLib.m_shader = shader;
  111. shaderLib.m_pipelineStateDescriptor = pipelineStateDescriptor;
  112. return shaderLib;
  113. };
  114. auto& rayGenShaderLib{ loadRayTracingShader(m_passData->m_rayGenerationShaderAssetReference) };
  115. rayGenShaderLib.m_rayGenerationShaderName = m_passData->m_rayGenerationShaderName;
  116. m_rayGenerationShader = rayGenShaderLib.m_shader;
  117. auto& closestHitShaderLib{ loadRayTracingShader(m_passData->m_closestHitShaderAssetReference) };
  118. closestHitShaderLib.m_closestHitShaderName = m_passData->m_closestHitShaderName;
  119. m_closestHitShader = closestHitShaderLib.m_shader;
  120. if (!m_passData->m_closestHitProceduralShaderName.empty())
  121. {
  122. auto& closestHitProceduralShaderLib{ loadRayTracingShader(
  123. m_passData->m_closestHitProceduralShaderAssetReference, AZ::RHI::GetDefaultSupervariantNameWithNoFloat16Fallback()) };
  124. closestHitProceduralShaderLib.m_closestHitProceduralShaderName = m_passData->m_closestHitProceduralShaderName;
  125. m_closestHitProceduralShader = closestHitProceduralShaderLib.m_shader;
  126. }
  127. auto& missShaderLib{ loadRayTracingShader(m_passData->m_missShaderAssetReference) };
  128. missShaderLib.m_missShaderName = m_passData->m_missShaderName;
  129. m_missShader = missShaderLib.m_shader;
  130. m_globalPipelineState = m_rayGenerationShader->AcquirePipelineState(shaderLibs.front().m_pipelineStateDescriptor);
  131. AZ_Assert(m_globalPipelineState, "Failed to acquire ray tracing global pipeline state");
  132. // create global srg
  133. const auto& globalSrgLayout = m_rayGenerationShader->FindShaderResourceGroupLayout(RayTracingGlobalSrgBindingSlot);
  134. AZ_Error("PassSystem", globalSrgLayout != nullptr, "RayTracingPass [%s] Failed to find RayTracingGlobalSrg layout", GetPathName().GetCStr());
  135. m_shaderResourceGroup = RPI::ShaderResourceGroup::Create( m_rayGenerationShader->GetAsset(), m_rayGenerationShader->GetSupervariantIndex(), globalSrgLayout->GetName());
  136. AZ_Assert(m_shaderResourceGroup, "RayTracingPass [%s]: Failed to create RayTracingGlobalSrg", GetPathName().GetCStr());
  137. RPI::PassUtils::BindDataMappingsToSrg(m_passDescriptor, m_shaderResourceGroup.get());
  138. // check to see if the shader requires the View, Scene, or RayTracingMaterial Srgs
  139. const auto& viewSrgLayout = m_rayGenerationShader->FindShaderResourceGroupLayout(RPI::SrgBindingSlot::View);
  140. m_requiresViewSrg = (viewSrgLayout != nullptr);
  141. const auto& sceneSrgLayout = m_rayGenerationShader->FindShaderResourceGroupLayout(RPI::SrgBindingSlot::Scene);
  142. m_requiresSceneSrg = (sceneSrgLayout != nullptr);
  143. const auto& rayTracingMaterialSrgLayout = m_rayGenerationShader->FindShaderResourceGroupLayout(RayTracingMaterialSrgBindingSlot);
  144. m_requiresRayTracingMaterialSrg = (rayTracingMaterialSrgLayout != nullptr);
  145. const auto& rayTracingSceneSrgLayout = m_rayGenerationShader->FindShaderResourceGroupLayout(RayTracingSceneSrgBindingSlot);
  146. m_requiresRayTracingSceneSrg = (rayTracingSceneSrgLayout != nullptr);
  147. // build the ray tracing pipeline state descriptor
  148. RHI::RayTracingPipelineStateDescriptor descriptor;
  149. descriptor.Build()
  150. ->PipelineState(m_globalPipelineState.get())
  151. ->MaxPayloadSize(m_passData->m_maxPayloadSize)
  152. ->MaxAttributeSize(m_passData->m_maxAttributeSize)
  153. ->MaxRecursionDepth(m_passData->m_maxRecursionDepth);
  154. for (auto& shaderLib : shaderLibs)
  155. {
  156. descriptor.ShaderLibrary(shaderLib.m_pipelineStateDescriptor);
  157. if (!shaderLib.m_rayGenerationShaderName.IsEmpty())
  158. {
  159. descriptor.RayGenerationShaderName(AZ::Name{ m_passData->m_rayGenerationShaderName });
  160. }
  161. if (!shaderLib.m_closestHitShaderName.IsEmpty())
  162. {
  163. descriptor.ClosestHitShaderName(AZ::Name{ m_passData->m_closestHitShaderName });
  164. }
  165. if (!shaderLib.m_closestHitProceduralShaderName.IsEmpty())
  166. {
  167. descriptor.ClosestHitShaderName(AZ::Name{ m_passData->m_closestHitProceduralShaderName });
  168. }
  169. if (!shaderLib.m_missShaderName.IsEmpty())
  170. {
  171. descriptor.MissShaderName(AZ::Name{ m_passData->m_missShaderName });
  172. }
  173. }
  174. descriptor.HitGroup(AZ::Name("HitGroup"))->ClosestHitShaderName(AZ::Name(m_passData->m_closestHitShaderName.c_str()));
  175. RayTracingFeatureProcessor* rayTracingFeatureProcessor =
  176. GetScene() ? GetScene()->GetFeatureProcessor<RayTracingFeatureProcessor>() : nullptr;
  177. if (rayTracingFeatureProcessor && !m_passData->m_closestHitProceduralShaderName.empty())
  178. {
  179. const auto& proceduralGeometryTypes = rayTracingFeatureProcessor->GetProceduralGeometryTypes();
  180. for (auto it = proceduralGeometryTypes.cbegin(); it != proceduralGeometryTypes.cend(); ++it)
  181. {
  182. auto shaderVariant{ it->m_intersectionShader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId) };
  183. AZ::RHI::PipelineStateDescriptorForRayTracing pipelineStateDescriptor;
  184. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  185. descriptor.ShaderLibrary(pipelineStateDescriptor);
  186. descriptor.IntersectionShaderName(it->m_intersectionShaderName);
  187. descriptor.HitGroup(it->m_name)
  188. ->ClosestHitShaderName(AZ::Name(m_passData->m_closestHitProceduralShaderName))
  189. ->IntersectionShaderName(it->m_intersectionShaderName);
  190. }
  191. }
  192. // create the ray tracing pipeline state object
  193. m_rayTracingPipelineState = aznew RHI::RayTracingPipelineState;
  194. m_rayTracingPipelineState->Init(RHI::RHISystemInterface::Get()->GetRayTracingSupport(), descriptor);
  195. // register the ray tracing and global pipeline state object with the dispatch-item
  196. m_dispatchRaysItem.SetRayTracingPipelineState(m_rayTracingPipelineState.get());
  197. m_dispatchRaysItem.SetPipelineState(m_globalPipelineState.get());
  198. // make sure the shader table rebuilds if we're hotreloading
  199. m_rayTracingShaderTableRevision = 0;
  200. // store the max ray length
  201. m_maxRayLength = m_passData->m_maxRayLength;
  202. RPI::ShaderReloadNotificationBus::MultiHandler::BusDisconnect();
  203. RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_rayGenerationShaderAssetReference.m_assetId);
  204. RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_closestHitShaderAssetReference.m_assetId);
  205. RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_closestHitProceduralShaderAssetReference.m_assetId);
  206. RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_missShaderAssetReference.m_assetId);
  207. RPI::ShaderReloadNotificationBus::MultiHandler::BusConnect(m_passData->m_intersectionShaderAssetReference.m_assetId);
  208. }
  209. bool RayTracingPass::IsEnabled() const
  210. {
  211. if (!RenderPass::IsEnabled())
  212. {
  213. return false;
  214. }
  215. RPI::Scene* scene = m_pipeline->GetScene();
  216. if (!scene)
  217. {
  218. return false;
  219. }
  220. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  221. if (!rayTracingFeatureProcessor)
  222. {
  223. return false;
  224. }
  225. return true;
  226. }
  227. void RayTracingPass::BuildInternal()
  228. {
  229. if (m_indirectDispatch)
  230. {
  231. if (!m_indirectDispatchRaysBufferSignature)
  232. {
  233. AZ::RHI::IndirectBufferLayout bufferLayout;
  234. bufferLayout.AddIndirectCommand(AZ::RHI::IndirectCommandDescriptor(AZ::RHI::IndirectCommandType::DispatchRays));
  235. if (!bufferLayout.Finalize())
  236. {
  237. AZ_Assert(false, "Fail to finalize Indirect Layout");
  238. }
  239. m_indirectDispatchRaysBufferSignature = aznew AZ::RHI::IndirectBufferSignature();
  240. AZ::RHI::IndirectBufferSignatureDescriptor signatureDescriptor{};
  241. signatureDescriptor.m_layout = bufferLayout;
  242. [[maybe_unused]] auto result = m_indirectDispatchRaysBufferSignature->Init(
  243. AZ::RHI::RHISystemInterface::Get()->GetRayTracingSupport(), signatureDescriptor);
  244. AZ_Assert(result == AZ::RHI::ResultCode::Success, "Fail to initialize Indirect Buffer Signature");
  245. }
  246. m_indirectDispatchRaysBufferBinding = nullptr;
  247. if (!m_indirectDispatchBufferSlotName.IsEmpty())
  248. {
  249. m_indirectDispatchRaysBufferBinding = FindAttachmentBinding(m_indirectDispatchBufferSlotName);
  250. AZ_Assert(m_indirectDispatchRaysBufferBinding,
  251. "[RaytracingPass '%s']: Indirect dispatch buffer slot %s not found.",
  252. GetPathName().GetCStr(),
  253. m_indirectDispatchBufferSlotName.GetCStr());
  254. if (m_indirectDispatchRaysBufferBinding)
  255. {
  256. AZ_Assert(
  257. m_indirectDispatchRaysBufferBinding->m_scopeAttachmentUsage == AZ::RHI::ScopeAttachmentUsage::Indirect,
  258. "[RaytracingPass '%s']: Indirect dispatch buffer slot %s needs ScopeAttachmentUsage::Indirect.",
  259. GetPathName().GetCStr(),
  260. m_indirectDispatchBufferSlotName.GetCStr())
  261. }
  262. }
  263. else
  264. {
  265. for (auto& binding : m_attachmentBindings)
  266. {
  267. if (binding.m_scopeAttachmentUsage == AZ::RHI::ScopeAttachmentUsage::Indirect)
  268. {
  269. m_indirectDispatchRaysBufferBinding = &binding;
  270. break;
  271. }
  272. }
  273. AZ_Assert(m_indirectDispatchRaysBufferBinding,
  274. "[RaytracingPass '%s']: No valid indirect dispatch buffer slot found.",
  275. GetPathName().GetCStr());
  276. }
  277. if (!m_dispatchRaysIndirectBuffer)
  278. {
  279. m_dispatchRaysIndirectBuffer =
  280. aznew AZ::RHI::DispatchRaysIndirectBuffer{ AZ::RHI::RHISystemInterface::Get()->GetRayTracingSupport() };
  281. m_dispatchRaysIndirectBuffer->Init(
  282. AZ::RPI::BufferSystemInterface::Get()->GetCommonBufferPool(AZ::RPI::CommonBufferPoolType::Indirect).get());
  283. }
  284. }
  285. else if (m_fullscreenDispatch)
  286. {
  287. m_fullscreenSizeSourceBinding = nullptr;
  288. if (!m_fullscreenSizeSourceSlotName.IsEmpty())
  289. {
  290. m_fullscreenSizeSourceBinding = FindAttachmentBinding(m_fullscreenSizeSourceSlotName);
  291. AZ_Assert(
  292. m_fullscreenSizeSourceBinding,
  293. "[RaytracingPass '%s']: Fullscreen size source slot %s not found.",
  294. GetPathName().GetCStr(),
  295. m_fullscreenSizeSourceSlotName.GetCStr());
  296. }
  297. else
  298. {
  299. if (GetOutputCount() > 0)
  300. {
  301. m_fullscreenSizeSourceBinding = &GetOutputBinding(0);
  302. }
  303. else if (!m_fullscreenSizeSourceBinding && GetInputOutputCount() > 0)
  304. {
  305. m_fullscreenSizeSourceBinding = &GetInputOutputBinding(0);
  306. }
  307. AZ_Assert(
  308. m_fullscreenSizeSourceBinding,
  309. "[RaytracingPass '%s']: No valid Output or InputOutput slot as a fullscreen size source found.",
  310. GetPathName().GetCStr());
  311. }
  312. }
  313. }
  314. void RayTracingPass::FrameBeginInternal(FramePrepareParams params)
  315. {
  316. RPI::Scene* scene = m_pipeline->GetScene();
  317. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  318. if (!rayTracingFeatureProcessor)
  319. {
  320. return;
  321. }
  322. RPI::RenderPass::FrameBeginInternal(params);
  323. }
  324. void RayTracingPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph)
  325. {
  326. RPI::Scene* scene = m_pipeline->GetScene();
  327. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  328. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  329. RPI::RenderPass::SetupFrameGraphDependencies(frameGraph);
  330. frameGraph.SetEstimatedItemCount(1);
  331. // TLAS
  332. {
  333. const RHI::Ptr<RHI::Buffer>& rayTracingTlasBuffer = rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer();
  334. if (rayTracingTlasBuffer)
  335. {
  336. AZ::RHI::AttachmentId tlasAttachmentId = rayTracingFeatureProcessor->GetTlasAttachmentId();
  337. if (frameGraph.GetAttachmentDatabase().IsAttachmentValid(tlasAttachmentId) == false)
  338. {
  339. [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportBuffer(tlasAttachmentId, rayTracingTlasBuffer);
  340. AZ_Assert(result == RHI::ResultCode::Success, "Failed to import ray tracing TLAS buffer with error %d", result);
  341. }
  342. uint32_t tlasBufferByteCount = aznumeric_cast<uint32_t>(rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer()->GetDescriptor().m_byteCount);
  343. RHI::BufferViewDescriptor tlasBufferViewDescriptor =
  344. RHI::BufferViewDescriptor::CreateRayTracingTLAS(tlasBufferByteCount);
  345. RHI::BufferScopeAttachmentDescriptor desc;
  346. desc.m_attachmentId = tlasAttachmentId;
  347. desc.m_bufferViewDescriptor = tlasBufferViewDescriptor;
  348. desc.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Load;
  349. frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::RayTracingShader);
  350. }
  351. }
  352. }
  353. void RayTracingPass::CompileResources(const RHI::FrameGraphCompileContext& context)
  354. {
  355. RPI::Scene* scene = m_pipeline->GetScene();
  356. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  357. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  358. if (m_indirectDispatch)
  359. {
  360. if (m_indirectDispatchRaysBufferBinding)
  361. {
  362. auto& attachment{ m_indirectDispatchRaysBufferBinding->GetAttachment() };
  363. AZ_Assert(
  364. attachment,
  365. "[RayTracingPass '%s']: Indirect dispatch buffer slot %s has no attachment.",
  366. GetPathName().GetCStr(),
  367. m_indirectDispatchRaysBufferBinding->m_name.GetCStr());
  368. if (attachment)
  369. {
  370. auto* indirectDispatchBuffer{ context.GetBuffer(attachment->GetAttachmentId()) };
  371. m_indirectDispatchRaysBufferView = AZ::RHI::IndirectBufferView{ *indirectDispatchBuffer,
  372. *m_indirectDispatchRaysBufferSignature,
  373. 0,
  374. sizeof(DispatchRaysIndirectCommand),
  375. sizeof(DispatchRaysIndirectCommand) };
  376. RHI::DispatchRaysIndirect dispatchRaysArgs(
  377. 1, m_indirectDispatchRaysBufferView, 0, m_dispatchRaysIndirectBuffer.get());
  378. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  379. }
  380. }
  381. }
  382. else if (m_fullscreenDispatch)
  383. {
  384. auto& attachment = m_fullscreenSizeSourceBinding->GetAttachment();
  385. AZ_Assert(
  386. attachment,
  387. "[RaytracingPass '%s']: Slot %s has no attachment for fullscreen size source.",
  388. GetPathName().GetCStr(),
  389. m_fullscreenSizeSourceBinding->m_name.GetCStr());
  390. AZ::RHI::DispatchRaysDirect dispatchRaysArgs;
  391. if (attachment)
  392. {
  393. AZ_Assert(
  394. attachment->GetAttachmentType() == AZ::RHI::AttachmentType::Image,
  395. "[RaytracingPass '%s']: Slot %s must be an image for fullscreen size source.",
  396. GetPathName().GetCStr(),
  397. m_fullscreenSizeSourceBinding->m_name.GetCStr());
  398. auto imageDescriptor = context.GetImageDescriptor(attachment->GetAttachmentId());
  399. dispatchRaysArgs.m_width = imageDescriptor.m_size.m_width;
  400. dispatchRaysArgs.m_height = imageDescriptor.m_size.m_height;
  401. dispatchRaysArgs.m_depth = imageDescriptor.m_size.m_depth;
  402. }
  403. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  404. }
  405. else
  406. {
  407. AZ::RHI::DispatchRaysDirect dispatchRaysArgs{ m_passData->m_threadCountX,
  408. m_passData->m_threadCountY,
  409. m_passData->m_threadCountZ };
  410. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  411. }
  412. uint32_t proceduralGeometryTypeRevision = rayTracingFeatureProcessor->GetProceduralGeometryTypeRevision();
  413. if (m_proceduralGeometryTypeRevision != proceduralGeometryTypeRevision)
  414. {
  415. CreatePipelineState();
  416. RPI::SceneNotificationBus::Event(
  417. GetScene()->GetId(),
  418. &RPI::SceneNotification::OnRenderPipelineChanged,
  419. GetRenderPipeline(),
  420. RPI::SceneNotification::RenderPipelineChangeType::PassChanged);
  421. m_proceduralGeometryTypeRevision = proceduralGeometryTypeRevision;
  422. }
  423. if (!m_rayTracingShaderTable || m_rayTracingShaderTableRevision != rayTracingFeatureProcessor->GetRevision())
  424. {
  425. // scene changed, need to rebuild the shader table
  426. m_rayTracingShaderTableRevision = rayTracingFeatureProcessor->GetRevision();
  427. m_rayTracingShaderTable = aznew AZ::RHI::RayTracingShaderTable();
  428. m_rayTracingShaderTable->Init(
  429. AZ::RHI::RHISystemInterface::Get()->GetRayTracingSupport(), rayTracingFeatureProcessor->GetBufferPools());
  430. AZStd::shared_ptr<RHI::RayTracingShaderTableDescriptor> descriptor = AZStd::make_shared<RHI::RayTracingShaderTableDescriptor>();
  431. if (rayTracingFeatureProcessor->HasGeometry())
  432. {
  433. // build the ray tracing shader table descriptor
  434. RHI::RayTracingShaderTableDescriptor* descriptorBuild = descriptor->Build(AZ::Name("RayTracingShaderTable"), m_rayTracingPipelineState)
  435. ->RayGenerationRecord(AZ::Name(m_passData->m_rayGenerationShaderName.c_str()))
  436. ->MissRecord(AZ::Name(m_passData->m_missShaderName.c_str()));
  437. // add a hit group for standard meshes mesh to the shader table
  438. descriptorBuild->HitGroupRecord(AZ::Name("HitGroup"));
  439. // add a hit group for each procedural geometry type to the shader table
  440. const auto& proceduralGeometryTypes = rayTracingFeatureProcessor->GetProceduralGeometryTypes();
  441. for (auto it = proceduralGeometryTypes.cbegin(); it != proceduralGeometryTypes.cend(); ++it)
  442. {
  443. descriptorBuild->HitGroupRecord(it->m_name);
  444. // TODO(intersection): Set per-hitgroup SRG once RayTracingPipelineState supports local root signatures
  445. }
  446. }
  447. m_rayTracingShaderTable->Build(descriptor);
  448. // register the shader-table with the dispatch item
  449. m_dispatchRaysItem.SetRayTracingPipelineState(m_rayTracingPipelineState.get());
  450. m_dispatchRaysItem.SetRayTracingShaderTable(m_rayTracingShaderTable.get());
  451. }
  452. // Collect and register the Srgs (RayTracingGlobal, RayTracingScene, ViewSrg, SceneSrg and RayTracingMaterialSrg)
  453. // The more consistent way would be to call BindSrg() of the RenderPass, and then call
  454. // SetSrgsForDispatchRays() in BuildCommandListInternal, but that function doesn't exist.
  455. // [GFX TODO][ATOM-15610] Add RenderPass::SetSrgsForRayTracingDispatch
  456. if (m_shaderResourceGroup != nullptr)
  457. {
  458. m_shaderResourceGroup->SetConstant(m_maxRayLengthInputIndex, m_maxRayLength);
  459. BindPassSrg(context, m_shaderResourceGroup);
  460. m_shaderResourceGroup->Compile();
  461. m_rayTracingSRGsToBind.push_back(m_shaderResourceGroup->GetRHIShaderResourceGroup());
  462. }
  463. if (m_requiresRayTracingSceneSrg)
  464. {
  465. m_rayTracingSRGsToBind.push_back(rayTracingFeatureProcessor->GetRayTracingSceneSrg()->GetRHIShaderResourceGroup());
  466. }
  467. if (m_requiresViewSrg)
  468. {
  469. RPI::ViewPtr view = m_pipeline->GetFirstView(GetPipelineViewTag());
  470. if (view)
  471. {
  472. m_rayTracingSRGsToBind.push_back(view->GetShaderResourceGroup()->GetRHIShaderResourceGroup());
  473. }
  474. }
  475. if (m_requiresSceneSrg)
  476. {
  477. m_rayTracingSRGsToBind.push_back(scene->GetShaderResourceGroup()->GetRHIShaderResourceGroup());
  478. }
  479. if (m_requiresRayTracingMaterialSrg)
  480. {
  481. m_rayTracingSRGsToBind.push_back(rayTracingFeatureProcessor->GetRayTracingMaterialSrg()->GetRHIShaderResourceGroup());
  482. }
  483. }
  484. void RayTracingPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context)
  485. {
  486. RPI::Scene* scene = m_pipeline->GetScene();
  487. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  488. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  489. if (!rayTracingFeatureProcessor || !rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer() ||
  490. !rayTracingFeatureProcessor->HasGeometry() || !m_rayTracingShaderTable)
  491. {
  492. return;
  493. }
  494. if (m_dispatchRaysShaderTableRevision != m_rayTracingShaderTableRevision)
  495. {
  496. m_dispatchRaysShaderTableRevision = m_rayTracingShaderTableRevision;
  497. if (m_dispatchRaysIndirectBuffer)
  498. {
  499. m_dispatchRaysIndirectBuffer->Build(m_rayTracingShaderTable.get());
  500. }
  501. }
  502. // TODO: change this to BindSrgsForDispatchRays() as soon as it exists
  503. // IMPORTANT: The data in shaderResourceGroups must be sorted by (entry)->GetBindingSlot() (FrequencyId value in SRG source file
  504. // from SrgSemantics.azsli) in order for them to be correctly assigned by Vulkan
  505. AZStd::sort(
  506. m_rayTracingSRGsToBind.begin(),
  507. m_rayTracingSRGsToBind.end(),
  508. [](const auto& lhs, const auto& rhs)
  509. {
  510. return lhs->GetBindingSlot() < rhs->GetBindingSlot();
  511. });
  512. m_dispatchRaysItem.SetShaderResourceGroups(m_rayTracingSRGsToBind.data(), static_cast<uint32_t>(m_rayTracingSRGsToBind.size()));
  513. // submit the DispatchRays item
  514. context.GetCommandList()->Submit(m_dispatchRaysItem.GetDeviceDispatchRaysItem(context.GetDeviceIndex()));
  515. }
  516. void RayTracingPass::FrameEndInternal()
  517. {
  518. m_rayTracingSRGsToBind.clear();
  519. }
  520. void RayTracingPass::OnShaderReinitialized([[maybe_unused]] const RPI::Shader& shader)
  521. {
  522. CreatePipelineState();
  523. }
  524. void RayTracingPass::OnShaderAssetReinitialized([[maybe_unused]] const Data::Asset<RPI::ShaderAsset>& shaderAsset)
  525. {
  526. CreatePipelineState();
  527. }
  528. void RayTracingPass::OnShaderVariantReinitialized(const RPI::ShaderVariant&)
  529. {
  530. CreatePipelineState();
  531. }
  532. } // namespace Render
  533. } // namespace AZ