Subpass_RPI_ExampleComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 <Subpass_RPI_ExampleComponent.h>
  9. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  10. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  11. #include <Atom/RHI/Device.h>
  12. #include <Atom/RHI/Factory.h>
  13. #include <Atom/RPI.Public/View.h>
  14. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  16. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  17. #include <AzCore/Asset/AssetManagerBus.h>
  18. #include <AzCore/Component/Entity.h>
  19. #include <AzCore/IO/IOUtils.h>
  20. #include <AzCore/Serialization/SerializeContext.h>
  21. #include <AzCore/std/smart_ptr/make_shared.h>
  22. #include <AzCore/std/sort.h>
  23. #include <AzFramework/Components/TransformComponent.h>
  24. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  25. #include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  26. #include <SampleComponentManager.h>
  27. #include <SampleComponentConfig.h>
  28. #include <EntityUtilityFunctions.h>
  29. #include <Automation/ScriptableImGui.h>
  30. #include <Automation/ScriptRunnerBus.h>
  31. #include <RHI/BasicRHIComponent.h>
  32. namespace AtomSampleViewer
  33. {
  34. const char* Subpass_RPI_ExampleComponent::CameraControllerNameTable[CameraControllerCount] =
  35. {
  36. "ArcBall",
  37. "NoClip"
  38. };
  39. void Subpass_RPI_ExampleComponent::Reflect(AZ::ReflectContext* context)
  40. {
  41. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  42. {
  43. serializeContext->Class<Subpass_RPI_ExampleComponent, AZ::Component>()
  44. ->Version(0)
  45. ;
  46. }
  47. }
  48. Subpass_RPI_ExampleComponent::Subpass_RPI_ExampleComponent()
  49. {
  50. }
  51. void Subpass_RPI_ExampleComponent::DefaultWindowCreated()
  52. {
  53. AZ::Render::Bootstrap::DefaultWindowBus::BroadcastResult(m_windowContext, &AZ::Render::Bootstrap::DefaultWindowBus::Events::GetDefaultWindowContext);
  54. }
  55. void Subpass_RPI_ExampleComponent::ChangeActivePipeline(AvailablePipelines pipelineOption)
  56. {
  57. if ((pipelineOption == m_activePipelineOption) && (m_activePipeline != nullptr))
  58. {
  59. return;
  60. }
  61. // remove currently running sample pipeline, if any
  62. bool removeOriginalPipeline = true;
  63. if (m_activePipeline)
  64. {
  65. m_scene->RemoveRenderPipeline(m_activePipeline->GetId());
  66. m_activePipeline = nullptr;
  67. removeOriginalPipeline = false;
  68. }
  69. // Create the pipeline.
  70. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  71. pipelineDesc.m_mainViewTagName = "MainCamera";
  72. pipelineDesc.m_materialPipelineTag = "MultiViewPipeline";
  73. pipelineDesc.m_name = "SubpassesPipeline";
  74. pipelineDesc.m_rootPassTemplate = "SubpassesPipelineTemplate";
  75. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 1;
  76. pipelineDesc.m_allowSubpassMerging = pipelineOption == AvailablePipelines::TwoSubpassesPipeline;
  77. m_activePipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext);
  78. AZ_Assert(
  79. m_activePipeline != nullptr, "Failed to create render pipeline with name='%s' and template='%s'.", pipelineDesc.m_name.c_str(),
  80. pipelineDesc.m_rootPassTemplate.c_str());
  81. // Activate the pipeline
  82. m_activePipeline->GetRootPass()->SetEnabled(true); // PassSystem::RemoveRenderPipeline was calling SetEnabled(false)
  83. m_scene->AddRenderPipeline(m_activePipeline);
  84. m_activePipeline->SetDefaultView(m_originalPipeline->GetDefaultView());
  85. if (removeOriginalPipeline)
  86. {
  87. m_scene->RemoveRenderPipeline(m_originalPipeline->GetId());
  88. }
  89. m_activePipelineOption = pipelineOption;
  90. AZ_TracePrintf(
  91. LogName, "New active pipeline is '%s' from template '%s'", pipelineDesc.m_name.c_str(),
  92. pipelineDesc.m_rootPassTemplate.c_str());
  93. }
  94. void Subpass_RPI_ExampleComponent::RestoreOriginalPipeline()
  95. {
  96. if (m_activePipeline)
  97. {
  98. m_scene->RemoveRenderPipeline(m_activePipeline->GetId());
  99. m_activePipeline = nullptr;
  100. }
  101. m_originalPipeline->GetRootPass()->SetEnabled(true); // PassSystem::RemoveRenderPipeline was calling SetEnabled(false)
  102. m_scene->AddRenderPipeline(m_originalPipeline);
  103. }
  104. void Subpass_RPI_ExampleComponent::Activate()
  105. {
  106. UseArcBallCameraController();
  107. InitLightingPresets(true);
  108. ActivateGroundPlane();
  109. ActivateModel();
  110. // Need to connect to this EBus before creating the pipeline because
  111. // we need the window context.
  112. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusConnect();
  113. AzFramework::InputChannelEventListener::BusConnect();
  114. // Save a pointer to the original default pipeline.
  115. m_originalPipeline = m_scene->GetDefaultRenderPipeline();
  116. // Start with our default pipeline
  117. ChangeActivePipeline(m_activePipelineOption);
  118. }
  119. void Subpass_RPI_ExampleComponent::ActivateGroundPlane()
  120. {
  121. // Load the material asset first.
  122. const auto traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  123. auto groundPlaneMaterialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::MaterialAsset>(DefaultPbrMaterialPath, traceLevel);
  124. AZ_Assert(groundPlaneMaterialAsset.GetId().IsValid(), "Invalid material asset from path='%s'", DefaultPbrMaterialPath);
  125. m_groundPlaneModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(DefaultGroundPlaneModelPath, traceLevel);
  126. AZ_Assert(m_groundPlaneModelAsset.GetId().IsValid(), "Invalid ground plane model asset from path='%s'", DefaultGroundPlaneModelPath);
  127. auto meshHandleDescriptor = AZ::Render::MeshHandleDescriptor(m_groundPlaneModelAsset, AZ::RPI::Material::FindOrCreate(groundPlaneMaterialAsset));
  128. m_groundPlandMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(meshHandleDescriptor);
  129. GetMeshFeatureProcessor()->SetTransform(m_groundPlandMeshHandle, AZ::Transform::CreateIdentity());
  130. }
  131. void Subpass_RPI_ExampleComponent::ActivateModel()
  132. {
  133. // Load the material asset first.
  134. const auto traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  135. auto materialAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::MaterialAsset>(DefaultMaterialPath, traceLevel);
  136. AZ_Assert(materialAsset.GetId().IsValid(), "Invalid material asset from path='%s'", DefaultMaterialPath);
  137. m_modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(DefaultModelPath, traceLevel);
  138. AZ_Assert(m_modelAsset.GetId().IsValid(), "Invalid model asset from path='%s'", DefaultModelPath);
  139. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  140. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  141. AZ::Render::MeshHandleDescriptor descriptor(m_modelAsset, AZ::RPI::Material::FindOrCreate(materialAsset));
  142. descriptor.m_modelChangedEventHandler = AZ::Render::MeshHandleDescriptor::ModelChangedEvent::Handler{
  143. [this](const AZ::Data::Instance<AZ::RPI::Model>& /*model*/)
  144. {
  145. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  146. // This handler will be connected to the feature processor so that when the model is updated, the camera
  147. // controller will reset. This ensures the camera is a reasonable distance from the model when it resizes.
  148. ResetCameraController();
  149. UpdateGroundPlane();
  150. }
  151. };
  152. m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(descriptor);
  153. GetMeshFeatureProcessor()->SetTransform(m_meshHandle, AZ::Transform::CreateIdentity());
  154. }
  155. void Subpass_RPI_ExampleComponent::Deactivate()
  156. {
  157. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusDisconnect();
  158. AzFramework::InputChannelEventListener::BusDisconnect();
  159. GetMeshFeatureProcessor()->ReleaseMesh(m_groundPlandMeshHandle);
  160. m_groundPlandMeshHandle = {};
  161. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  162. m_modelAsset = {};
  163. RestoreOriginalPipeline();
  164. RemoveController();
  165. ShutdownLightingPresets();
  166. }
  167. void Subpass_RPI_ExampleComponent::UpdateGroundPlane()
  168. {
  169. if (m_groundPlandMeshHandle.IsValid())
  170. {
  171. AZ::Transform groundPlaneTransform = AZ::Transform::CreateIdentity();
  172. if (m_modelAsset)
  173. {
  174. AZ::Vector3 modelCenter;
  175. float modelRadius;
  176. m_modelAsset->GetAabb().GetAsSphere(modelCenter, modelRadius);
  177. static const float GroundPlaneRelativeScale = 4.0f;
  178. static const float GroundPlaneOffset = 0.01f;
  179. groundPlaneTransform.SetUniformScale(GroundPlaneRelativeScale * modelRadius);
  180. groundPlaneTransform.SetTranslation(AZ::Vector3(0.0f, 0.0f, m_modelAsset->GetAabb().GetMin().GetZ() - GroundPlaneOffset));
  181. }
  182. GetMeshFeatureProcessor()->SetTransform(m_groundPlandMeshHandle, groundPlaneTransform);
  183. }
  184. }
  185. void Subpass_RPI_ExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  186. {
  187. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  188. }
  189. // AzFramework::InputChannelEventListener
  190. bool Subpass_RPI_ExampleComponent::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel)
  191. {
  192. const auto& inputDevice = inputChannel.GetInputDevice();
  193. if (!AzFramework::InputDeviceKeyboard::IsKeyboardDevice(inputDevice.GetInputDeviceId()))
  194. {
  195. return false;
  196. }
  197. const AzFramework::InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
  198. switch (inputChannel.GetState())
  199. {
  200. case AzFramework::InputChannel::State::Ended:
  201. {
  202. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Alphanumeric1)
  203. {
  204. ChangeActivePipeline(AvailablePipelines::TwoSubpassesPipeline);
  205. }
  206. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Alphanumeric2)
  207. {
  208. ChangeActivePipeline(AvailablePipelines::TwoPassesPipeline);
  209. }
  210. else
  211. {
  212. AZ_TracePrintf(LogName, "Invalid Key=%s. Only '1' or '2' are supported\n", inputChannelId.GetName());
  213. }
  214. break;
  215. }
  216. default:
  217. {
  218. break;
  219. }
  220. }
  221. return false;
  222. }
  223. void Subpass_RPI_ExampleComponent::UseArcBallCameraController()
  224. {
  225. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  226. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  227. }
  228. void Subpass_RPI_ExampleComponent::UseNoClipCameraController()
  229. {
  230. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  231. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  232. }
  233. void Subpass_RPI_ExampleComponent::RemoveController()
  234. {
  235. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  236. }
  237. void Subpass_RPI_ExampleComponent::SetArcBallControllerParams()
  238. {
  239. if (!m_modelAsset.IsReady())
  240. {
  241. return;
  242. }
  243. // Adjust the arc-ball controller so that it has bounds that make sense for the current model
  244. AZ::Vector3 center;
  245. float radius;
  246. m_modelAsset->GetAabb().GetAsSphere(center, radius);
  247. const float startingDistance = radius * ArcballRadiusDefaultModifier;
  248. const float minDistance = radius * ArcballRadiusMinModifier;
  249. const float maxDistance = radius * ArcballRadiusMaxModifier;
  250. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  251. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, startingDistance);
  252. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMinDistance, minDistance);
  253. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, maxDistance);
  254. }
  255. void Subpass_RPI_ExampleComponent::ResetCameraController()
  256. {
  257. RemoveController();
  258. if (m_currentCameraControllerType == CameraControllerType::ArcBall)
  259. {
  260. UseArcBallCameraController();
  261. SetArcBallControllerParams();
  262. }
  263. else if (m_currentCameraControllerType == CameraControllerType::NoClip)
  264. {
  265. UseNoClipCameraController();
  266. }
  267. }
  268. } // namespace AtomSampleViewer