AnimViewportRenderer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 <AzFramework/Entity/GameEntityContextBus.h>
  9. #include <AzFramework/Components/TransformComponent.h>
  10. #include <Integration/ActorComponentBus.h>
  11. #include <Integration/Components/ActorComponent.h>
  12. #include <Atom/RPI.Public/Scene.h>
  13. #include <Atom/RPI.Public/RenderPipeline.h>
  14. #include <Atom/RPI.Public/RPIUtils.h>
  15. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  16. #include <Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h>
  17. #include <Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h>
  18. #include <Atom/Feature/PostProcess/PostProcessFeatureProcessorInterface.h>
  19. #include <Atom/Feature/ImageBasedLights/ImageBasedLightFeatureProcessorInterface.h>
  20. #include <Atom/Feature/Mesh/MeshFeatureProcessorInterface.h>
  21. #include <Atom/Component/DebugCamera/CameraComponent.h>
  22. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  23. #include <AtomLyIntegration/CommonFeatures/Material/MaterialComponentConstants.h>
  24. #include <AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h>
  25. #include <AtomLyIntegration/CommonFeatures/Mesh/MeshComponentConstants.h>
  26. #include <AtomLyIntegration/CommonFeatures/Mesh/MeshComponentBus.h>
  27. #include <AtomLyIntegration/CommonFeatures/PostProcess/PostFxLayerComponentConstants.h>
  28. #include <AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlComponentConstants.h>
  29. #include <AtomLyIntegration/CommonFeatures/ImageBasedLights/ImageBasedLightComponentConstants.h>
  30. #include <EMStudio/AnimViewportRenderer.h>
  31. #include <EMotionFX/Source/EMotionFXManager.h>
  32. #include <EMotionFX/Source/ActorManager.h>
  33. #include <EMotionFX/CommandSystem/Source/CommandManager.h>
  34. #include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h>
  35. #include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h>
  36. namespace EMStudio
  37. {
  38. AnimViewportRenderer::AnimViewportRenderer(AZ::RPI::ViewportContextPtr viewportContext, const RenderOptions* renderOptions)
  39. : m_windowContext(viewportContext->GetWindowContext())
  40. , m_renderOptions(renderOptions)
  41. {
  42. // Create a new entity context
  43. m_entityContext = AZStd::make_unique<AzFramework::EntityContext>();
  44. m_entityContext->InitContext();
  45. // Create the scene
  46. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  47. AZ_Assert(sceneSystem, "Unable to retrieve scene system.");
  48. AZ::Outcome<AZStd::shared_ptr<AzFramework::Scene>, AZStd::string> createSceneOutcome = sceneSystem->CreateScene("AnimViewport");
  49. AZ_Assert(createSceneOutcome, "%s", createSceneOutcome.GetError().data());
  50. m_frameworkScene = createSceneOutcome.TakeValue();
  51. m_frameworkScene->SetSubsystem<AzFramework::EntityContext::SceneStorageType>(m_entityContext.get());
  52. // Create and register a scene with all available feature processors
  53. AZ::RPI::SceneDescriptor sceneDesc;
  54. sceneDesc.m_nameId = AZ::Name("AnimViewport");
  55. m_scene = AZ::RPI::Scene::CreateScene(sceneDesc);
  56. m_scene->EnableAllFeatureProcessors();
  57. // Link our RPI::Scene to the AzFramework::Scene
  58. m_frameworkScene->SetSubsystem(m_scene);
  59. const char* pipelineAssetPath = "passes/MainRenderPipeline.azasset";
  60. AZStd::optional<AZ::RPI::RenderPipelineDescriptor> renderPipelineDesc =
  61. AZ::RPI::GetRenderPipelineDescriptorFromAsset(pipelineAssetPath, AZStd::string::format("_%i", viewportContext->GetId()));
  62. AZ_Assert(renderPipelineDesc.has_value(), "Invalid render pipeline descriptor from asset %s", pipelineAssetPath);
  63. m_renderPipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForWindow(renderPipelineDesc.value(), *m_windowContext.get());
  64. m_scene->AddRenderPipeline(m_renderPipeline);
  65. m_renderPipeline->SetDefaultView(viewportContext->GetDefaultView());
  66. // Currently the scene has to be activated after render pipeline was added so some feature processors (i.e. imgui) can be
  67. // initialized properly with pipeline's pass information.
  68. m_scene->Activate();
  69. AZ::RPI::RPISystemInterface::Get()->RegisterScene(m_scene);
  70. AzFramework::EntityContextId entityContextId = m_entityContext->GetContextId();
  71. // Get the FeatureProcessors
  72. m_meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
  73. // Configure tone mapper
  74. AzFramework::EntityContextRequestBus::EventResult(
  75. m_postProcessEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity");
  76. AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity.");
  77. m_postProcessEntity->CreateComponent(AZ::Render::PostFxLayerComponentTypeId);
  78. m_postProcessEntity->CreateComponent(AZ::Render::ExposureControlComponentTypeId);
  79. m_postProcessEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  80. m_postProcessEntity->Init();
  81. m_postProcessEntity->Activate();
  82. // Init directional light processor
  83. m_directionalLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DirectionalLightFeatureProcessorInterface>();
  84. // Init display mapper processor
  85. m_displayMapperFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DisplayMapperFeatureProcessorInterface>();
  86. // Init Skybox
  87. m_skyboxFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  88. m_skyboxFeatureProcessor->Enable(true);
  89. m_skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  90. // Create IBL
  91. AzFramework::EntityContextRequestBus::EventResult(
  92. m_iblEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "IblEntity");
  93. AZ_Assert(m_iblEntity != nullptr, "Failed to create ibl entity.");
  94. m_iblEntity->CreateComponent(AZ::Render::ImageBasedLightComponentTypeId);
  95. m_iblEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  96. m_iblEntity->Init();
  97. m_iblEntity->Activate();
  98. // Load light preset
  99. AZ::Data::Asset<AZ::RPI::AnyAsset> lightingPresetAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>(
  100. "lightingpresets/default.lightingpreset.azasset", AZ::RPI::AssetUtils::TraceLevel::Warning);
  101. const AZ::Render::LightingPreset* preset = lightingPresetAsset->GetDataAs<AZ::Render::LightingPreset>();
  102. SetLightingPreset(preset);
  103. // Create the ground plane
  104. AzFramework::EntityContextRequestBus::EventResult(
  105. m_groundEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ViewportModel");
  106. AZ_Assert(m_groundEntity != nullptr, "Failed to create model entity.");
  107. m_groundEntity->CreateComponent(AZ::Render::MeshComponentTypeId);
  108. m_groundEntity->CreateComponent(AZ::Render::MaterialComponentTypeId);
  109. m_groundEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  110. m_groundEntity->Init();
  111. m_groundEntity->Activate();
  112. Reinit();
  113. }
  114. AnimViewportRenderer::~AnimViewportRenderer()
  115. {
  116. // Destroy all the entity we created.
  117. m_entityContext->DestroyEntity(m_iblEntity);
  118. m_entityContext->DestroyEntity(m_postProcessEntity);
  119. m_entityContext->DestroyEntity(m_groundEntity);
  120. for (AZ::Entity* entity : m_actorEntities)
  121. {
  122. m_entityContext->DestroyEntity(entity);
  123. }
  124. m_actorEntities.clear();
  125. m_entityContext->DestroyContext();
  126. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  127. {
  128. m_directionalLightFeatureProcessor->ReleaseLight(handle);
  129. }
  130. m_lightHandles.clear();
  131. m_frameworkScene->UnsetSubsystem(m_scene);
  132. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  133. AZ_Assert(sceneSystem, "AtomViewportRenderer was unable to get the scene system during destruction.");
  134. bool removeSuccess = sceneSystem->RemoveScene("AnimViewport");
  135. if (!removeSuccess)
  136. {
  137. AZ_Assert(false, "AtomViewportRenderer should be removed.");
  138. }
  139. AZ::RPI::RPISystemInterface::Get()->UnregisterScene(m_scene);
  140. m_scene = nullptr;
  141. }
  142. void AnimViewportRenderer::Reinit()
  143. {
  144. ReinitActorEntities();
  145. ResetEnvironment();
  146. }
  147. void AnimViewportRenderer::MoveActorEntitiesToOrigin()
  148. {
  149. for (AZ::Entity* entity : m_actorEntities)
  150. {
  151. AZ::TransformBus::Event(entity->GetId(), &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateIdentity());
  152. }
  153. }
  154. AZ::Vector3 AnimViewportRenderer::GetCharacterCenter() const
  155. {
  156. AZ::Vector3 result = AZ::Vector3::CreateZero();
  157. if (!m_actorEntities.empty())
  158. {
  159. // Find the actor instance and calculate the center from aabb.
  160. EMotionFX::Integration::ActorComponent* actorComponent =
  161. m_actorEntities[0]->FindComponent<EMotionFX::Integration::ActorComponent>();
  162. EMotionFX::ActorInstance* actorInstance = actorComponent->GetActorInstance();
  163. if (actorInstance)
  164. {
  165. result = actorInstance->GetAabb().GetCenter();
  166. }
  167. }
  168. return result;
  169. }
  170. void AnimViewportRenderer::UpdateActorRenderFlag(EMotionFX::ActorRenderFlags renderFlags)
  171. {
  172. for (AZ::Entity* entity : m_actorEntities)
  173. {
  174. EMotionFX::Integration::ActorComponent* actorComponent = entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  175. if (!actorComponent)
  176. {
  177. AZ_Assert(false, "Found entity without actor component in the actor entity list.");
  178. continue;
  179. }
  180. actorComponent->SetRenderFlag(renderFlags);
  181. }
  182. }
  183. AZStd::shared_ptr<AzFramework::Scene> AnimViewportRenderer::GetFrameworkScene() const
  184. {
  185. return m_frameworkScene;
  186. }
  187. AZ::EntityId AnimViewportRenderer::GetEntityId() const
  188. {
  189. if (m_actorEntities.empty())
  190. {
  191. return AZ::EntityId();
  192. }
  193. return m_actorEntities[0]->GetId();
  194. }
  195. AzFramework::EntityContextId AnimViewportRenderer::GetEntityContextId() const
  196. {
  197. return m_entityContext->GetContextId();
  198. }
  199. void AnimViewportRenderer::UpdateGroundplane()
  200. {
  201. AZ::Vector3 groundPos;
  202. AZ::TransformBus::EventResult(groundPos, m_groundEntity->GetId(), &AZ::TransformBus::Events::GetWorldTranslation);
  203. const AZ::Vector3 characterPos = GetCharacterCenter();
  204. const float tileOffsetX = AZStd::fmod(characterPos.GetX(), TileSize);
  205. const float tileOffsetY = AZStd::fmod(characterPos.GetY(), TileSize);
  206. const AZ::Vector3 newGroundPos(characterPos.GetX() - tileOffsetX, characterPos.GetY() - tileOffsetY, groundPos.GetZ());
  207. AZ::TransformBus::Event(m_groundEntity->GetId(), &AZ::TransformBus::Events::SetWorldTranslation, newGroundPos);
  208. }
  209. void AnimViewportRenderer::ResetEnvironment()
  210. {
  211. // Reset environment
  212. AZ::Transform iblTransform = AZ::Transform::CreateIdentity();
  213. AZ::TransformBus::Event(m_iblEntity->GetId(), &AZ::TransformBus::Events::SetLocalTM, iblTransform);
  214. const AZ::Matrix4x4 rotationMatrix = AZ::Matrix4x4::CreateIdentity();
  215. auto skyBoxFeatureProcessorInterface = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  216. skyBoxFeatureProcessorInterface->SetCubemapRotationMatrix(rotationMatrix);
  217. // Reset ground entity
  218. AZ::Transform identityTransform = AZ::Transform::CreateIdentity();
  219. AZ::TransformBus::Event(m_groundEntity->GetId(), &AZ::TransformBus::Events::SetLocalTM, identityTransform);
  220. auto modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(
  221. "objects/groudplane/groundplane_512x512m.azmodel", AZ::RPI::AssetUtils::TraceLevel::Assert);
  222. AZ::Render::MeshComponentRequestBus::Event(
  223. m_groundEntity->GetId(), &AZ::Render::MeshComponentRequestBus::Events::SetModelAsset, modelAsset);
  224. // Reset actor position
  225. for (AZ::Entity* entity : m_actorEntities)
  226. {
  227. AZ::TransformBus::Event(entity->GetId(), &AZ::TransformBus::Events::SetLocalTM, identityTransform);
  228. }
  229. }
  230. void AnimViewportRenderer::ReinitActorEntities()
  231. {
  232. // 1. Destroy all the entities that do not point to any actorAsset anymore.
  233. AZStd::set<AZ::Data::AssetId> assetLookup;
  234. AzFramework::EntityContext* entityContext = m_entityContext.get();
  235. const size_t numActors = EMotionFX::GetActorManager().GetNumActors();
  236. for (size_t i = 0; i < numActors; ++i)
  237. {
  238. assetLookup.emplace(EMotionFX::GetActorManager().GetActorAsset(i).GetId());
  239. }
  240. m_actorEntities.erase(
  241. AZStd::remove_if(
  242. m_actorEntities.begin(), m_actorEntities.end(),
  243. [&assetLookup, entityContext](AZ::Entity* entity)
  244. {
  245. EMotionFX::Integration::ActorComponent* actorComponent =
  246. entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  247. if (assetLookup.find(actorComponent->GetActorAsset().GetId()) == assetLookup.end())
  248. {
  249. entityContext->DestroyEntity(entity);
  250. return true;
  251. }
  252. return false;
  253. }),
  254. m_actorEntities.end());
  255. // 2. Create an entity for every actorAsset stored in actor manager.
  256. for (size_t i = 0; i < numActors; ++i)
  257. {
  258. AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset = EMotionFX::GetActorManager().GetActorAsset(i);
  259. if (!actorAsset->IsReady())
  260. {
  261. continue;
  262. }
  263. AZ::Entity* entity = FindActorEntity(actorAsset);
  264. if (!entity)
  265. {
  266. m_actorEntities.emplace_back(CreateActorEntity(actorAsset));
  267. }
  268. }
  269. }
  270. AZ::Entity* AnimViewportRenderer::FindActorEntity(AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset) const
  271. {
  272. const auto foundEntity = AZStd::find_if(
  273. begin(m_actorEntities), end(m_actorEntities),
  274. [match = actorAsset](const AZ::Entity* entity)
  275. {
  276. EMotionFX::Integration::ActorComponent* actorComponent = entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  277. return actorComponent->GetActorAsset() == match;
  278. });
  279. return foundEntity != end(m_actorEntities) ? (*foundEntity) : nullptr;
  280. }
  281. AZ::Entity* AnimViewportRenderer::CreateActorEntity(AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset)
  282. {
  283. AZ::Entity* actorEntity = m_entityContext->CreateEntity(actorAsset->GetActor()->GetName());
  284. actorEntity->CreateComponent(azrtti_typeid<EMotionFX::Integration::ActorComponent>());
  285. actorEntity->CreateComponent(AZ::Render::MaterialComponentTypeId);
  286. actorEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  287. actorEntity->Init();
  288. actorEntity->Activate();
  289. EMotionFX::Integration::ActorComponent* actorComponent = actorEntity->FindComponent<EMotionFX::Integration::ActorComponent>();
  290. actorComponent->SetActorAsset(actorAsset);
  291. // Since this entity belongs to the animation editor, we need to set the isOwnByRuntime flag to false.
  292. actorComponent->GetActorInstance()->SetIsOwnedByRuntime(false);
  293. // Selet the actor instance in the command manager after it has been created.
  294. AZStd::string outResult;
  295. EMStudioManager::GetInstance()->GetCommandManager()->ExecuteCommandInsideCommand(
  296. AZStd::string::format("Select -actorInstanceID %i", actorComponent->GetActorInstance()->GetID()).c_str(), outResult);
  297. return actorEntity;
  298. }
  299. void AnimViewportRenderer::SetLightingPreset(const AZ::Render::LightingPreset* preset)
  300. {
  301. if (!preset)
  302. {
  303. AZ_Warning("AnimViewportRenderer", false, "Attempting to set invalid lighting preset.");
  304. return;
  305. }
  306. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor =
  307. m_scene->GetFeatureProcessor<AZ::Render::ImageBasedLightFeatureProcessorInterface>();
  308. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor =
  309. m_scene->GetFeatureProcessor<AZ::Render::PostProcessFeatureProcessorInterface>();
  310. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface =
  311. postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())
  312. ->GetOrCreateExposureControlSettingsInterface();
  313. Camera::Configuration cameraConfig;
  314. cameraConfig.m_fovRadians = AZ::DegToRad(m_renderOptions->GetFOV());
  315. cameraConfig.m_nearClipDistance = m_renderOptions->GetNearClipPlaneDistance();
  316. cameraConfig.m_farClipDistance = m_renderOptions->GetFarClipPlaneDistance();
  317. cameraConfig.m_frustumWidth = DefaultFrustumDimension;
  318. cameraConfig.m_frustumHeight = DefaultFrustumDimension;
  319. preset->ApplyLightingPreset(
  320. iblFeatureProcessor, m_skyboxFeatureProcessor, exposureControlSettingInterface, m_directionalLightFeatureProcessor,
  321. cameraConfig, m_lightHandles, false);
  322. }
  323. } // namespace EMStudio