XRExampleComponent.cpp 18 KB

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