RayTracingPass.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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::MultiDevice::AllDevices)
  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 =
  243. m_indirectDispatchRaysBufferSignature->Init(AZ::RHI::MultiDevice::AllDevices, 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 = aznew AZ::RHI::DispatchRaysIndirectBuffer{ AZ::RHI::MultiDevice::AllDevices };
  280. m_dispatchRaysIndirectBuffer->Init(
  281. AZ::RPI::BufferSystemInterface::Get()->GetCommonBufferPool(AZ::RPI::CommonBufferPoolType::Indirect).get());
  282. }
  283. }
  284. else if (m_fullscreenDispatch)
  285. {
  286. m_fullscreenSizeSourceBinding = nullptr;
  287. if (!m_fullscreenSizeSourceSlotName.IsEmpty())
  288. {
  289. m_fullscreenSizeSourceBinding = FindAttachmentBinding(m_fullscreenSizeSourceSlotName);
  290. AZ_Assert(
  291. m_fullscreenSizeSourceBinding,
  292. "[RaytracingPass '%s']: Fullscreen size source slot %s not found.",
  293. GetPathName().GetCStr(),
  294. m_fullscreenSizeSourceSlotName.GetCStr());
  295. }
  296. else
  297. {
  298. if (GetOutputCount() > 0)
  299. {
  300. m_fullscreenSizeSourceBinding = &GetOutputBinding(0);
  301. }
  302. else if (!m_fullscreenSizeSourceBinding && GetInputOutputCount() > 0)
  303. {
  304. m_fullscreenSizeSourceBinding = &GetInputOutputBinding(0);
  305. }
  306. AZ_Assert(
  307. m_fullscreenSizeSourceBinding,
  308. "[RaytracingPass '%s']: No valid Output or InputOutput slot as a fullscreen size source found.",
  309. GetPathName().GetCStr());
  310. }
  311. }
  312. }
  313. void RayTracingPass::FrameBeginInternal(FramePrepareParams params)
  314. {
  315. RPI::Scene* scene = m_pipeline->GetScene();
  316. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  317. if (!rayTracingFeatureProcessor)
  318. {
  319. return;
  320. }
  321. RPI::RenderPass::FrameBeginInternal(params);
  322. }
  323. void RayTracingPass::SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph)
  324. {
  325. RPI::Scene* scene = m_pipeline->GetScene();
  326. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  327. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  328. RPI::RenderPass::SetupFrameGraphDependencies(frameGraph);
  329. frameGraph.SetEstimatedItemCount(1);
  330. // TLAS
  331. {
  332. const RHI::Ptr<RHI::Buffer>& rayTracingTlasBuffer = rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer();
  333. if (rayTracingTlasBuffer)
  334. {
  335. AZ::RHI::AttachmentId tlasAttachmentId = rayTracingFeatureProcessor->GetTlasAttachmentId();
  336. if (frameGraph.GetAttachmentDatabase().IsAttachmentValid(tlasAttachmentId) == false)
  337. {
  338. [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportBuffer(tlasAttachmentId, rayTracingTlasBuffer);
  339. AZ_Assert(result == RHI::ResultCode::Success, "Failed to import ray tracing TLAS buffer with error %d", result);
  340. }
  341. uint32_t tlasBufferByteCount = aznumeric_cast<uint32_t>(rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer()->GetDescriptor().m_byteCount);
  342. RHI::BufferViewDescriptor tlasBufferViewDescriptor =
  343. RHI::BufferViewDescriptor::CreateRayTracingTLAS(tlasBufferByteCount);
  344. RHI::BufferScopeAttachmentDescriptor desc;
  345. desc.m_attachmentId = tlasAttachmentId;
  346. desc.m_bufferViewDescriptor = tlasBufferViewDescriptor;
  347. desc.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Load;
  348. frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::RayTracingShader);
  349. }
  350. }
  351. }
  352. void RayTracingPass::CompileResources(const RHI::FrameGraphCompileContext& context)
  353. {
  354. RPI::Scene* scene = m_pipeline->GetScene();
  355. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  356. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  357. if (m_indirectDispatch)
  358. {
  359. if (m_indirectDispatchRaysBufferBinding)
  360. {
  361. auto& attachment{ m_indirectDispatchRaysBufferBinding->GetAttachment() };
  362. AZ_Assert(
  363. attachment,
  364. "[RayTracingPass '%s']: Indirect dispatch buffer slot %s has no attachment.",
  365. GetPathName().GetCStr(),
  366. m_indirectDispatchRaysBufferBinding->m_name.GetCStr());
  367. if (attachment)
  368. {
  369. auto* indirectDispatchBuffer{ context.GetBuffer(attachment->GetAttachmentId()) };
  370. m_indirectDispatchRaysBufferView = AZ::RHI::IndirectBufferView{ *indirectDispatchBuffer,
  371. *m_indirectDispatchRaysBufferSignature,
  372. 0,
  373. sizeof(DispatchRaysIndirectCommand),
  374. sizeof(DispatchRaysIndirectCommand) };
  375. RHI::DispatchRaysIndirect dispatchRaysArgs(
  376. 1, m_indirectDispatchRaysBufferView, 0, m_dispatchRaysIndirectBuffer.get());
  377. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  378. }
  379. }
  380. }
  381. else if (m_fullscreenDispatch)
  382. {
  383. auto& attachment = m_fullscreenSizeSourceBinding->GetAttachment();
  384. AZ_Assert(
  385. attachment,
  386. "[RaytracingPass '%s']: Slot %s has no attachment for fullscreen size source.",
  387. GetPathName().GetCStr(),
  388. m_fullscreenSizeSourceBinding->m_name.GetCStr());
  389. AZ::RHI::DispatchRaysDirect dispatchRaysArgs;
  390. if (attachment)
  391. {
  392. AZ_Assert(
  393. attachment->GetAttachmentType() == AZ::RHI::AttachmentType::Image,
  394. "[RaytracingPass '%s']: Slot %s must be an image for fullscreen size source.",
  395. GetPathName().GetCStr(),
  396. m_fullscreenSizeSourceBinding->m_name.GetCStr());
  397. auto imageDescriptor = context.GetImageDescriptor(attachment->GetAttachmentId());
  398. dispatchRaysArgs.m_width = imageDescriptor.m_size.m_width;
  399. dispatchRaysArgs.m_height = imageDescriptor.m_size.m_height;
  400. dispatchRaysArgs.m_depth = imageDescriptor.m_size.m_depth;
  401. }
  402. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  403. }
  404. else
  405. {
  406. AZ::RHI::DispatchRaysDirect dispatchRaysArgs{ m_passData->m_threadCountX,
  407. m_passData->m_threadCountY,
  408. m_passData->m_threadCountZ };
  409. m_dispatchRaysItem.SetArguments(dispatchRaysArgs);
  410. }
  411. uint32_t proceduralGeometryTypeRevision = rayTracingFeatureProcessor->GetProceduralGeometryTypeRevision();
  412. if (m_proceduralGeometryTypeRevision != proceduralGeometryTypeRevision)
  413. {
  414. CreatePipelineState();
  415. RPI::SceneNotificationBus::Event(
  416. GetScene()->GetId(),
  417. &RPI::SceneNotification::OnRenderPipelineChanged,
  418. GetRenderPipeline(),
  419. RPI::SceneNotification::RenderPipelineChangeType::PassChanged);
  420. m_proceduralGeometryTypeRevision = proceduralGeometryTypeRevision;
  421. }
  422. if (!m_rayTracingShaderTable || m_rayTracingShaderTableRevision != rayTracingFeatureProcessor->GetRevision())
  423. {
  424. // scene changed, need to rebuild the shader table
  425. m_rayTracingShaderTableRevision = rayTracingFeatureProcessor->GetRevision();
  426. m_rayTracingShaderTable = aznew AZ::RHI::RayTracingShaderTable();
  427. m_rayTracingShaderTable->Init(AZ::RHI::MultiDevice::AllDevices, rayTracingFeatureProcessor->GetBufferPools());
  428. AZStd::shared_ptr<RHI::RayTracingShaderTableDescriptor> descriptor = AZStd::make_shared<RHI::RayTracingShaderTableDescriptor>();
  429. if (rayTracingFeatureProcessor->HasGeometry())
  430. {
  431. // build the ray tracing shader table descriptor
  432. RHI::RayTracingShaderTableDescriptor* descriptorBuild = descriptor->Build(AZ::Name("RayTracingShaderTable"), m_rayTracingPipelineState)
  433. ->RayGenerationRecord(AZ::Name(m_passData->m_rayGenerationShaderName.c_str()))
  434. ->MissRecord(AZ::Name(m_passData->m_missShaderName.c_str()));
  435. // add a hit group for standard meshes mesh to the shader table
  436. descriptorBuild->HitGroupRecord(AZ::Name("HitGroup"));
  437. // add a hit group for each procedural geometry type to the shader table
  438. const auto& proceduralGeometryTypes = rayTracingFeatureProcessor->GetProceduralGeometryTypes();
  439. for (auto it = proceduralGeometryTypes.cbegin(); it != proceduralGeometryTypes.cend(); ++it)
  440. {
  441. descriptorBuild->HitGroupRecord(it->m_name);
  442. // TODO(intersection): Set per-hitgroup SRG once RayTracingPipelineState supports local root signatures
  443. }
  444. }
  445. m_rayTracingShaderTable->Build(descriptor);
  446. // register the shader-table with the dispatch item
  447. m_dispatchRaysItem.SetRayTracingPipelineState(m_rayTracingPipelineState.get());
  448. m_dispatchRaysItem.SetRayTracingShaderTable(m_rayTracingShaderTable.get());
  449. }
  450. // Collect and register the Srgs (RayTracingGlobal, RayTracingScene, ViewSrg, SceneSrg and RayTracingMaterialSrg)
  451. // The more consistent way would be to call BindSrg() of the RenderPass, and then call
  452. // SetSrgsForDispatchRays() in BuildCommandListInternal, but that function doesn't exist.
  453. // [GFX TODO][ATOM-15610] Add RenderPass::SetSrgsForRayTracingDispatch
  454. if (m_shaderResourceGroup != nullptr)
  455. {
  456. m_shaderResourceGroup->SetConstant(m_maxRayLengthInputIndex, m_maxRayLength);
  457. BindPassSrg(context, m_shaderResourceGroup);
  458. m_shaderResourceGroup->Compile();
  459. m_rayTracingSRGsToBind.push_back(m_shaderResourceGroup->GetRHIShaderResourceGroup());
  460. }
  461. if (m_requiresRayTracingSceneSrg)
  462. {
  463. m_rayTracingSRGsToBind.push_back(rayTracingFeatureProcessor->GetRayTracingSceneSrg()->GetRHIShaderResourceGroup());
  464. }
  465. if (m_requiresViewSrg)
  466. {
  467. RPI::ViewPtr view = m_pipeline->GetFirstView(GetPipelineViewTag());
  468. if (view)
  469. {
  470. m_rayTracingSRGsToBind.push_back(view->GetShaderResourceGroup()->GetRHIShaderResourceGroup());
  471. }
  472. }
  473. if (m_requiresSceneSrg)
  474. {
  475. m_rayTracingSRGsToBind.push_back(scene->GetShaderResourceGroup()->GetRHIShaderResourceGroup());
  476. }
  477. if (m_requiresRayTracingMaterialSrg)
  478. {
  479. m_rayTracingSRGsToBind.push_back(rayTracingFeatureProcessor->GetRayTracingMaterialSrg()->GetRHIShaderResourceGroup());
  480. }
  481. }
  482. void RayTracingPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context)
  483. {
  484. RPI::Scene* scene = m_pipeline->GetScene();
  485. RayTracingFeatureProcessor* rayTracingFeatureProcessor = scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  486. AZ_Assert(rayTracingFeatureProcessor, "RayTracingPass requires the RayTracingFeatureProcessor");
  487. if (!rayTracingFeatureProcessor || !rayTracingFeatureProcessor->GetTlas()->GetTlasBuffer() ||
  488. !rayTracingFeatureProcessor->HasGeometry() || !m_rayTracingShaderTable)
  489. {
  490. return;
  491. }
  492. if (m_dispatchRaysShaderTableRevision != m_rayTracingShaderTableRevision)
  493. {
  494. m_dispatchRaysShaderTableRevision = m_rayTracingShaderTableRevision;
  495. if (m_dispatchRaysIndirectBuffer)
  496. {
  497. m_dispatchRaysIndirectBuffer->Build(m_rayTracingShaderTable.get());
  498. }
  499. }
  500. // TODO: change this to BindSrgsForDispatchRays() as soon as it exists
  501. // IMPORTANT: The data in shaderResourceGroups must be sorted by (entry)->GetBindingSlot() (FrequencyId value in SRG source file
  502. // from SrgSemantics.azsli) in order for them to be correctly assigned by Vulkan
  503. AZStd::sort(
  504. m_rayTracingSRGsToBind.begin(),
  505. m_rayTracingSRGsToBind.end(),
  506. [](const auto& lhs, const auto& rhs)
  507. {
  508. return lhs->GetBindingSlot() < rhs->GetBindingSlot();
  509. });
  510. m_dispatchRaysItem.SetShaderResourceGroups(m_rayTracingSRGsToBind.data(), static_cast<uint32_t>(m_rayTracingSRGsToBind.size()));
  511. // submit the DispatchRays item
  512. context.GetCommandList()->Submit(m_dispatchRaysItem.GetDeviceDispatchRaysItem(context.GetDeviceIndex()));
  513. }
  514. void RayTracingPass::FrameEndInternal()
  515. {
  516. m_rayTracingSRGsToBind.clear();
  517. }
  518. void RayTracingPass::OnShaderReinitialized([[maybe_unused]] const RPI::Shader& shader)
  519. {
  520. CreatePipelineState();
  521. }
  522. void RayTracingPass::OnShaderAssetReinitialized([[maybe_unused]] const Data::Asset<RPI::ShaderAsset>& shaderAsset)
  523. {
  524. CreatePipelineState();
  525. }
  526. void RayTracingPass::OnShaderVariantReinitialized(const RPI::ShaderVariant&)
  527. {
  528. CreatePipelineState();
  529. }
  530. } // namespace Render
  531. } // namespace AZ