CommonSampleComponentBase.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 <CommonSampleComponentBase.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  13. #include <Atom/RPI.Public/Image/StreamingImage.h>
  14. #include <RHI/BasicRHIComponent.h>
  15. #include <EntityUtilityFunctions.h>
  16. namespace AtomSampleViewer
  17. {
  18. using namespace AZ;
  19. using namespace RPI;
  20. bool CommonSampleComponentBase::ReadInConfig(const ComponentConfig* baseConfig)
  21. {
  22. m_scene = RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  23. auto config = azrtti_cast<const SampleComponentConfig*>(baseConfig);
  24. if (config && config->IsValid())
  25. {
  26. m_cameraEntityId = config->m_cameraEntityId;
  27. m_entityContextId = config->m_entityContextId;
  28. return true;
  29. }
  30. else
  31. {
  32. AZ_Assert(false, "SampleComponentConfig required for sample component configuration.");
  33. return false;
  34. }
  35. }
  36. AzFramework::EntityContextId CommonSampleComponentBase::GetEntityContextId() const
  37. {
  38. return m_entityContextId;
  39. }
  40. AZ::EntityId CommonSampleComponentBase::GetCameraEntityId() const
  41. {
  42. return m_cameraEntityId;
  43. }
  44. AZ::Render::MeshFeatureProcessorInterface* CommonSampleComponentBase::GetMeshFeatureProcessor() const
  45. {
  46. if (!m_meshFeatureProcessor)
  47. {
  48. m_meshFeatureProcessor = Scene::GetFeatureProcessorForEntityContextId<Render::MeshFeatureProcessorInterface>(m_entityContextId);
  49. AZ_Assert(m_meshFeatureProcessor, "MeshFeatureProcessor not available.");
  50. }
  51. return m_meshFeatureProcessor;
  52. }
  53. void CommonSampleComponentBase::InitLightingPresets(bool loadDefaultLightingPresets)
  54. {
  55. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(GetEntityContextId());
  56. AZ_Assert(skyboxFeatureProcessor, "Unable to find SkyBoxFeatureProcessorInterface.");
  57. skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  58. skyboxFeatureProcessor->Enable(true);
  59. // We don't necessarily need an entity but PostProcessFeatureProcessorInterface needs an ID to retrieve ExposureControlSettingsInterface.
  60. AzFramework::EntityContextRequestBus::EventResult(m_postProcessEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity");
  61. AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity.");
  62. m_postProcessEntity->Activate();
  63. if (loadDefaultLightingPresets)
  64. {
  65. AZStd::list<AZ::Data::AssetInfo> lightingAssetInfoList;
  66. AZ::Data::AssetCatalogRequests::AssetEnumerationCB enumerateCB = [&lightingAssetInfoList]([[maybe_unused]] const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info)
  67. {
  68. if (AzFramework::StringFunc::EndsWith(info.m_relativePath.c_str(), ".lightingpreset.azasset"))
  69. {
  70. lightingAssetInfoList.push_front(info);
  71. }
  72. };
  73. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::EnumerateAssets, nullptr, enumerateCB, nullptr);
  74. for (const auto& info : lightingAssetInfoList)
  75. {
  76. AppendLightingPresetsFromAsset(info.m_relativePath);
  77. }
  78. }
  79. // set the initial lighting preset
  80. static const char* InitialLightingPresetName = "Palermo Sidewalk";
  81. for (uint32_t index = 0; index < m_lightingPresets.size(); ++index)
  82. {
  83. if (m_lightingPresets[index].m_displayName == InitialLightingPresetName)
  84. {
  85. m_currentLightingPresetIndex = index;
  86. OnLightingPresetSelected(m_lightingPresets[m_currentLightingPresetIndex], m_useAlternateSkybox);
  87. break;
  88. }
  89. }
  90. AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntityId);
  91. AZ::EntityBus::MultiHandler::BusConnect(m_postProcessEntity->GetId());
  92. }
  93. void CommonSampleComponentBase::ShutdownLightingPresets()
  94. {
  95. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  96. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  97. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  98. {
  99. directionalLightFeatureProcessor->ReleaseLight(handle);
  100. }
  101. m_lightHandles.clear();
  102. ClearLightingPresets();
  103. if (m_postProcessEntity)
  104. {
  105. DestroyEntity(m_postProcessEntity, GetEntityContextId());
  106. }
  107. skyboxFeatureProcessor->Enable(false);
  108. AZ::TransformNotificationBus::MultiHandler::BusDisconnect();
  109. AZ::EntityBus::MultiHandler::BusDisconnect();
  110. }
  111. void CommonSampleComponentBase::LoadLightingPresetsFromAsset(const AZStd::string& assetPath)
  112. {
  113. ClearLightingPresets();
  114. AppendLightingPresetsFromAsset(assetPath);
  115. }
  116. void CommonSampleComponentBase::AppendLightingPresetsFromAsset(const AZStd::string& assetPath)
  117. {
  118. Data::Asset<AnyAsset> asset = AssetUtils::LoadAssetByProductPath<AnyAsset>(assetPath.c_str(), AssetUtils::TraceLevel::Error);
  119. if (asset)
  120. {
  121. const AZ::Render::LightingPreset* preset = asset->GetDataAs<AZ::Render::LightingPreset>();
  122. if (preset)
  123. {
  124. m_lightingPresets.push_back(*preset);
  125. }
  126. m_lightingPresetsDirty = true;
  127. if (!m_lightingPresets.empty() && m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  128. {
  129. m_currentLightingPresetIndex = 0;
  130. OnLightingPresetSelected(m_lightingPresets[0], m_useAlternateSkybox);
  131. }
  132. }
  133. else
  134. {
  135. AZ_Error("Lighting Preset", false, "Lighting preset file failed to load from path: %s.", assetPath.c_str());
  136. }
  137. }
  138. void CommonSampleComponentBase::ClearLightingPresets()
  139. {
  140. m_currentLightingPresetIndex = InvalidLightingPresetIndex;
  141. m_useAlternateSkybox = false;
  142. m_lightingPresets.clear();
  143. m_lightingPresetsDirty = true;
  144. }
  145. void CommonSampleComponentBase::ImGuiLightingPreset()
  146. {
  147. AZ_Assert((m_currentLightingPresetIndex == InvalidLightingPresetIndex) == m_lightingPresets.empty(),
  148. "m_currentLightingPresetIndex should be invalid if and only if no lighting presets are loaded.");
  149. if (m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  150. {
  151. AZ_Warning("Lighting Preset", false, "Lighting presets must be loaded before calling ImGui.");
  152. return;
  153. }
  154. AZStd::string selectedPresetLabel = m_lightingPresets[m_currentLightingPresetIndex].m_displayName;
  155. if (m_useAlternateSkybox)
  156. {
  157. selectedPresetLabel += " (Alt)";
  158. }
  159. // Note that before we were using ScriptableImGui::Combo but there were issues (at least on some systems) when the number of items
  160. // exceeded the max visible item count (which defaults to 8 in ImGui). In this case you'd expect to see a scroll bar in the combo box,
  161. // but the combo box just never popped up. This only happened in profile, not debug builds. It seems to be a bug in ImGui. So by using
  162. // BeginCombo with ImGuiComboFlags_HeightLargest, we just make sure the combo box is always big enough for all the items.
  163. if (ScriptableImGui::BeginCombo("Lighting Preset##SampleBase", selectedPresetLabel.c_str(), ImGuiComboFlags_HeightLargest))
  164. {
  165. for (uint32_t i = 0; i < m_lightingPresets.size(); ++i)
  166. {
  167. AZStd::string& name = m_lightingPresets[i].m_displayName;
  168. AZStd::string nameForAlternateSkybox = name + " (Alt)";
  169. // Each LightingPreset can have an alternate skybox (usually a blurred version of the primary skybox), so we expose both here as separate items in the UI.
  170. bool useThisPresetWithNormalSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && !m_useAlternateSkybox;
  171. bool useThisPresetWithAlternateSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && m_useAlternateSkybox;
  172. useThisPresetWithNormalSkybox = ScriptableImGui::Selectable(name.c_str(), useThisPresetWithNormalSkybox);
  173. useThisPresetWithAlternateSkybox = ScriptableImGui::Selectable(nameForAlternateSkybox.c_str(), useThisPresetWithAlternateSkybox);
  174. if (useThisPresetWithNormalSkybox || useThisPresetWithAlternateSkybox)
  175. {
  176. m_currentLightingPresetIndex = i;
  177. m_useAlternateSkybox = useThisPresetWithAlternateSkybox;
  178. OnLightingPresetSelected(m_lightingPresets[i], m_useAlternateSkybox);
  179. }
  180. }
  181. ScriptableImGui::EndCombo();
  182. }
  183. }
  184. void CommonSampleComponentBase::OnLightingPresetSelected(const AZ::Render::LightingPreset& preset, bool useAlternateSkybox)
  185. {
  186. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  187. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  188. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  189. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  190. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())->GetOrCreateExposureControlSettingsInterface();
  191. Camera::Configuration cameraConfig;
  192. Camera::CameraRequestBus::EventResult(cameraConfig, m_cameraEntityId, &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  193. preset.ApplyLightingPreset(
  194. iblFeatureProcessor,
  195. skyboxFeatureProcessor,
  196. exposureControlSettingInterface,
  197. directionalLightFeatureProcessor,
  198. cameraConfig,
  199. m_lightHandles,
  200. nullptr,
  201. AZ::RPI::MaterialPropertyIndex{},
  202. useAlternateSkybox);
  203. }
  204. void CommonSampleComponentBase::OnTransformChanged(const AZ::Transform&, const AZ::Transform&)
  205. {
  206. const AZ::EntityId* currentBusId = AZ::TransformNotificationBus::GetCurrentBusId();
  207. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  208. if (currentBusId && *currentBusId == m_cameraEntityId && directionalLightFeatureProcessor)
  209. {
  210. auto transform = AZ::Transform::CreateIdentity();
  211. AZ::TransformBus::EventResult(
  212. transform,
  213. m_cameraEntityId,
  214. &AZ::TransformBus::Events::GetWorldTM);
  215. for (const AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  216. {
  217. directionalLightFeatureProcessor->SetCameraTransform(handle, transform);
  218. }
  219. }
  220. }
  221. void CommonSampleComponentBase::OnLightingPresetEntityShutdown(const AZ::EntityId& entityId)
  222. {
  223. if (m_postProcessEntity && m_postProcessEntity->GetId() == entityId)
  224. {
  225. m_postProcessEntity = nullptr;
  226. }
  227. }
  228. void CommonSampleComponentBase::PreloadAssets(const AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo>& assetList)
  229. {
  230. m_isAllAssetsReady = false;
  231. // Configure the imgui progress list widget.
  232. auto onUserCancelledAction = [&]()
  233. {
  234. AZ_TracePrintf(m_sampleName.c_str() , "Cancelled by user.\n");
  235. m_assetLoadManager.Cancel();
  236. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  237. };
  238. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  239. AZStd::for_each(assetList.begin(), assetList.end(),
  240. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  241. m_assetLoadManager.LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  242. {
  243. AZ_Error(m_sampleName.c_str(), success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  244. AZ_TracePrintf(m_sampleName.c_str(), "Asset %s loaded %s. Wait for %zu more assets before full activation\n", assetName.data(), success ? "successfully" : "UNSUCCESSFULLY", pendingAssetCount);
  245. m_imguiProgressList.RemoveItem(assetName);
  246. if (!pendingAssetCount && !m_isAllAssetsReady)
  247. {
  248. m_isAllAssetsReady = true;
  249. OnAllAssetsReadyActivate();
  250. }
  251. });
  252. }
  253. void CommonSampleComponentBase::ResetScene()
  254. {
  255. m_meshFeatureProcessor = nullptr;
  256. }
  257. } // namespace AtomSampleViewer