BloomExampleComponent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 <BloomExampleComponent.h>
  9. #include <AzCore/Component/Entity.h>
  10. #include <AzCore/IO/Path/Path.h>
  11. #include <AzFramework/Components/TransformComponent.h>
  12. #include <AzFramework/Entity/EntityContextBus.h>
  13. #include <SampleComponentManager.h>
  14. #include <SampleComponentConfig.h>
  15. #include <EntityUtilityFunctions.h>
  16. #include <Atom/Feature/Utils/FrameCaptureBus.h>
  17. #include <Atom/RHI/DrawPacketBuilder.h>
  18. #include <Atom/RPI.Public/RPISystemInterface.h>
  19. #include <Atom/RPI.Public/Shader/Shader.h>
  20. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  21. #include <RHI/BasicRHIComponent.h>
  22. namespace AtomSampleViewer
  23. {
  24. using namespace AZ;
  25. void BloomExampleComponent::Reflect(AZ::ReflectContext* context)
  26. {
  27. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  28. {
  29. serializeContext->Class<BloomExampleComponent, AZ::Component>()
  30. ->Version(0)
  31. ;
  32. }
  33. }
  34. BloomExampleComponent::BloomExampleComponent()
  35. : m_imageBrowser("@user@/BloomExampleComponent/image_browser.xml")
  36. {
  37. }
  38. void BloomExampleComponent::Activate()
  39. {
  40. m_dynamicDraw = RPI::GetDynamicDraw();
  41. m_postProcessFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::PostProcessFeatureProcessorInterface>();
  42. CreateBloomEntity();
  43. m_imguiSidebar.Activate();
  44. AZ::TickBus::Handler::BusConnect();
  45. PrepareRenderData();
  46. m_imageBrowser.SetFilter([this](const AZ::Data::AssetInfo& assetInfo)
  47. {
  48. if (!AzFramework::StringFunc::Path::IsExtension(assetInfo.m_relativePath.c_str(), "streamingimage"))
  49. {
  50. return false;
  51. }
  52. AZStd::string assetPath(assetInfo.m_relativePath);
  53. if (!AzFramework::StringFunc::Path::Normalize(assetPath))
  54. {
  55. return false;
  56. }
  57. if (!Utils::IsFileUnderFolder(assetPath, InputImageFolder))
  58. {
  59. return false;
  60. }
  61. return true;
  62. });
  63. m_imageBrowser.Activate();
  64. // Load a default image
  65. QueueAssetPathForLoad("textures/tonemapping/hdr_test_pattern.exr.streamingimage");
  66. Data::Asset<RPI::AnyAsset> displayMapperAsset = RPI::AssetUtils::LoadAssetByProductPath<RPI::AnyAsset>("passes/DisplayMapperConfiguration.azasset", RPI::AssetUtils::TraceLevel::Error);
  67. const Render::DisplayMapperConfigurationDescriptor* displayMapperConfigurationDescriptor = RPI::GetDataFromAnyAsset<Render::DisplayMapperConfigurationDescriptor>(displayMapperAsset);
  68. if (displayMapperConfigurationDescriptor == nullptr)
  69. {
  70. AZ_Error("DisplayMapperPass", false, "Failed to load display mapper configuration file.");
  71. return;
  72. }
  73. m_displayMapperConfiguration = *displayMapperConfigurationDescriptor;
  74. }
  75. void BloomExampleComponent::Deactivate()
  76. {
  77. AZ::TickBus::Handler::BusDisconnect();
  78. AZ::EntityBus::MultiHandler::BusDisconnect();
  79. if (m_bloomEntity)
  80. {
  81. DestroyEntity(m_bloomEntity, GetEntityContextId());
  82. m_postProcessFeatureProcessor = nullptr;
  83. }
  84. m_imguiSidebar.Deactivate();
  85. m_imageBrowser.Deactivate();
  86. }
  87. void BloomExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  88. {
  89. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  90. if (m_bloomEntity && m_bloomEntity->GetId() == entityId)
  91. {
  92. m_postProcessFeatureProcessor->RemoveSettingsInterface(m_bloomEntity->GetId());
  93. m_bloomEntity = nullptr;
  94. }
  95. else
  96. {
  97. AZ_Assert(false, "unexpected entity destruction is signaled.");
  98. }
  99. }
  100. void BloomExampleComponent::OnTick([[maybe_unused]] float deltaTime, AZ::ScriptTimePoint)
  101. {
  102. if (m_drawImage.m_image && !m_drawImage.m_wasStreamed)
  103. {
  104. m_drawImage.m_wasStreamed = m_drawImage.m_image->GetResidentMipLevel() == 0;
  105. m_drawImage.m_srg->Compile();
  106. }
  107. DrawSidebar();
  108. DrawImage(&m_drawImage);
  109. }
  110. void BloomExampleComponent::DrawSidebar()
  111. {
  112. using namespace AZ::Render;
  113. const char* items[] = { "White", "Red", "Green", "Blue" };
  114. static int item_current0 = 0;
  115. static int item_current1 = 0;
  116. static int item_current2 = 0;
  117. static int item_current3 = 0;
  118. static int item_current4 = 0;
  119. auto ColorPicker = [](int index)->Vector3 {
  120. switch (index)
  121. {
  122. case 0: return Vector3(1.0, 1.0, 1.0); break;
  123. case 1: return Vector3(1.0, 0.5, 0.5); break;
  124. case 2: return Vector3(0.5, 1.0, 0.5); break;
  125. case 3: return Vector3(0.5, 0.5, 1.0); break;
  126. default: return Vector3(1.0, 1.0, 1.0);
  127. }
  128. };
  129. if (!m_imguiSidebar.Begin())
  130. {
  131. return;
  132. }
  133. ImGui::Spacing();
  134. bool enabled = m_bloomSettings->GetEnabled();
  135. if (ImGui::Checkbox("Enable", &enabled) || m_isInitParameters)
  136. {
  137. m_bloomSettings->SetEnabled(enabled);
  138. m_bloomSettings->OnConfigChanged();
  139. }
  140. ImGui::Spacing();
  141. float threshold = m_bloomSettings->GetThreshold();
  142. if (ImGui::SliderFloat("Threshold", &threshold, 0.0f, 20.0f, "%0.1f") || !m_isInitParameters)
  143. {
  144. m_bloomSettings->SetThreshold(threshold);
  145. m_bloomSettings->OnConfigChanged();
  146. }
  147. float knee = m_bloomSettings->GetKnee();
  148. if (ImGui::SliderFloat("Knee", &knee, 0.0f, 1.0f) || m_isInitParameters)
  149. {
  150. m_bloomSettings->SetKnee(knee);
  151. m_bloomSettings->OnConfigChanged();
  152. }
  153. ImGui::Spacing();
  154. float sizeScale = m_bloomSettings->GetKernelSizeScale();
  155. if (ImGui::SliderFloat("KernelSizeScale", &sizeScale, 0.0f, 2.0f) || m_isInitParameters)
  156. {
  157. m_bloomSettings->SetKernelSizeScale(sizeScale);
  158. m_bloomSettings->OnConfigChanged();
  159. }
  160. if (ImGui::CollapsingHeader("KernelSize", ImGuiTreeNodeFlags_DefaultOpen))
  161. {
  162. ImGui::Indent();
  163. float kernelSize0 = m_bloomSettings->GetKernelSizeStage0();
  164. if (ImGui::SliderFloat("Size0", &kernelSize0, 0.0f, 1.0f) || m_isInitParameters)
  165. {
  166. m_bloomSettings->SetKernelSizeStage0(kernelSize0);
  167. m_bloomSettings->OnConfigChanged();
  168. }
  169. float kernelSize1 = m_bloomSettings->GetKernelSizeStage1();
  170. if (ImGui::SliderFloat("Size1", &kernelSize1, 0.0f, 1.0f) || m_isInitParameters)
  171. {
  172. m_bloomSettings->SetKernelSizeStage1(kernelSize1);
  173. m_bloomSettings->OnConfigChanged();
  174. }
  175. float kernelSize2 = m_bloomSettings->GetKernelSizeStage2();
  176. if (ImGui::SliderFloat("Size2", &kernelSize2, 0.0f, 1.0f) || m_isInitParameters)
  177. {
  178. m_bloomSettings->SetKernelSizeStage2(kernelSize2);
  179. m_bloomSettings->OnConfigChanged();
  180. }
  181. float kernelSize3 = m_bloomSettings->GetKernelSizeStage3();
  182. if (ImGui::SliderFloat("Size3", &kernelSize3, 0.0f, 1.0f) || m_isInitParameters)
  183. {
  184. m_bloomSettings->SetKernelSizeStage3(kernelSize3);
  185. m_bloomSettings->OnConfigChanged();
  186. }
  187. float kernelSize4 = m_bloomSettings->GetKernelSizeStage4();
  188. if (ImGui::SliderFloat("Size4", &kernelSize4, 0.0f, 1.0f) || m_isInitParameters)
  189. {
  190. m_bloomSettings->SetKernelSizeStage4(kernelSize4);
  191. m_bloomSettings->OnConfigChanged();
  192. }
  193. ImGui::Unindent();
  194. }
  195. ImGui::Spacing();
  196. float intensity = m_bloomSettings->GetIntensity();
  197. if (ImGui::SliderFloat("Intensity", &intensity, 0.0f, 1.0f) || m_isInitParameters)
  198. {
  199. m_bloomSettings->SetIntensity(intensity);
  200. m_bloomSettings->OnConfigChanged();
  201. }
  202. if (ImGui::CollapsingHeader("Tint", ImGuiTreeNodeFlags_DefaultOpen))
  203. {
  204. ImGui::Indent();
  205. if (ImGui::ListBox("Tint0", &item_current0, items, IM_ARRAYSIZE(items), 4) || m_isInitParameters)
  206. {
  207. m_bloomSettings->SetTintStage0(ColorPicker(item_current0));
  208. m_bloomSettings->OnConfigChanged();
  209. }
  210. if (ImGui::ListBox("Tint1", &item_current1, items, IM_ARRAYSIZE(items), 4) || m_isInitParameters)
  211. {
  212. m_bloomSettings->SetTintStage1(ColorPicker(item_current1));
  213. m_bloomSettings->OnConfigChanged();
  214. }
  215. if (ImGui::ListBox("Tint2", &item_current2, items, IM_ARRAYSIZE(items), 4) || m_isInitParameters)
  216. {
  217. m_bloomSettings->SetTintStage2(ColorPicker(item_current2));
  218. m_bloomSettings->OnConfigChanged();
  219. }
  220. if (ImGui::ListBox("Tint3", &item_current3, items, IM_ARRAYSIZE(items), 4) || m_isInitParameters)
  221. {
  222. m_bloomSettings->SetTintStage3(ColorPicker(item_current3));
  223. m_bloomSettings->OnConfigChanged();
  224. }
  225. if (ImGui::ListBox("Tint4", &item_current4, items, IM_ARRAYSIZE(items), 4) || m_isInitParameters)
  226. {
  227. m_bloomSettings->SetTintStage4(ColorPicker(item_current4));
  228. m_bloomSettings->OnConfigChanged();
  229. }
  230. ImGui::Unindent();
  231. }
  232. ImGui::Spacing();
  233. bool bicubicEnabled = m_bloomSettings->GetBicubicEnabled();
  234. if (ImGui::Checkbox("Bicubic upsampling", &bicubicEnabled) || m_isInitParameters)
  235. {
  236. m_bloomSettings->SetBicubicEnabled(bicubicEnabled);
  237. m_bloomSettings->OnConfigChanged();
  238. }
  239. m_imguiSidebar.End();
  240. }
  241. void BloomExampleComponent::PrepareRenderData()
  242. {
  243. const auto CreatePipeline = [](const char* shaderFilepath,
  244. const char* srgName,
  245. Data::Asset<AZ::RPI::ShaderAsset>& shaderAsset,
  246. RHI::Ptr<AZ::RHI::ShaderResourceGroupLayout>& srgLayout,
  247. RHI::ConstPtr<RHI::PipelineState>& pipelineState,
  248. RHI::DrawListTag& drawListTag,
  249. RPI::Scene* scene)
  250. {
  251. // Since the shader is using SV_VertexID and SV_InstanceID as VS input, we won't need to have vertex buffer.
  252. // Also, the index buffer is not needed with DrawLinear.
  253. RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor;
  254. shaderAsset = RPI::AssetUtils::LoadAssetByProductPath<RPI::ShaderAsset>(shaderFilepath, RPI::AssetUtils::TraceLevel::Error);
  255. Data::Instance<RPI::Shader> shader = RPI::Shader::FindOrCreate(shaderAsset);
  256. if (!shader)
  257. {
  258. AZ_Error("Render", false, "Failed to find or create shader instance from shader asset with path %s", shaderFilepath);
  259. return;
  260. }
  261. const RPI::ShaderVariant& shaderVariant = shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId);
  262. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  263. drawListTag = shader->GetDrawListTag();
  264. scene->ConfigurePipelineState(shader->GetDrawListTag(), pipelineStateDescriptor);
  265. pipelineStateDescriptor.m_inputStreamLayout.SetTopology(AZ::RHI::PrimitiveTopology::TriangleStrip);
  266. pipelineStateDescriptor.m_inputStreamLayout.Finalize();
  267. pipelineState = shader->AcquirePipelineState(pipelineStateDescriptor);
  268. if (!pipelineState)
  269. {
  270. AZ_Error("Render", false, "Failed to acquire default pipeline state for shader %s", shaderFilepath);
  271. }
  272. // Load shader resource group layout
  273. srgLayout = shaderAsset->FindShaderResourceGroupLayout(AZ::Name(srgName));
  274. };
  275. // Create the example's main pipeline object
  276. {
  277. CreatePipeline("Shaders/tonemappingexample/renderimage.azshader", "RenderImageSrg", m_shaderAsset, m_srgLayout, m_pipelineState, m_drawListTag, m_scene);
  278. // Set the input indices
  279. m_imageInputIndex.Reset();
  280. m_positionInputIndex.Reset();
  281. m_sizeInputIndex.Reset();
  282. m_colorSpaceIndex.Reset();
  283. }
  284. m_drawImage.m_srg = RPI::ShaderResourceGroup::Create(m_shaderAsset, m_srgLayout->GetName());
  285. m_drawImage.m_wasStreamed = false;
  286. // Set the image to occupy the full screen.
  287. // The window's left bottom is (-1, -1). The window size is (2, 2)
  288. AZStd::array<float, 2> position, size;
  289. position[0] = -1.f;
  290. position[1] = -1.f;
  291. size[0] = 2.0f;
  292. size[1] = 2.0f;
  293. m_drawImage.m_srg->SetConstant(m_positionInputIndex, position);
  294. m_drawImage.m_srg->SetConstant(m_sizeInputIndex, size);
  295. m_drawImage.m_srg->SetConstant<int>(m_colorSpaceIndex, static_cast<int>(m_inputColorSpace));
  296. }
  297. void BloomExampleComponent::DrawImage(const ImageToDraw* imageInfo)
  298. {
  299. // Build draw packet
  300. RHI::DrawPacketBuilder drawPacketBuilder{RHI::MultiDevice::DefaultDevice};
  301. drawPacketBuilder.Begin(nullptr);
  302. m_geometryView.SetDrawArguments(RHI::DrawLinear(4, 0));
  303. drawPacketBuilder.SetGeometryView(&m_geometryView);
  304. RHI::DrawPacketBuilder::DrawRequest drawRequest;
  305. drawRequest.m_listTag = m_drawListTag;
  306. drawRequest.m_pipelineState = m_pipelineState.get();
  307. drawRequest.m_sortKey = 0;
  308. drawRequest.m_uniqueShaderResourceGroup = imageInfo->m_srg->GetRHIShaderResourceGroup();
  309. drawPacketBuilder.AddDrawItem(drawRequest);
  310. // Submit draw packet
  311. auto drawPacket{drawPacketBuilder.End()};
  312. m_dynamicDraw->AddDrawPacket(m_scene, AZStd::move(drawPacket));
  313. }
  314. RPI::ColorSpaceId BloomExampleComponent::GetColorSpaceIdForIndex(uint8_t colorSpaceIndex) const
  315. {
  316. const AZStd::vector<AZ::RPI::ColorSpaceId> colorSpaces =
  317. {
  318. RPI::ColorSpaceId::SRGB,
  319. RPI::ColorSpaceId::LinearSRGB,
  320. RPI::ColorSpaceId::ACEScg,
  321. RPI::ColorSpaceId::ACES2065
  322. };
  323. if (colorSpaceIndex >= colorSpaces.size())
  324. {
  325. AZ_Assert(false, "Invalid colorSpaceIndex");
  326. return RPI::ColorSpaceId::SRGB;
  327. }
  328. return colorSpaces[colorSpaceIndex];
  329. }
  330. void BloomExampleComponent::CreateBloomEntity()
  331. {
  332. m_bloomEntity = CreateEntity("Bloom", GetEntityContextId());
  333. // Bloom
  334. auto* bloomSettings = m_postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_bloomEntity->GetId());
  335. m_bloomSettings = bloomSettings->GetOrCreateBloomSettingsInterface();
  336. m_bloomSettings->SetEnabled(false);
  337. m_bloomEntity->Activate();
  338. AZ::EntityBus::MultiHandler::BusConnect(m_bloomEntity->GetId());
  339. }
  340. void BloomExampleComponent::QueueAssetPathForLoad(const AZStd::string& filePath)
  341. {
  342. AZ::Data::AssetId imageAssetId;
  343. AZ::Data::AssetCatalogRequestBus::BroadcastResult(
  344. imageAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, filePath.c_str(),
  345. azrtti_typeid <AZ::RPI::StreamingImageAsset>(), false);
  346. AZ_Assert(imageAssetId.IsValid(), "Unable to load file %s", filePath.c_str());
  347. QueueAssetIdForLoad(imageAssetId);
  348. }
  349. void BloomExampleComponent::QueueAssetIdForLoad(const AZ::Data::AssetId& imageAssetId)
  350. {
  351. if (imageAssetId.IsValid())
  352. {
  353. Data::Asset<AZ::RPI::StreamingImageAsset> imageAsset;
  354. if (!imageAsset.Create(imageAssetId))
  355. {
  356. auto assetId = imageAssetId.ToString<AZStd::string>();
  357. AZ_Assert(false, "Unable to create image asset for asset ID %s", assetId.c_str());
  358. return;
  359. }
  360. auto image = AZ::RPI::StreamingImage::FindOrCreate(imageAsset);
  361. if (image == nullptr)
  362. {
  363. auto imageAssetName = imageAssetId.ToString<AZStd::string>();
  364. AZ_Assert(false, "Failed to find or create an image instance from image asset %s", imageAssetName.c_str());
  365. return;
  366. }
  367. m_drawImage.m_assetId = imageAssetId;
  368. m_drawImage.m_image = image;
  369. m_drawImage.m_wasStreamed = false;
  370. m_drawImage.m_srg->SetImage(m_imageInputIndex, m_drawImage.m_image);
  371. }
  372. }
  373. } // namespace AtomSampleViewer