AlphaToCoverageExampleComponent.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 <AzCore/Math/MatrixUtils.h>
  9. #include <Atom/RHI/CommandList.h>
  10. #include <Atom/RPI.Public/Shader/Shader.h>
  11. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  12. #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h>
  13. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  14. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <AzCore/std/createdestroy.h>
  17. #include <RHI/AlphaToCoverageExampleComponent.h>
  18. #include <SampleComponentManager.h>
  19. #include <Utils/Utils.h>
  20. namespace AtomSampleViewer
  21. {
  22. namespace AlphaToCoverage
  23. {
  24. const char* SampleName = "AlphaToCoverageExample";
  25. const char* ShaderFilePath = "Shaders/RHI/TexturedSurface.azshader";
  26. const char* TextureFilePath = "TestData/Textures/Foliage_Leaves_0_BaseColor.dds.streamingimage";
  27. }
  28. void AlphaToCoverageExampleComponent::Reflect(AZ::ReflectContext* context)
  29. {
  30. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  31. {
  32. serializeContext->Class<AlphaToCoverageExampleComponent, AZ::Component>()
  33. ->Version(0)
  34. ;
  35. }
  36. }
  37. AlphaToCoverageExampleComponent::AlphaToCoverageExampleComponent()
  38. {
  39. m_supportRHISamplePipeline = true;
  40. }
  41. void AlphaToCoverageExampleComponent::Activate()
  42. {
  43. using namespace AZ;
  44. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  45. m_inputAssemblyBufferPool = aznew RHI::BufferPool();
  46. RHI::BufferPoolDescriptor bufferPoolDesc;
  47. bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly;
  48. bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
  49. m_inputAssemblyBufferPool->Init(RHI::MultiDevice::AllDevices, bufferPoolDesc);
  50. m_depthImageAttachmentId = RHI::AttachmentId("A2C_Depth");
  51. m_multisamleDepthImageAttachmentId = RHI::AttachmentId("A2C_MSAA_Depth");
  52. m_resolveImageAttachmentId = RHI::AttachmentId("A2C_Resolve");
  53. CreateResources();
  54. CreateScopeResources(BlendType::SrcOver);
  55. CreateScopeResources(BlendType::AlphaTest);
  56. CreateScopeResources(BlendType::A2C_MSAA);
  57. // render A2C_MSAA first since it contains resolve
  58. CreateRectangleScopeProducer(BlendType::A2C_MSAA);
  59. CreateRectangleScopeProducer(BlendType::SrcOver);
  60. CreateRectangleScopeProducer(BlendType::AlphaTest);
  61. AZ::TickBus::Handler::BusConnect();
  62. AZ::RHI::RHISystemNotificationBus::Handler::BusConnect();
  63. }
  64. void AlphaToCoverageExampleComponent::Deactivate()
  65. {
  66. m_rectangleInputAssemblyBuffer = nullptr;
  67. m_inputAssemblyBufferPool = nullptr;
  68. m_pipelineStates.fill(nullptr);
  69. AZStd::for_each(m_shaderResourceGroups.begin(), m_shaderResourceGroups.end(), [](auto& srgs)
  70. {
  71. srgs.fill(nullptr);
  72. });
  73. AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect();
  74. m_windowContext = nullptr;
  75. m_scopeProducers.clear();
  76. }
  77. void AlphaToCoverageExampleComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time)
  78. {
  79. AZ_UNUSED(time);
  80. m_time += deltaTime;
  81. }
  82. void AlphaToCoverageExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder)
  83. {
  84. using namespace AZ;
  85. const float baseAngle = fmod(m_time * AZ::Constants::TwoPi / 16, AZ::Constants::TwoPi); // 1 rotate for 16 seconds.
  86. const auto rotate0 = AZ::Matrix4x4::CreateRotationY(-baseAngle);
  87. const auto rotate1 = AZ::Matrix4x4::CreateRotationY(-baseAngle + AZ::Constants::HalfPi);
  88. const float rectHeight = 2 * m_targetDepth * tanf(m_fieldOfView / 2);
  89. const float rectWidth = rectHeight / 3;
  90. const auto scale = AZ::Matrix4x4::CreateScale(AZ::Vector3(rectWidth / 2, rectHeight / 2, rectWidth / 2));
  91. for (int32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  92. {
  93. const auto translate = AZ::Matrix4x4::CreateTranslation(AZ::Vector3((blendIndex - 1) * rectWidth, 0.f, 0.f));
  94. const auto worldMatrix0 = translate * rotate0 * scale;
  95. const auto worldMatrix1 = translate * rotate1 * scale;
  96. auto& srg0 = m_shaderResourceGroups[blendIndex][0];
  97. auto& srg1 = m_shaderResourceGroups[blendIndex][1];
  98. if(srg0)
  99. {
  100. srg0->SetConstant(m_worldMatrixIndex, worldMatrix0);
  101. srg0->Compile();
  102. }
  103. if (srg1)
  104. {
  105. srg1->SetConstant(m_worldMatrixIndex, worldMatrix1);
  106. srg1->Compile();
  107. }
  108. }
  109. BasicRHIComponent::OnFramePrepare(frameGraphBuilder);
  110. }
  111. void AlphaToCoverageExampleComponent::CreateResources()
  112. {
  113. using namespace AZ;
  114. RHI::InputStreamLayoutBuilder layoutBuilder;
  115. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  116. layoutBuilder.AddBuffer()->Channel("UV", RHI::Format::R32G32_FLOAT);
  117. m_rectangleInputStreamLayout = layoutBuilder.End();
  118. RectangleBufferData bufferData;
  119. SetFullScreenRect(bufferData.m_positions.data(), bufferData.m_uvs.data(), bufferData.m_indices.data());
  120. m_rectangleInputAssemblyBuffer = aznew RHI::Buffer();
  121. RHI::ResultCode result = RHI::ResultCode::Success;
  122. RHI::BufferInitRequest request;
  123. request.m_buffer = m_rectangleInputAssemblyBuffer.get();
  124. request.m_descriptor = RHI::BufferDescriptor{RHI::BufferBindFlags::InputAssembly, sizeof(bufferData)};
  125. request.m_initialData = &bufferData;
  126. result = m_inputAssemblyBufferPool->InitBuffer(request);
  127. if (result != RHI::ResultCode::Success)
  128. {
  129. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to initialize position buffer with error code %d", result);
  130. return;
  131. }
  132. m_rectangleStreamBufferViews[0] = {
  133. *m_rectangleInputAssemblyBuffer,
  134. offsetof(RectangleBufferData, m_positions),
  135. sizeof(RectangleBufferData::m_positions),
  136. sizeof(VertexPosition)
  137. };
  138. m_rectangleStreamBufferViews[1] = {
  139. *m_rectangleInputAssemblyBuffer,
  140. offsetof(RectangleBufferData, m_uvs),
  141. sizeof(RectangleBufferData::m_uvs),
  142. sizeof(VertexUV)
  143. };
  144. RHI::ValidateStreamBufferViews(m_rectangleInputStreamLayout, m_rectangleStreamBufferViews);
  145. m_shader = LoadShader(AlphaToCoverage::ShaderFilePath, AlphaToCoverage::SampleName);
  146. if (!m_shader)
  147. {
  148. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to load shader.");
  149. return;
  150. }
  151. for (uint32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  152. {
  153. for (uint32_t rectIndex = 0; rectIndex < s_numRectangles; ++rectIndex)
  154. {
  155. m_shaderResourceGroups[blendIndex][rectIndex] = CreateShaderResourceGroup(m_shader, "TexturedSurfaceSrg", AlphaToCoverage::SampleName);
  156. }
  157. }
  158. m_worldMatrixIndex.Reset();
  159. m_viewProjectionMatrixIndex.Reset();
  160. m_alphaTestRefValueIndex.Reset();
  161. const AZ::Vector3 upVector{0.f, 1.f, 0.f};
  162. const AZ::Vector3 lookAtPos{0.f, 0.f, 0.f};
  163. const float zNear = 0.1f, zFar = 10.f;
  164. const float screenAspect = 1.f;
  165. const AZ::Vector3 eyePosition{0.f, 0.f, m_targetDepth};
  166. Matrix4x4 projectionMatrix;
  167. MakePerspectiveFovMatrixRH(projectionMatrix, m_fieldOfView, screenAspect, zNear, zFar);
  168. const auto viewMatrix = CreateViewMatrix(eyePosition, upVector, lookAtPos);
  169. const auto viewProjectionMatrix = projectionMatrix * viewMatrix;
  170. const Name albedoMapId{"m_albedoMap"};
  171. AZ::RHI::ShaderInputImageIndex albedMapImageIndex;
  172. FindShaderInputIndex(&albedMapImageIndex, m_shaderResourceGroups[0][0], albedoMapId, AlphaToCoverage::SampleName);
  173. auto textureIamge = LoadStreamingImage(AlphaToCoverage::TextureFilePath, AlphaToCoverage::SampleName);
  174. if (!textureIamge)
  175. {
  176. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to load texture image.");
  177. }
  178. constexpr float alphaTestRefValue = 0.1f;
  179. for (uint32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  180. {
  181. float alphaRefValue = blendIndex == static_cast<int32_t>(BlendType::AlphaTest) ? alphaTestRefValue : 0.f;
  182. for (uint32_t rectIndex = 0; rectIndex < s_numRectangles; ++rectIndex)
  183. {
  184. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetImage(albedMapImageIndex, textureIamge))
  185. {
  186. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set image into shader resource group.");
  187. return;
  188. }
  189. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetConstant(m_viewProjectionMatrixIndex, viewProjectionMatrix))
  190. {
  191. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set view projection matrix into shader resource group.");
  192. return;
  193. }
  194. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetConstant(m_alphaTestRefValueIndex, alphaRefValue))
  195. {
  196. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set alpha test reference value into shader resource group.");
  197. return;
  198. }
  199. }
  200. }
  201. }
  202. void AlphaToCoverageExampleComponent::CreateScopeResources(BlendType type)
  203. {
  204. using namespace AZ;
  205. if(!m_shader)
  206. {
  207. return;
  208. }
  209. const bool useDepth = (type == BlendType::AlphaTest) || (type == BlendType::A2C_MSAA);
  210. const bool useResolve = (type == BlendType::A2C_MSAA);
  211. AZ::RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor;
  212. pipelineStateDescriptor.m_inputStreamLayout = m_rectangleInputStreamLayout;
  213. auto shaderVariant = m_shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId);
  214. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  215. RHI::RenderAttachmentLayoutBuilder attachmentsBuilder;
  216. auto* subpass = attachmentsBuilder.AddSubpass();
  217. subpass->RenderTargetAttachment(m_outputFormat, useResolve);
  218. if (useDepth)
  219. {
  220. subpass->DepthStencilAttachment(s_depthFormat);
  221. }
  222. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineStateDescriptor.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  223. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  224. pipelineStateDescriptor.m_renderStates.m_depthStencilState.m_depth.m_enable = useDepth;
  225. pipelineStateDescriptor.m_renderStates.m_depthStencilState.m_depth.m_func = RHI::ComparisonFunc::LessEqual;
  226. pipelineStateDescriptor.m_renderStates.m_multisampleState.m_samples = useResolve ? s_sampleCount : 1;
  227. pipelineStateDescriptor.m_renderStates.m_rasterState.m_cullMode = RHI::CullMode::None;
  228. pipelineStateDescriptor.m_renderStates.m_blendState.m_alphaToCoverageEnable = pipelineStateDescriptor.m_renderStates.m_multisampleState.m_samples > 1;
  229. RHI::TargetBlendState& targetBlendState = pipelineStateDescriptor.m_renderStates.m_blendState.m_targets[0];
  230. if (type == BlendType::SrcOver)
  231. {
  232. targetBlendState.m_enable = true;
  233. targetBlendState.m_blendSource = RHI::BlendFactor::AlphaSource;
  234. targetBlendState.m_blendDest = RHI::BlendFactor::AlphaSourceInverse;
  235. targetBlendState.m_blendOp = RHI::BlendOp::Add;
  236. targetBlendState.m_blendAlphaSource = RHI::BlendFactor::One;
  237. targetBlendState.m_blendAlphaDest = RHI::BlendFactor::AlphaSourceInverse;
  238. targetBlendState.m_blendAlphaOp = RHI::BlendOp::Add;
  239. }
  240. auto& pipeline = m_pipelineStates[static_cast<uint32_t>(type)];
  241. pipeline = m_shader->AcquirePipelineState(pipelineStateDescriptor);
  242. if (!pipeline)
  243. {
  244. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to acquire default pipeline state for shader '%s'", AlphaToCoverage::ShaderFilePath);
  245. return;
  246. }
  247. }
  248. void AlphaToCoverageExampleComponent::CreateRectangleScopeProducer(BlendType type)
  249. {
  250. using namespace AZ;
  251. const uint32_t typeIndex = static_cast<uint32_t>(type);
  252. // Creates a scope for blend type.
  253. const auto prepareFunction = [this, type](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] const ScopeData& scopeData)
  254. {
  255. // Bind the color attachment
  256. {
  257. RHI::ImageScopeAttachmentDescriptor descriptor;
  258. if (type == BlendType::A2C_MSAA)
  259. {
  260. auto colorImageDesc = RHI::ImageDescriptor::Create2D(
  261. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderRead,
  262. m_outputWidth,
  263. m_outputHeight,
  264. m_outputFormat);
  265. colorImageDesc.m_multisampleState = RHI::MultisampleState(s_sampleCount, 0);
  266. frameGraph.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(m_resolveImageAttachmentId, colorImageDesc));
  267. descriptor.m_attachmentId = m_resolveImageAttachmentId;
  268. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  269. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateVector4Float(1.f, 1.f, 1.f, 0.f);
  270. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::DontCare;
  271. }
  272. else
  273. {
  274. descriptor.m_attachmentId = m_outputAttachmentId;
  275. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  276. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  277. }
  278. frameGraph.UseColorAttachment(descriptor);
  279. }
  280. // Bind the depth attachment
  281. if (type == BlendType::AlphaTest || type == BlendType::A2C_MSAA)
  282. {
  283. RHI::AttachmentId depthAttachmentId = (type == BlendType::AlphaTest) ? m_depthImageAttachmentId : m_multisamleDepthImageAttachmentId;
  284. auto depthImageDesc = RHI::ImageDescriptor::Create2D(
  285. RHI::ImageBindFlags::DepthStencil,
  286. m_outputWidth,
  287. m_outputHeight,
  288. s_depthFormat);
  289. depthImageDesc.m_multisampleState.m_samples = (type == BlendType::A2C_MSAA) ? s_sampleCount : 1;
  290. frameGraph.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(depthAttachmentId, depthImageDesc));
  291. RHI::ImageScopeAttachmentDescriptor descriptor;
  292. descriptor.m_attachmentId = depthAttachmentId;
  293. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  294. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateDepth(1.f);
  295. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  296. frameGraph.UseDepthStencilAttachment(
  297. descriptor, RHI::ScopeAttachmentAccess::ReadWrite,
  298. AZ::RHI::ScopeAttachmentStage::EarlyFragmentTest | AZ::RHI::ScopeAttachmentStage::LateFragmentTest);
  299. }
  300. // Bind the resolve attachment
  301. if (type == BlendType::A2C_MSAA)
  302. {
  303. RHI::ResolveScopeAttachmentDescriptor descriptor;
  304. descriptor.m_attachmentId = m_outputAttachmentId;
  305. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::DontCare;
  306. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  307. descriptor.m_resolveAttachmentId = m_resolveImageAttachmentId;
  308. frameGraph.UseResolveAttachment(descriptor);
  309. }
  310. // We will submit two draw item.
  311. frameGraph.SetEstimatedItemCount(2);
  312. };
  313. RHI::EmptyCompileFunction<ScopeData> compileFunction;
  314. const auto executeFunction = [this, typeIndex](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  315. {
  316. RHI::CommandList* commandList = context.GetCommandList();
  317. // Set persistent viewport and scissor state.
  318. commandList->SetViewports(&m_viewport, 1);
  319. commandList->SetScissors(&m_scissor, 1);
  320. RHI::DrawIndexed drawIndexed;
  321. drawIndexed.m_indexCount = 6;
  322. drawIndexed.m_instanceCount = 1;
  323. for (uint32_t rectIndex = context.GetSubmitRange().m_startIndex; rectIndex < context.GetSubmitRange().m_endIndex; ++rectIndex)
  324. {
  325. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[typeIndex][rectIndex]
  326. ->GetRHIShaderResourceGroup()
  327. ->GetDeviceShaderResourceGroup(
  328. context.GetDeviceIndex())
  329. .get() };
  330. RHI::DeviceDrawItem drawItem;
  331. drawItem.m_arguments = drawIndexed;
  332. drawItem.m_pipelineState = m_pipelineStates[typeIndex]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  333. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  334. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  335. const RHI::DeviceIndexBufferView indexBufferView = {
  336. *m_rectangleInputAssemblyBuffer->GetDeviceBuffer(context.GetDeviceIndex()), offsetof(RectangleBufferData, m_indices),
  337. sizeof(RectangleBufferData::m_indices), RHI::IndexFormat::Uint16
  338. };
  339. drawItem.m_indexBufferView = &indexBufferView;
  340. AZStd::array<AZ::RHI::DeviceStreamBufferView, 2> streamBufferViews{
  341. m_rectangleStreamBufferViews[0].GetDeviceStreamBufferView(context.GetDeviceIndex()),
  342. m_rectangleStreamBufferViews[1].GetDeviceStreamBufferView(context.GetDeviceIndex())
  343. };
  344. drawItem.m_streamBufferViewCount = static_cast<uint8_t>(streamBufferViews.size());
  345. drawItem.m_streamBufferViews = streamBufferViews.data();
  346. // Submit the rectangle draw item.
  347. commandList->Submit(drawItem);
  348. }
  349. };
  350. const auto name = AZStd::string::format("BlendType_%d", typeIndex);
  351. const AZ::RHI::ScopeId rectangleScopeId(name);
  352. m_scopeProducers.emplace_back(
  353. aznew RHI::ScopeProducerFunction<
  354. ScopeData,
  355. decltype(prepareFunction),
  356. decltype(compileFunction),
  357. decltype(executeFunction)>(
  358. rectangleScopeId,
  359. ScopeData{},
  360. prepareFunction,
  361. compileFunction,
  362. executeFunction));
  363. }
  364. } // namespace AtomSampleViewer