XRExampleComponent.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 <RHI/XRExampleComponent.h>
  9. #include <Atom/RHI/CommandList.h>
  10. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  11. #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h>
  12. #include <Atom/RPI.Public/Shader/Shader.h>
  13. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  14. #include <AzCore/Math/Color.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <SampleComponentManager.h>
  17. #include <Utils/Utils.h>
  18. namespace AtomSampleViewer
  19. {
  20. void XRExampleComponent::Reflect(AZ::ReflectContext* context)
  21. {
  22. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  23. {
  24. serializeContext->Class<XRExampleComponent, AZ::Component>()->Version(0);
  25. }
  26. }
  27. XRExampleComponent::XRExampleComponent()
  28. {
  29. m_supportRHISamplePipeline = true;
  30. }
  31. void XRExampleComponent::Activate()
  32. {
  33. m_depthStencilID = AZ::RHI::AttachmentId{ AZStd::string::format("DepthStencilID_%llu", GetId()) };
  34. CreateCubeInputAssemblyBuffer();
  35. CreateCubePipeline();
  36. CreateScope();
  37. AZ::RHI::RHISystemNotificationBus::Handler::BusConnect();
  38. AZ::TickBus::Handler::BusConnect();
  39. }
  40. void XRExampleComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  41. {
  42. m_time += deltaTime;
  43. }
  44. void XRExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder)
  45. {
  46. AZ::Matrix4x4 projection = AZ::Matrix4x4::CreateIdentity();
  47. AZ::RPI::XRRenderingInterface* xrSystem = AZ::RPI::RPISystemInterface::Get()->GetXRSystem();
  48. if (xrSystem && xrSystem->ShouldRender())
  49. {
  50. const AZ::RPI::FovData fovData = xrSystem->GetViewFov(m_viewIndex);
  51. const AZ::RPI::PoseData poseData = xrSystem->GetViewPose(m_viewIndex);
  52. static const float clip_near = 0.05f;
  53. static const float clip_far = 100.0f;
  54. projection = xrSystem->CreateProjectionOffset(fovData.m_angleLeft, fovData.m_angleRight,
  55. fovData.m_angleDown, fovData.m_angleUp,
  56. clip_near, clip_far);
  57. AZ::Quaternion poseOrientation = poseData.orientation;
  58. poseOrientation.InvertFast();
  59. AZ::Matrix4x4 viewMat = AZ::Matrix4x4::CreateFromQuaternionAndTranslation(poseOrientation, -poseData.position);
  60. m_viewProjMatrix = projection * viewMat;
  61. const AZ::Matrix4x4 initialScaleMat = AZ::Matrix4x4::CreateScale(AZ::Vector3(0.1f, 0.1f, 0.1f));
  62. //Model matrix for the cube related to the front view
  63. AZ::RPI::PoseData frontViewPoseData = xrSystem->GetViewFrontPose();
  64. m_modelMatrices[0] = AZ::Matrix4x4::CreateFromQuaternionAndTranslation(frontViewPoseData.orientation, frontViewPoseData.position) * initialScaleMat;
  65. //Model matrix for the cube related to the left controller
  66. AZ::RPI::PoseData controllerLeftPose = xrSystem->GetControllerPose(0);
  67. AZ::Matrix4x4 leftScaleMat = initialScaleMat * AZ::Matrix4x4::CreateScale(AZ::Vector3(xrSystem->GetControllerScale(0)));
  68. m_modelMatrices[1] = AZ::Matrix4x4::CreateFromQuaternionAndTranslation(controllerLeftPose.orientation, controllerLeftPose.position) * leftScaleMat;
  69. //Model matrix for the cube related to the right controller
  70. AZ::Matrix4x4 rightScaleMat = initialScaleMat * AZ::Matrix4x4::CreateScale(AZ::Vector3(xrSystem->GetControllerScale(1)));
  71. AZ::RPI::PoseData controllerRightPose = xrSystem->GetControllerPose(1);
  72. m_modelMatrices[2] = AZ::Matrix4x4::CreateFromQuaternionAndTranslation(controllerRightPose.orientation, controllerRightPose.position) * rightScaleMat;
  73. }
  74. for (int i = 0; i < NumberOfCubes; ++i)
  75. {
  76. m_shaderResourceGroups[i]->SetConstant(m_shaderIndexWorldMat, m_modelMatrices[i]);
  77. m_shaderResourceGroups[i]->SetConstant(m_shaderIndexViewProj, m_viewProjMatrix);
  78. m_shaderResourceGroups[i]->Compile();
  79. }
  80. BasicRHIComponent::OnFramePrepare(frameGraphBuilder);
  81. }
  82. XRExampleComponent::SingleCubeBufferData XRExampleComponent::CreateSingleCubeBufferData()
  83. {
  84. const AZStd::fixed_vector<AZ::Color, GeometryVertexCount> vertexColor =
  85. {
  86. //Front Face
  87. AZ::Colors::DarkBlue, AZ::Colors::DarkBlue, AZ::Colors::DarkBlue, AZ::Colors::DarkBlue,
  88. //Back Face
  89. AZ::Colors::Blue, AZ::Colors::Blue, AZ::Colors::Blue, AZ::Colors::Blue,
  90. //Left Face
  91. AZ::Colors::DarkGreen, AZ::Colors::DarkGreen, AZ::Colors::DarkGreen, AZ::Colors::DarkGreen,
  92. //Right Face
  93. AZ::Colors::Green, AZ::Colors::Green, AZ::Colors::Green, AZ::Colors::Green,
  94. //Top Face
  95. AZ::Colors::DarkRed, AZ::Colors::DarkRed, AZ::Colors::DarkRed, AZ::Colors::DarkRed,
  96. //Bottom Face
  97. AZ::Colors::Red, AZ::Colors::Red, AZ::Colors::Red, AZ::Colors::Red,
  98. };
  99. // Create vertices, colors and normals for a cube and a plane
  100. SingleCubeBufferData bufferData;
  101. {
  102. const AZStd::fixed_vector<AZ::Vector3, GeometryVertexCount> vertices =
  103. {
  104. //Front Face
  105. AZ::Vector3(1.0, 1.0, 1.0), AZ::Vector3(-1.0, 1.0, 1.0), AZ::Vector3(-1.0, -1.0, 1.0), AZ::Vector3(1.0, -1.0, 1.0),
  106. //Back Face
  107. AZ::Vector3(1.0, 1.0, -1.0), AZ::Vector3(-1.0, 1.0, -1.0), AZ::Vector3(-1.0, -1.0, -1.0), AZ::Vector3(1.0, -1.0, -1.0),
  108. //Left Face
  109. AZ::Vector3(-1.0, 1.0, 1.0), AZ::Vector3(-1.0, -1.0, 1.0), AZ::Vector3(-1.0, -1.0, -1.0), AZ::Vector3(-1.0, 1.0, -1.0),
  110. //Right Face
  111. AZ::Vector3(1.0, 1.0, 1.0), AZ::Vector3(1.0, -1.0, 1.0), AZ::Vector3(1.0, -1.0, -1.0), AZ::Vector3(1.0, 1.0, -1.0),
  112. //Top Face
  113. AZ::Vector3(1.0, 1.0, 1.0), AZ::Vector3(-1.0, 1.0, 1.0), AZ::Vector3(-1.0, 1.0, -1.0), AZ::Vector3(1.0, 1.0, -1.0),
  114. //Bottom Face
  115. AZ::Vector3(1.0, -1.0, 1.0), AZ::Vector3(-1.0, -1.0, 1.0), AZ::Vector3(-1.0, -1.0, -1.0), AZ::Vector3(1.0, -1.0, -1.0),
  116. };
  117. for (int i = 0; i < GeometryVertexCount; ++i)
  118. {
  119. SetVertexPosition(bufferData.m_positions.data(), i, vertices[i]);
  120. SetVertexColor(bufferData.m_colors.data(), i, vertexColor[i].GetAsVector4());
  121. }
  122. bufferData.m_indices =
  123. {
  124. {
  125. //Back
  126. 2, 0, 1,
  127. 0, 2, 3,
  128. //Front
  129. 4, 6, 5,
  130. 6, 4, 7,
  131. //Left
  132. 8, 10, 9,
  133. 10, 8, 11,
  134. //Right
  135. 14, 12, 13,
  136. 15, 12, 14,
  137. //Top
  138. 16, 18, 17,
  139. 18, 16, 19,
  140. //Bottom
  141. 22, 20, 21,
  142. 23, 20, 22,
  143. }
  144. };
  145. }
  146. return bufferData;
  147. }
  148. void XRExampleComponent::CreateCubeInputAssemblyBuffer()
  149. {
  150. const AZ::RHI::Ptr<AZ::RHI::Device> device = Utils::GetRHIDevice();
  151. AZ::RHI::ResultCode result = AZ::RHI::ResultCode::Success;
  152. m_bufferPool = AZ::RHI::Factory::Get().CreateBufferPool();
  153. AZ::RHI::BufferPoolDescriptor bufferPoolDesc;
  154. bufferPoolDesc.m_bindFlags = AZ::RHI::BufferBindFlags::InputAssembly;
  155. bufferPoolDesc.m_heapMemoryLevel = AZ::RHI::HeapMemoryLevel::Device;
  156. result = m_bufferPool->Init(*device, bufferPoolDesc);
  157. if (result != AZ::RHI::ResultCode::Success)
  158. {
  159. AZ_Error("XRExampleComponent", false, "Failed to initialize buffer pool with error code %d", result);
  160. return;
  161. }
  162. SingleCubeBufferData bufferData = CreateSingleCubeBufferData();
  163. m_inputAssemblyBuffer = AZ::RHI::Factory::Get().CreateBuffer();
  164. AZ::RHI::BufferInitRequest request;
  165. request.m_buffer = m_inputAssemblyBuffer.get();
  166. request.m_descriptor = AZ::RHI::BufferDescriptor{ AZ::RHI::BufferBindFlags::InputAssembly, sizeof(SingleCubeBufferData) };
  167. request.m_initialData = &bufferData;
  168. result = m_bufferPool->InitBuffer(request);
  169. if (result != AZ::RHI::ResultCode::Success)
  170. {
  171. AZ_Error("XRExampleComponent", false, "Failed to initialize buffer with error code %d", result);
  172. return;
  173. }
  174. m_streamBufferViews[0] =
  175. {
  176. *m_inputAssemblyBuffer,
  177. offsetof(SingleCubeBufferData, m_positions),
  178. sizeof(SingleCubeBufferData::m_positions),
  179. sizeof(VertexPosition)
  180. };
  181. m_streamBufferViews[1] =
  182. {
  183. *m_inputAssemblyBuffer,
  184. offsetof(SingleCubeBufferData, m_colors),
  185. sizeof(SingleCubeBufferData::m_colors),
  186. sizeof(VertexColor)
  187. };
  188. m_indexBufferView =
  189. {
  190. *m_inputAssemblyBuffer,
  191. offsetof(SingleCubeBufferData, m_indices),
  192. sizeof(SingleCubeBufferData::m_indices),
  193. AZ::RHI::IndexFormat::Uint16
  194. };
  195. AZ::RHI::InputStreamLayoutBuilder layoutBuilder;
  196. layoutBuilder.SetTopology(AZ::RHI::PrimitiveTopology::TriangleList);
  197. layoutBuilder.AddBuffer()->Channel("POSITION", AZ::RHI::Format::R32G32B32_FLOAT);
  198. layoutBuilder.AddBuffer()->Channel("COLOR", AZ::RHI::Format::R32G32B32A32_FLOAT);
  199. m_streamLayoutDescriptor.Clear();
  200. m_streamLayoutDescriptor = layoutBuilder.End();
  201. AZ::RHI::ValidateStreamBufferViews(m_streamLayoutDescriptor, m_streamBufferViews);
  202. }
  203. void XRExampleComponent::CreateCubePipeline()
  204. {
  205. const char* shaderFilePath = "Shaders/RHI/OpenXrSample.azshader";
  206. const char* sampleName = "XRExampleComponent";
  207. auto shader = LoadShader(shaderFilePath, sampleName);
  208. if (shader == nullptr)
  209. {
  210. return;
  211. }
  212. const AZ::RHI::Ptr<AZ::RHI::Device> device = Utils::GetRHIDevice();
  213. AZ::RHI::PipelineStateDescriptorForDraw pipelineDesc;
  214. shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId).ConfigurePipelineState(pipelineDesc);
  215. pipelineDesc.m_inputStreamLayout = m_streamLayoutDescriptor;
  216. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_enable = 1;
  217. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_func = AZ::RHI::ComparisonFunc::LessEqual;
  218. AZ::RHI::RenderAttachmentLayoutBuilder attachmentsBuilder;
  219. attachmentsBuilder.AddSubpass()
  220. ->RenderTargetAttachment(m_outputFormat)
  221. ->DepthStencilAttachment(device->GetNearestSupportedFormat(AZ::RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil));
  222. [[maybe_unused]] AZ::RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  223. AZ_Assert(result == AZ::RHI::ResultCode::Success, "Failed to create render attachment layout");
  224. m_pipelineState = shader->AcquirePipelineState(pipelineDesc);
  225. if (!m_pipelineState)
  226. {
  227. AZ_Error("XRExampleComponent", false, "Failed to acquire default pipeline state for shader '%s'", shaderFilePath);
  228. return;
  229. }
  230. auto perInstanceSrgLayout = shader->FindShaderResourceGroupLayout(AZ::Name{ "OpenXrSrg" });
  231. if (!perInstanceSrgLayout)
  232. {
  233. AZ_Error("XRExampleComponent", false, "Failed to get shader resource group layout");
  234. return;
  235. }
  236. for (int i = 0; i < NumberOfCubes; ++i)
  237. {
  238. m_shaderResourceGroups[i] = CreateShaderResourceGroup(shader, "OpenXrSrg", sampleName);
  239. }
  240. // Using the first SRG to get the correct index as all the SRGs will have the same indices.
  241. FindShaderInputIndex(&m_shaderIndexWorldMat, m_shaderResourceGroups[0], AZ::Name{ "m_worldMatrix" }, "XRExampleComponent");
  242. FindShaderInputIndex(&m_shaderIndexViewProj, m_shaderResourceGroups[0], AZ::Name{ "m_viewProjMatrix" }, "XRExampleComponent");
  243. }
  244. void XRExampleComponent::CreateScope()
  245. {
  246. // Creates a scope for rendering the triangle.
  247. struct ScopeData
  248. {
  249. };
  250. const auto prepareFunction = [this](AZ::RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  251. {
  252. // Binds the swap chain as a color attachment. Clears it to black.
  253. {
  254. AZ::RHI::ImageScopeAttachmentDescriptor descriptor;
  255. descriptor.m_attachmentId = m_outputAttachmentId;
  256. descriptor.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Load;
  257. frameGraph.UseColorAttachment(descriptor);
  258. }
  259. // Create & Binds DepthStencil image
  260. {
  261. const AZ::RHI::Ptr<AZ::RHI::Device> device = Utils::GetRHIDevice();
  262. const AZ::RHI::ImageDescriptor imageDescriptor = AZ::RHI::ImageDescriptor::Create2D(
  263. AZ::RHI::ImageBindFlags::DepthStencil,
  264. m_outputWidth,
  265. m_outputHeight,
  266. device->GetNearestSupportedFormat(AZ::RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil));
  267. const AZ::RHI::TransientImageDescriptor transientImageDescriptor(m_depthStencilID, imageDescriptor);
  268. frameGraph.GetAttachmentDatabase().CreateTransientImage(transientImageDescriptor);
  269. AZ::RHI::ImageScopeAttachmentDescriptor dsDesc;
  270. dsDesc.m_attachmentId = m_depthStencilID;
  271. dsDesc.m_imageViewDescriptor.m_overrideFormat = device->GetNearestSupportedFormat(AZ::RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil);
  272. dsDesc.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateDepthStencil(1.0f, 0);
  273. dsDesc.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Clear;
  274. dsDesc.m_loadStoreAction.m_loadActionStencil = AZ::RHI::AttachmentLoadAction::DontCare;
  275. frameGraph.UseDepthStencilAttachment(dsDesc, AZ::RHI::ScopeAttachmentAccess::Write);
  276. }
  277. // We will submit NumberOfCubes draw items.
  278. frameGraph.SetEstimatedItemCount(NumberOfCubes);
  279. };
  280. AZ::RHI::EmptyCompileFunction<ScopeData> compileFunction;
  281. const auto executeFunction = [this](const AZ::RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  282. {
  283. AZ::RHI::CommandList* commandList = context.GetCommandList();
  284. // Set persistent viewport and scissor state.
  285. commandList->SetViewports(&m_viewport, 1);
  286. commandList->SetScissors(&m_scissor, 1);
  287. AZ::RHI::DrawIndexed drawIndexed;
  288. drawIndexed.m_indexCount = GeometryIndexCount;
  289. drawIndexed.m_instanceCount = 1;
  290. // Dividing NumberOfCubes by context.GetCommandListCount() to balance to number
  291. // of draw call equally between each thread.
  292. uint32_t numberOfCubesPerCommandList = NumberOfCubes / context.GetCommandListCount();
  293. uint32_t indexStart = context.GetCommandListIndex() * numberOfCubesPerCommandList;
  294. uint32_t indexEnd = indexStart + numberOfCubesPerCommandList;
  295. if (context.GetCommandListIndex() == context.GetCommandListCount() - 1)
  296. {
  297. indexEnd = NumberOfCubes;
  298. }
  299. for (uint32_t i = indexStart; i < indexEnd; ++i)
  300. {
  301. const AZ::RHI::ShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[i]->GetRHIShaderResourceGroup() };
  302. AZ::RHI::DrawItem drawItem;
  303. drawItem.m_arguments = drawIndexed;
  304. drawItem.m_pipelineState = m_pipelineState.get();
  305. drawItem.m_indexBufferView = &m_indexBufferView;
  306. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(AZ::RHI::ArraySize(shaderResourceGroups));
  307. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  308. drawItem.m_streamBufferViewCount = static_cast<uint8_t>(m_streamBufferViews.size());
  309. drawItem.m_streamBufferViews = m_streamBufferViews.data();
  310. commandList->Submit(drawItem);
  311. }
  312. };
  313. m_scopeProducers.emplace_back(
  314. aznew AZ::RHI::ScopeProducerFunction<
  315. ScopeData,
  316. decltype(prepareFunction),
  317. decltype(compileFunction),
  318. decltype(executeFunction)>(
  319. AZ::RHI::ScopeId{ AZStd::string::format("XRSample_Id_%llu", GetId()) },
  320. ScopeData{},
  321. prepareFunction,
  322. compileFunction,
  323. executeFunction));
  324. }
  325. void XRExampleComponent::Deactivate()
  326. {
  327. m_inputAssemblyBuffer = nullptr;
  328. m_bufferPool = nullptr;
  329. m_pipelineState = nullptr;
  330. m_shaderResourceGroups.fill(nullptr);
  331. AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect();
  332. m_windowContext = nullptr;
  333. m_scopeProducers.clear();
  334. }
  335. }