From 3c50fdc671b1d1e1ef562b3a0b2f1a3840ac81a0 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 7 Oct 2021 11:58:01 -0500 Subject: [PATCH 01/52] =?UTF-8?q?First=20phase=20of=20refactoring=20atom?= =?UTF-8?q?=20thumbnail=20and=20preview=20rendering=20into=20a=20reusable?= =?UTF-8?q?=20system=20that=20can=20be=20used=20for=20additional=20thumbna?= =?UTF-8?q?il=20types=20and=20capturing=20preview=20images=20for=20other?= =?UTF-8?q?=20purposes.=20=20Our=20=E2=80=A2=20Removed=20classes=20for=20i?= =?UTF-8?q?nitialization=20and=20teardown=20steps=20of=20the=20renderer=20?= =?UTF-8?q?=E2=80=A2=20Moved=20initialization=20and=20teardown=20logic=20b?= =?UTF-8?q?ack=20to=20the=20renderer=20constructor=20and=20destructor=20?= =?UTF-8?q?=E2=80=A2=20Combined=20thumbnail=20render=20context=20and=20dat?= =?UTF-8?q?a=20with=20the=20main=20renderer=20class=20=E2=80=A2=20Made=20a?= =?UTF-8?q?ll=20render=20data=20private=20and=20instead=20implemented=20a?= =?UTF-8?q?=20public=20interface=20=E2=80=A2=20Remaining=20steps=20were=20?= =?UTF-8?q?simplified=20and=20updated=20to=20work=20directly=20with=20the?= =?UTF-8?q?=20new=20public=20interface=20=E2=80=A2=20Changed=20the=20waiti?= =?UTF-8?q?ng=20for=20assets=20to=20load=20state=20to=20poll=20asset=20sta?= =?UTF-8?q?tus=20on=20tick=20because=20we=20were=20timing=20out=20there=20?= =?UTF-8?q?anyway=20=E2=80=A2=20Unified=20redundant=20camera=20configurati?= =?UTF-8?q?on=20variables=20and=20made=20sure=20they=20were=20used=20consi?= =?UTF-8?q?stently=20when=20initializing=20and=20updating=20the=20scene=20?= =?UTF-8?q?and=20camera=20=E2=80=A2=20Changed=20interface=20for=20custom?= =?UTF-8?q?=20feature=20processor=20request=20API=20to=20build=20a=20set?= =?UTF-8?q?=20instead=20of=20returning=20a=20vector=20=E2=80=A2=20Moved=20?= =?UTF-8?q?initialization=20of=20the=20thumbnail=20renderer=20and=20previe?= =?UTF-8?q?w=20factory=20after=20asset=20catalog=20has=20loaded?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Guthrie Adams --- .../ThumbnailFeatureProcessorProviderBus.h | 2 +- .../EditorCommonFeaturesSystemComponent.cpp | 12 +- .../EditorCommonFeaturesSystemComponent.h | 4 + .../Rendering/CommonThumbnailRenderer.cpp | 392 +++++++++++++++--- .../Rendering/CommonThumbnailRenderer.h | 104 ++++- .../Rendering/ThumbnailRendererContext.h | 42 -- .../Rendering/ThumbnailRendererData.h | 70 ---- .../ThumbnailRendererSteps/CaptureStep.cpp | 97 +---- .../ThumbnailRendererSteps/CaptureStep.h | 11 +- .../FindThumbnailToRenderStep.cpp | 48 +-- .../FindThumbnailToRenderStep.h | 4 +- .../ThumbnailRendererSteps/InitializeStep.cpp | 191 --------- .../ThumbnailRendererSteps/InitializeStep.h | 37 -- .../ReleaseResourcesStep.cpp | 57 --- .../ReleaseResourcesStep.h | 30 -- .../ThumbnailRendererStep.h | 6 +- .../WaitForAssetsToLoadStep.cpp | 74 +--- .../WaitForAssetsToLoadStep.h | 16 +- ...egration_commonfeatures_editor_files.cmake | 6 - 19 files changed, 466 insertions(+), 737 deletions(-) delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererContext.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererData.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h index 8030c3ae05..a4d76809ba 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h @@ -24,7 +24,7 @@ namespace AZ { public: //! Get a list of custom feature processors to register with thumbnail renderer - virtual const AZStd::vector& GetCustomFeatureProcessors() const = 0; + virtual void GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; }; using ThumbnailFeatureProcessorProviderBus = AZ::EBus; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 896e88f4e2..8be947ae26 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -82,12 +82,11 @@ namespace AZ void EditorCommonFeaturesSystemComponent::Activate() { - m_renderer = AZStd::make_unique(); - m_previewerFactory = AZStd::make_unique (); m_skinnedMeshDebugDisplay = AZStd::make_unique(); AzToolsFramework::EditorLevelNotificationBus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusConnect(); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); } @@ -95,6 +94,7 @@ namespace AZ { AzToolsFramework::EditorLevelNotificationBus::Handler::BusDisconnect(); AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); + AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusDisconnect(); m_skinnedMeshDebugDisplay.reset(); @@ -191,6 +191,14 @@ namespace AZ } } + void EditorCommonFeaturesSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) + { + AZ::TickBus::QueueFunction([this](){ + m_renderer = AZStd::make_unique(); + m_previewerFactory = AZStd::make_unique(); + }); + } + const AzToolsFramework::AssetBrowser::PreviewerFactory* EditorCommonFeaturesSystemComponent::GetPreviewerFactory( const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h index 2560bf7e11..d26886c4ae 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h @@ -28,6 +28,7 @@ namespace AZ , public AzToolsFramework::EditorLevelNotificationBus::Handler , public AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler , public AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler + , public AzFramework::AssetCatalogEventBus::Handler , public AzFramework::ApplicationLifecycleEvents::Bus::Handler { public: @@ -56,6 +57,9 @@ namespace AZ void OnSliceInstantiated(const AZ::Data::AssetId&, AZ::SliceComponent::SliceInstanceAddress&, const AzFramework::SliceInstantiationTicket&) override; void OnSliceInstantiationFailed(const AZ::Data::AssetId&, const AzFramework::SliceInstantiationTicket&) override; + // AzFramework::AssetCatalogEventBus::Handler overrides ... + void OnCatalogLoaded(const char* catalogFile) override; + // AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler overrides... const AzToolsFramework::AssetBrowser::PreviewerFactory* GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp index 9c69fdd995..d12d9df892 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp @@ -6,15 +6,42 @@ * */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include -#include #include #include -#include -#include #include +#include namespace AZ { @@ -23,23 +50,310 @@ namespace AZ namespace Thumbnails { CommonThumbnailRenderer::CommonThumbnailRenderer() - : m_data(new ThumbnailRendererData) { // CommonThumbnailRenderer supports both models and materials, but we connect on materialAssetType // since MaterialOrModelThumbnail dispatches event on materialAssetType address too AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); - SystemTickBus::Handler::BusConnect(); ThumbnailFeatureProcessorProviderBus::Handler::BusConnect(); + SystemTickBus::Handler::BusConnect(); - m_steps[Step::Initialize] = AZStd::make_shared(this); - m_steps[Step::FindThumbnailToRender] = AZStd::make_shared(this); - m_steps[Step::WaitForAssetsToLoad] = AZStd::make_shared(this); - m_steps[Step::Capture] = AZStd::make_shared(this); - m_steps[Step::ReleaseResources] = AZStd::make_shared(this); + m_entityContext = AZStd::make_unique(); + m_entityContext->InitContext(); - m_minimalFeatureProcessors = + // Create and register a scene with all required feature processors + AZStd::unordered_set featureProcessors; + ThumbnailFeatureProcessorProviderBus::Broadcast( + &ThumbnailFeatureProcessorProviderBus::Handler::GetCustomFeatureProcessors, featureProcessors); + + RPI::SceneDescriptor sceneDesc; + sceneDesc.m_featureProcessorNames.assign(featureProcessors.begin(), featureProcessors.end()); + m_scene = RPI::Scene::CreateScene(sceneDesc); + + // Bind m_frameworkScene to the entity context's AzFramework::Scene + auto sceneSystem = AzFramework::SceneSystemInterface::Get(); + AZ_Assert(sceneSystem, "Thumbnail system failed to get scene system implementation."); + + Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(m_sceneName); + AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); + + m_frameworkScene = createSceneOutcome.TakeValue(); + m_frameworkScene->SetSubsystem(m_scene); + m_frameworkScene->SetSubsystem(m_entityContext.get()); + + // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene + RPI::RenderPipelineDescriptor pipelineDesc; + pipelineDesc.m_mainViewTagName = "MainCamera"; + pipelineDesc.m_name = m_pipelineName; + pipelineDesc.m_rootPassTemplate = "MainPipelineRenderToTexture"; + + // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue + // [GFX TODO] [ATOM-13551] Default value sand validation required to prevent pipeline crash and device lost + pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; + m_renderPipeline = RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc); + m_scene->AddRenderPipeline(m_renderPipeline); + m_scene->Activate(); + RPI::RPISystemInterface::Get()->RegisterScene(m_scene); + m_passHierarchy.push_back(m_pipelineName); + m_passHierarchy.push_back("CopyToSwapChain"); + + // Connect camera to pipeline's default view after camera entity activated + Matrix4x4 viewToClipMatrix; + MakePerspectiveFovMatrixRH(viewToClipMatrix, FieldOfView, AspectRatio, NearDist, FarDist, true); + m_view = RPI::View::CreateView(Name("MainCamera"), RPI::View::UsageCamera); + m_view->SetViewToClipMatrix(viewToClipMatrix); + m_renderPipeline->SetDefaultView(m_view); + + // Create preview model + AzFramework::EntityContextRequestBus::EventResult( + m_modelEntity, m_entityContext->GetContextId(), &AzFramework::EntityContextRequestBus::Events::CreateEntity, + "ThumbnailPreviewModel"); + m_modelEntity->CreateComponent(Render::MeshComponentTypeId); + m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); + m_modelEntity->CreateComponent(azrtti_typeid()); + m_modelEntity->Init(); + m_modelEntity->Activate(); + + m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); + m_defaultModelAsset.Create(DefaultModelAssetId, true); + + m_steps[CommonThumbnailRenderer::Step::FindThumbnailToRender] = AZStd::make_shared(this); + m_steps[CommonThumbnailRenderer::Step::WaitForAssetsToLoad] = AZStd::make_shared(this); + m_steps[CommonThumbnailRenderer::Step::Capture] = AZStd::make_shared(this); + SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + } + + CommonThumbnailRenderer::~CommonThumbnailRenderer() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); + SystemTickBus::Handler::BusDisconnect(); + ThumbnailFeatureProcessorProviderBus::Handler::BusDisconnect(); + + SetStep(CommonThumbnailRenderer::Step::None); + + if (m_modelEntity) { + AzFramework::EntityContextRequestBus::Event( + m_entityContext->GetContextId(), &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); + m_modelEntity = nullptr; + } + + m_scene->Deactivate(); + m_scene->RemoveRenderPipeline(m_renderPipeline->GetId()); + RPI::RPISystemInterface::Get()->UnregisterScene(m_scene); + m_frameworkScene->UnsetSubsystem(m_scene); + m_frameworkScene->UnsetSubsystem(m_entityContext.get()); + } + + void CommonThumbnailRenderer::SetStep(Step step) + { + auto stepItr = m_steps.find(m_currentStep); + if (stepItr != m_steps.end()) + { + stepItr->second->Stop(); + } + + m_currentStep = step; + + stepItr = m_steps.find(m_currentStep); + if (stepItr != m_steps.end()) + { + stepItr->second->Start(); + } + } + + CommonThumbnailRenderer::Step CommonThumbnailRenderer::GetStep() const + { + return m_currentStep; + } + + void CommonThumbnailRenderer::SelectThumbnail() + { + if (!m_thumbnailInfoQueue.empty()) + { + // pop the next thumbnailkey to be rendered from the queue + m_currentThubnailInfo = m_thumbnailInfoQueue.front(); + m_thumbnailInfoQueue.pop(); + + SetStep(CommonThumbnailRenderer::Step::WaitForAssetsToLoad); + } + } + + void CommonThumbnailRenderer::CancelThumbnail() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + m_currentThubnailInfo.m_key, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + } + + void CommonThumbnailRenderer::CompleteThumbnail() + { + SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + } + + void CommonThumbnailRenderer::LoadAssets() + { + // Determine if thumbnailkey contains a material asset or set a default material + const Data::AssetId materialAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::MaterialAsset::RTTI_Type()); + m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, true); + + // Determine if thumbnailkey contains a model asset or set a default model + const Data::AssetId modelAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::ModelAsset::RTTI_Type()); + m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, true); + + // Determine if thumbnailkey contains a lighting preset asset or set a default lighting preset + const Data::AssetId lightingPresetAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::AnyAsset::RTTI_Type()); + m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, true); + } + + void CommonThumbnailRenderer::UpdateLoadAssets() + { + if (m_materialAsset.IsReady() && m_modelAsset.IsReady() && m_lightingPresetAsset.IsReady()) + { + SetStep(CommonThumbnailRenderer::Step::Capture); + return; + } + + if (m_materialAsset.IsError() || m_modelAsset.IsError() || m_lightingPresetAsset.IsError()) + { + CancelLoadAssets(); + return; + } + } + + void CommonThumbnailRenderer::CancelLoadAssets() + { + AZ_Warning( + "CommonThumbnailRenderer", m_materialAsset.IsReady(), "Asset failed to load in time: %s", + m_materialAsset.ToString().c_str()); + AZ_Warning( + "CommonThumbnailRenderer", m_modelAsset.IsReady(), "Asset failed to load in time: %s", + m_modelAsset.ToString().c_str()); + AZ_Warning( + "CommonThumbnailRenderer", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", + m_lightingPresetAsset.ToString().c_str()); + CancelThumbnail(); + } + + void CommonThumbnailRenderer::UpdateScene() + { + UpdateModel(); + UpdateLighting(); + UpdateCamera(); + } + + void CommonThumbnailRenderer::UpdateModel() + { + Render::MaterialComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, + m_materialAsset.GetId()); + + Render::MeshComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); + } + + void CommonThumbnailRenderer::UpdateLighting() + { + auto preset = m_lightingPresetAsset->GetDataAs(); + if (preset) + { + auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); + auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); + auto directionalLightFeatureProcessor = + m_scene->GetFeatureProcessor(); + auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); + skyboxFeatureProcessor->Enable(true); + skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); + + Camera::Configuration cameraConfig; + cameraConfig.m_fovRadians = FieldOfView; + cameraConfig.m_nearClipDistance = NearDist; + cameraConfig.m_farClipDistance = FarDist; + cameraConfig.m_frustumWidth = 100.0f; + cameraConfig.m_frustumHeight = 100.0f; + + AZStd::vector lightHandles; + + preset->ApplyLightingPreset( + iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, + cameraConfig, lightHandles); + } + } + + void CommonThumbnailRenderer::UpdateCamera() + { + // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it + Vector3 center = {}; + float radius = {}; + m_modelAsset->GetAabb().GetAsSphere(center, radius); + + const auto distance = radius + NearDist; + const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); + const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); + const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); + m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); + } + + RPI::AttachmentReadback::CallbackFunction CommonThumbnailRenderer::GetCaptureCallback() + { + return [this](const RPI::AttachmentReadback::ReadbackResult& result) + { + if (result.m_dataBuffer) + { + QImage image( + result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, + result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888); + + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + m_currentThubnailInfo.m_key, + &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, QPixmap::fromImage(image)); + } + else + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + m_currentThubnailInfo.m_key, + &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + } + }; + } + + bool CommonThumbnailRenderer::StartCapture() + { + if (auto renderToTexturePass = azrtti_cast(m_renderPipeline->GetRootPass().get())) + { + renderToTexturePass->ResizeOutput(m_currentThubnailInfo.m_size, m_currentThubnailInfo.m_size); + } + + m_renderPipeline->AddToRenderTickOnce(); + + bool startedCapture = false; + Render::FrameCaptureRequestBus::BroadcastResult( + startedCapture, &Render::FrameCaptureRequestBus::Events::CapturePassAttachmentWithCallback, m_passHierarchy, + AZStd::string("Output"), GetCaptureCallback(), RPI::PassAttachmentReadbackOption::Output); + return startedCapture; + } + + void CommonThumbnailRenderer::EndCapture() + { + m_renderPipeline->RemoveFromRenderTick(); + } + + bool CommonThumbnailRenderer::Installed() const + { + return true; + } + + void CommonThumbnailRenderer::OnSystemTick() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); + } + + void CommonThumbnailRenderer::GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const + { + featureProcessors.insert({ "AZ::Render::TransformServiceFeatureProcessor", "AZ::Render::MeshFeatureProcessor", "AZ::Render::SimplePointLightFeatureProcessor", @@ -56,64 +370,12 @@ namespace AZ "AZ::Render::DecalTextureArrayFeatureProcessor", "AZ::Render::ImageBasedLightFeatureProcessor", "AZ::Render::PostProcessFeatureProcessor", - "AZ::Render::SkyBoxFeatureProcessor" - }; - } - - CommonThumbnailRenderer::~CommonThumbnailRenderer() - { - if (m_currentStep != Step::None) - { - CommonThumbnailRenderer::SetStep(Step::ReleaseResources); - } - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); - SystemTickBus::Handler::BusDisconnect(); - ThumbnailFeatureProcessorProviderBus::Handler::BusDisconnect(); - } - - void CommonThumbnailRenderer::SetStep(Step step) - { - if (m_currentStep != Step::None) - { - m_steps[m_currentStep]->Stop(); - } - m_currentStep = step; - m_steps[m_currentStep]->Start(); - } - - Step CommonThumbnailRenderer::GetStep() const - { - return m_currentStep; - } - - bool CommonThumbnailRenderer::Installed() const - { - return true; - } - - void CommonThumbnailRenderer::OnSystemTick() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); - } - - const AZStd::vector& CommonThumbnailRenderer::GetCustomFeatureProcessors() const - { - return m_minimalFeatureProcessors; + "AZ::Render::SkyBoxFeatureProcessor" }); } - AZStd::shared_ptr CommonThumbnailRenderer::GetData() const - { - return m_data; - } - void CommonThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) { - m_data->m_thumbnailSize = thumbnailSize; - m_data->m_thumbnailQueue.push(thumbnailKey); - if (m_currentStep == Step::None) - { - SetStep(Step::Initialize); - } + m_thumbnailInfoQueue.push({ thumbnailKey, thumbnailSize }); } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h index 7c3b17e104..2b1ccbd4e6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h @@ -8,15 +8,24 @@ #pragma once +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include +#include -#include +namespace AzFramework +{ + class Scene; +} // Disables warning messages triggered by the Qt library -// 4251: class needs to have dll-interface to be used by clients of class +// 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") #include @@ -32,10 +41,9 @@ namespace AZ //! Provides custom rendering of material and model thumbnails class CommonThumbnailRenderer - : public ThumbnailRendererContext - , private AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler - , private SystemTickBus::Handler - , private ThumbnailFeatureProcessorProviderBus::Handler + : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler + , public SystemTickBus::Handler + , public ThumbnailFeatureProcessorProviderBus::Handler { public: AZ_CLASS_ALLOCATOR(CommonThumbnailRenderer, AZ::SystemAllocator, 0) @@ -43,10 +51,33 @@ namespace AZ CommonThumbnailRenderer(); ~CommonThumbnailRenderer(); - //! ThumbnailRendererContext overrides... - void SetStep(Step step) override; - Step GetStep() const override; - AZStd::shared_ptr GetData() const override; + enum class Step : AZ::s8 + { + None, + FindThumbnailToRender, + WaitForAssetsToLoad, + Capture + }; + + void SetStep(Step step); + Step GetStep() const; + + void SelectThumbnail(); + void CancelThumbnail(); + void CompleteThumbnail(); + + void LoadAssets(); + void UpdateLoadAssets(); + void CancelLoadAssets(); + + void UpdateScene(); + void UpdateModel(); + void UpdateLighting(); + void UpdateCamera(); + + RPI::AttachmentReadback::CallbackFunction GetCaptureCallback(); + bool StartCapture(); + void EndCapture(); private: //! ThumbnailerRendererRequestsBus::Handler interface overrides... @@ -57,12 +88,53 @@ namespace AZ void OnSystemTick() override; //! Render::ThumbnailFeatureProcessorProviderBus::Handler interface overrides... - const AZStd::vector& GetCustomFeatureProcessors() const override; + void GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; + + static constexpr float AspectRatio = 1.0f; + static constexpr float NearDist = 0.001f; + static constexpr float FarDist = 100.0f; + static constexpr float FieldOfView = Constants::HalfPi; + static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; + + RPI::ScenePtr m_scene; + AZStd::string m_sceneName = "Material Thumbnail Scene"; + AZStd::string m_pipelineName = "Material Thumbnail Pipeline"; + AZStd::shared_ptr m_frameworkScene; + RPI::RenderPipelinePtr m_renderPipeline; + RPI::ViewPtr m_view; + AZStd::vector m_passHierarchy; + AZStd::unique_ptr m_entityContext; + + //! Incoming thumbnail requests are appended to this queue and processed one at a time in OnTick function. + struct ThumbnailInfo + { + AzToolsFramework::Thumbnailer::SharedThumbnailKey m_key; + int m_size = 512; + }; + AZStd::queue m_thumbnailInfoQueue; + ThumbnailInfo m_currentThubnailInfo; AZStd::unordered_map> m_steps; - Step m_currentStep = Step::None; - AZStd::shared_ptr m_data; - AZStd::vector m_minimalFeatureProcessors; + Step m_currentStep = CommonThumbnailRenderer::Step::None; + + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; + Data::Asset m_lightingPresetAsset; + + //! Model asset about to be rendered + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; + Data::Asset m_modelAsset; + + //! Material asset about to be rendered + static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; + const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); + Data::Asset m_defaultMaterialAsset; + Data::Asset m_materialAsset; + + Entity* m_modelEntity = nullptr; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererContext.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererContext.h deleted file mode 100644 index d3bb2be64a..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererContext.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - struct ThumbnailRendererData; - - enum class Step - { - None, - Initialize, - FindThumbnailToRender, - WaitForAssetsToLoad, - Capture, - ReleaseResources - }; - - //! An interface for ThumbnailRendererSteps to communicate with thumbnail renderer - class ThumbnailRendererContext - { - public: - virtual void SetStep(Step step) = 0; - virtual Step GetStep() const = 0; - virtual AZStd::shared_ptr GetData() const = 0; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererData.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererData.h deleted file mode 100644 index c471cf90d7..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererData.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include "Atom/RPI.Reflect/Model/ModelAsset.h" - -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - class Scene; -} - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! ThumbnailRendererData encapsulates all data used by thumbnail renderer and caches assets - struct ThumbnailRendererData final - { - static constexpr const char* LightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; - - RPI::ScenePtr m_scene; - AZStd::string m_sceneName = "Material Thumbnail Scene"; - AZStd::string m_pipelineName = "Material Thumbnail Pipeline"; - AZStd::shared_ptr m_frameworkScene; - RPI::RenderPipelinePtr m_renderPipeline; - AZStd::unique_ptr m_entityContext; - AZStd::vector m_passHierarchy; - - RPI::ViewPtr m_view = nullptr; - Entity* m_modelEntity = nullptr; - - int m_thumbnailSize = 512; - - //! Incoming thumbnail requests are appended to this queue and processed one at a time in OnTick function. - AZStd::queue m_thumbnailQueue; - //! Current thumbnail key being rendered. - AzToolsFramework::Thumbnailer::SharedThumbnailKey m_thumbnailKeyRendered; - - Data::Asset m_lightingPresetAsset; - - Data::Asset m_defaultModelAsset; - //! Model asset about to be rendered - Data::Asset m_modelAsset; - - Data::Asset m_defaultMaterialAsset; - //! Material asset about to be rendered - Data::Asset m_materialAsset; - - AZStd::unordered_set m_assetsToLoad; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp index f728d56bbc..0686ffb971 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp @@ -6,19 +6,8 @@ * */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include -#include namespace AZ { @@ -26,104 +15,42 @@ namespace AZ { namespace Thumbnails { - CaptureStep::CaptureStep(ThumbnailRendererContext* context) - : ThumbnailRendererStep(context) + CaptureStep::CaptureStep(CommonThumbnailRenderer* renderer) + : ThumbnailRendererStep(renderer) { } void CaptureStep::Start() { - if (!m_context->GetData()->m_materialAsset || - !m_context->GetData()->m_modelAsset) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - m_context->SetStep(Step::FindThumbnailToRender); - return; - } - Render::MaterialComponentRequestBus::Event( - m_context->GetData()->m_modelEntity->GetId(), - &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, - m_context->GetData()->m_materialAsset.GetId()); - Render::MeshComponentRequestBus::Event( - m_context->GetData()->m_modelEntity->GetId(), - &Render::MeshComponentRequestBus::Events::SetModelAsset, - m_context->GetData()->m_modelAsset); - RepositionCamera(); - m_readyToCapture = true; m_ticksToCapture = 1; + m_renderer->UpdateScene(); TickBus::Handler::BusConnect(); } void CaptureStep::Stop() { - m_context->GetData()->m_renderPipeline->RemoveFromRenderTick(); + m_renderer->EndCapture(); TickBus::Handler::BusDisconnect(); Render::FrameCaptureNotificationBus::Handler::BusDisconnect(); } - void CaptureStep::RepositionCamera() const - { - // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it - const Aabb& aabb = m_context->GetData()->m_modelAsset->GetAabb(); - Vector3 modelCenter; - float radius; - aabb.GetAsSphere(modelCenter, radius); - - float distance = StartingDistanceMultiplier * - GetMax(GetMax(aabb.GetExtents().GetX(), aabb.GetExtents().GetY()), aabb.GetExtents().GetZ()) + - DepthNear; - const Quaternion cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), StartingRotationAngle); - Vector3 cameraPosition(modelCenter.GetX(), modelCenter.GetY() - distance, modelCenter.GetZ()); - cameraPosition = cameraRotation.TransformVector(cameraPosition); - auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); - m_context->GetData()->m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); - } - void CaptureStep::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) { - if (m_readyToCapture && m_ticksToCapture-- <= 0) + if (m_ticksToCapture-- <= 0) { - m_context->GetData()->m_renderPipeline->AddToRenderTickOnce(); - - RPI::AttachmentReadback::CallbackFunction readbackCallback = [&](const RPI::AttachmentReadback::ReadbackResult& result) - { - if (!result.m_dataBuffer) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - return; - } - uchar* data = result.m_dataBuffer.get()->data(); - QImage image( - data, result.m_imageDescriptor.m_size.m_width, result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888); - QPixmap pixmap; - pixmap.convertFromImage(image); - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, - pixmap); - }; - - Render::FrameCaptureNotificationBus::Handler::BusConnect(); - bool startedCapture = false; - Render::FrameCaptureRequestBus::BroadcastResult( - startedCapture, - &Render::FrameCaptureRequestBus::Events::CapturePassAttachmentWithCallback, - m_context->GetData()->m_passHierarchy, AZStd::string("Output"), readbackCallback, RPI::PassAttachmentReadbackOption::Output); // Reset the capture flag if the capture request was successful. Otherwise try capture it again next tick. - if (startedCapture) + if (m_renderer->StartCapture()) { - m_readyToCapture = false; + Render::FrameCaptureNotificationBus::Handler::BusConnect(); + TickBus::Handler::BusDisconnect(); } } } - void CaptureStep::OnCaptureFinished([[maybe_unused]] Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) + void CaptureStep::OnCaptureFinished( + [[maybe_unused]] Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) { - m_context->SetStep(Step::FindThumbnailToRender); + m_renderer->CompleteThumbnail(); } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h index e93828e3b8..46d642ce53 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h @@ -25,27 +25,18 @@ namespace AZ , private Render::FrameCaptureNotificationBus::Handler { public: - CaptureStep(ThumbnailRendererContext* context); + CaptureStep(CommonThumbnailRenderer* renderer); void Start() override; void Stop() override; private: - //! Places the camera so that the entire model is visible - void RepositionCamera() const; - //! AZ::TickBus::Handler interface overrides... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; //! Render::FrameCaptureNotificationBus::Handler overrides... void OnCaptureFinished(Render::FrameCaptureResult result, const AZStd::string& info) override; - - static constexpr float DepthNear = 0.01f; - static constexpr float StartingDistanceMultiplier = 1.75f; - static constexpr float StartingRotationAngle = Constants::QuarterPi / 2.0f; - //! This flag is needed to wait one frame after each frame capture to reset FrameCaptureSystemComponent - bool m_readyToCapture = true; //! This is necessary to suspend capture to allow a frame for Material and Mesh components to assign materials int m_ticksToCapture = 0; }; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp index 826ec4ae0d..d9c978605a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp @@ -6,11 +6,7 @@ * */ -#include -#include -#include -#include -#include +#include #include namespace AZ @@ -19,8 +15,8 @@ namespace AZ { namespace Thumbnails { - FindThumbnailToRenderStep::FindThumbnailToRenderStep(ThumbnailRendererContext* context) - : ThumbnailRendererStep(context) + FindThumbnailToRenderStep::FindThumbnailToRenderStep(CommonThumbnailRenderer* renderer) + : ThumbnailRendererStep(renderer) { } @@ -36,43 +32,7 @@ namespace AZ void FindThumbnailToRenderStep::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) { - PickNextThumbnail(); - } - - void FindThumbnailToRenderStep::PickNextThumbnail() - { - if (!m_context->GetData()->m_thumbnailQueue.empty()) - { - // pop the next thumbnailkey to be rendered from the queue - m_context->GetData()->m_thumbnailKeyRendered = m_context->GetData()->m_thumbnailQueue.front(); - m_context->GetData()->m_thumbnailQueue.pop(); - - // Find whether thumbnailkey contains a material asset or set a default material - m_context->GetData()->m_materialAsset = m_context->GetData()->m_defaultMaterialAsset; - Data::AssetId materialAssetId = GetAssetId(m_context->GetData()->m_thumbnailKeyRendered, RPI::MaterialAsset::RTTI_Type()); - if (materialAssetId.IsValid()) - { - if (m_context->GetData()->m_assetsToLoad.emplace(materialAssetId).second) - { - m_context->GetData()->m_materialAsset.Create(materialAssetId); - m_context->GetData()->m_materialAsset.QueueLoad(); - } - } - - // Find whether thumbnailkey contains a model asset or set a default model - m_context->GetData()->m_modelAsset = m_context->GetData()->m_defaultModelAsset; - Data::AssetId modelAssetId = GetAssetId(m_context->GetData()->m_thumbnailKeyRendered, RPI::ModelAsset::RTTI_Type()); - if (modelAssetId.IsValid()) - { - if (m_context->GetData()->m_assetsToLoad.emplace(modelAssetId).second) - { - m_context->GetData()->m_modelAsset.Create(modelAssetId); - m_context->GetData()->m_modelAsset.QueueLoad(); - } - } - - m_context->SetStep(Step::WaitForAssetsToLoad); - } + m_renderer->SelectThumbnail(); } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h index e63bc5dce5..6ba9b974a1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h @@ -22,7 +22,7 @@ namespace AZ , private TickBus::Handler { public: - FindThumbnailToRenderStep(ThumbnailRendererContext* context); + FindThumbnailToRenderStep(CommonThumbnailRenderer* renderer); void Start() override; void Stop() override; @@ -31,8 +31,6 @@ namespace AZ //! AZ::TickBus::Handler interface overrides... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - - void PickNextThumbnail(); }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp deleted file mode 100644 index 6f74627bee..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include -#include - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - InitializeStep::InitializeStep(ThumbnailRendererContext* context) - : ThumbnailRendererStep(context) - { - } - - void InitializeStep::Start() - { - auto data = m_context->GetData(); - - data->m_entityContext = AZStd::make_unique(); - data->m_entityContext->InitContext(); - - // Create and register a scene with all required feature processors - RPI::SceneDescriptor sceneDesc; - - AZ::EBusAggregateResults> results; - ThumbnailFeatureProcessorProviderBus::BroadcastResult(results, &ThumbnailFeatureProcessorProviderBus::Handler::GetCustomFeatureProcessors); - - AZStd::set featureProcessorNames; - for (auto& resultCollection : results.values) - { - for (auto& featureProcessorName : resultCollection) - { - if (featureProcessorNames.emplace(featureProcessorName).second) - { - sceneDesc.m_featureProcessorNames.push_back(featureProcessorName); - } - } - } - - data->m_scene = RPI::Scene::CreateScene(sceneDesc); - - // Bind m_defaultScene to the GameEntityContext's AzFramework::Scene - auto* sceneSystem = AzFramework::SceneSystemInterface::Get(); - AZ_Assert(sceneSystem, "Thumbnail system failed to get scene system implementation."); - Outcome, AZStd::string> createSceneOutcome = - sceneSystem->CreateScene(data->m_sceneName); - AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); // This should never happen unless scene creation has changed. - data->m_frameworkScene = createSceneOutcome.TakeValue(); - data->m_frameworkScene->SetSubsystem(data->m_scene); - - data->m_frameworkScene->SetSubsystem(data->m_entityContext.get()); - // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene - RPI::RenderPipelineDescriptor pipelineDesc; - pipelineDesc.m_mainViewTagName = "MainCamera"; - pipelineDesc.m_name = data->m_pipelineName; - pipelineDesc.m_rootPassTemplate = "ThumbnailPipelineRenderToTexture"; - // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue - // [GFX TODO] [ATOM-13551] Default value sand validation required to prevent pipeline crash and device lost - pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; - data->m_renderPipeline = RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc); - data->m_scene->AddRenderPipeline(data->m_renderPipeline); - data->m_scene->Activate(); - RPI::RPISystemInterface::Get()->RegisterScene(data->m_scene); - data->m_passHierarchy.push_back(data->m_pipelineName); - data->m_passHierarchy.push_back("CopyToSwapChain"); - - // Connect camera to pipeline's default view after camera entity activated - Name viewName = Name("MainCamera"); - data->m_view = RPI::View::CreateView(viewName, RPI::View::UsageCamera); - - Matrix4x4 viewToClipMatrix; - MakePerspectiveFovMatrixRH(viewToClipMatrix, - Constants::QuarterPi, - AspectRatio, - NearDist, - FarDist, true); - data->m_view->SetViewToClipMatrix(viewToClipMatrix); - - data->m_renderPipeline->SetDefaultView(data->m_view); - - // Create lighting preset - data->m_lightingPresetAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath(ThumbnailRendererData::LightingPresetPath); - if (data->m_lightingPresetAsset.IsReady()) - { - auto preset = data->m_lightingPresetAsset->GetDataAs(); - if (preset) - { - auto iblFeatureProcessor = data->m_scene->GetFeatureProcessor(); - auto postProcessFeatureProcessor = data->m_scene->GetFeatureProcessor(); - auto exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId())->GetOrCreateExposureControlSettingsInterface(); - auto directionalLightFeatureProcessor = data->m_scene->GetFeatureProcessor(); - auto skyboxFeatureProcessor = data->m_scene->GetFeatureProcessor(); - skyboxFeatureProcessor->Enable(true); - skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); - - Camera::Configuration cameraConfig; - cameraConfig.m_fovRadians = Constants::HalfPi; - cameraConfig.m_nearClipDistance = NearDist; - cameraConfig.m_farClipDistance = FarDist; - cameraConfig.m_frustumWidth = 100.0f; - cameraConfig.m_frustumHeight = 100.0f; - - AZStd::vector lightHandles; - - preset->ApplyLightingPreset( - iblFeatureProcessor, - skyboxFeatureProcessor, - exposureControlSettingInterface, - directionalLightFeatureProcessor, - cameraConfig, - lightHandles); - } - } - - // Create preview model - AzFramework::EntityContextRequestBus::EventResult(data->m_modelEntity, data->m_entityContext->GetContextId(), - &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ThumbnailPreviewModel"); - data->m_modelEntity->CreateComponent(Render::MeshComponentTypeId); - data->m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); - data->m_modelEntity->CreateComponent(azrtti_typeid()); - data->m_modelEntity->Init(); - data->m_modelEntity->Activate(); - - // preload default model - Data::AssetId defaultModelAssetId; - Data::AssetCatalogRequestBus::BroadcastResult( - defaultModelAssetId, - &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, - m_context->GetData()->DefaultModelPath, - RPI::ModelAsset::RTTI_Type(), - false); - AZ_Error("ThumbnailRenderer", defaultModelAssetId.IsValid(), "Default model asset is invalid. Verify the asset %s exists.", m_context->GetData()->DefaultModelPath); - if (m_context->GetData()->m_assetsToLoad.emplace(defaultModelAssetId).second) - { - data->m_defaultModelAsset.Create(defaultModelAssetId); - data->m_defaultModelAsset.QueueLoad(); - } - - // preload default material - Data::AssetId defaultMaterialAssetId; - Data::AssetCatalogRequestBus::BroadcastResult( - defaultMaterialAssetId, - &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, - m_context->GetData()->DefaultMaterialPath, - RPI::MaterialAsset::RTTI_Type(), - false); - AZ_Error("ThumbnailRenderer", defaultMaterialAssetId.IsValid(), "Default material asset is invalid. Verify the asset %s exists.", m_context->GetData()->DefaultMaterialPath); - if (m_context->GetData()->m_assetsToLoad.emplace(defaultMaterialAssetId).second) - { - data->m_defaultMaterialAsset.Create(defaultMaterialAssetId); - data->m_defaultMaterialAsset.QueueLoad(); - } - - m_context->SetStep(Step::FindThumbnailToRender); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.h deleted file mode 100644 index cdac492e80..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! InitializeStep sets up RPI system and scene and prepares it for rendering thumbnail entities - //! This step is only called once when CommonThumbnailRenderer begins rendering its first thumbnail - class InitializeStep - : public ThumbnailRendererStep - { - public: - InitializeStep(ThumbnailRendererContext* context); - - void Start() override; - - private: - static constexpr float AspectRatio = 1.0f; - static constexpr float NearDist = 0.1f; - static constexpr float FarDist = 100.0f; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp deleted file mode 100644 index a14f48e408..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - ReleaseResourcesStep::ReleaseResourcesStep(ThumbnailRendererContext* context) - : ThumbnailRendererStep(context) - { - } - - void ReleaseResourcesStep::Start() - { - auto data = m_context->GetData(); - - data->m_defaultMaterialAsset.Release(); - data->m_defaultModelAsset.Release(); - data->m_materialAsset.Release(); - data->m_modelAsset.Release(); - data->m_lightingPresetAsset.Release(); - - if (data->m_modelEntity) - { - AzFramework::EntityContextRequestBus::Event(data->m_entityContext->GetContextId(), - &AzFramework::EntityContextRequestBus::Events::DestroyEntity, data->m_modelEntity); - data->m_modelEntity = nullptr; - } - - data->m_scene->Deactivate(); - data->m_scene->RemoveRenderPipeline(data->m_renderPipeline->GetId()); - RPI::RPISystemInterface::Get()->UnregisterScene(data->m_scene); - data->m_frameworkScene->UnsetSubsystem(data->m_scene); - data->m_frameworkScene->UnsetSubsystem(data->m_entityContext.get()); - data->m_scene = nullptr; - data->m_frameworkScene = nullptr; - data->m_renderPipeline = nullptr; - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.h deleted file mode 100644 index 4858b90b96..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - class ReleaseResourcesStep - : public ThumbnailRendererStep - { - public: - ReleaseResourcesStep(ThumbnailRendererContext* context); - - void Start() override; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h index cc10f91525..0a629e7e25 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h @@ -14,13 +14,13 @@ namespace AZ { namespace Thumbnails { - class ThumbnailRendererContext; + class CommonThumbnailRenderer; //! ThumbnailRendererStep decouples CommonThumbnailRenderer logic into easy-to-understand and debug pieces class ThumbnailRendererStep { public: - explicit ThumbnailRendererStep(ThumbnailRendererContext* context) : m_context(context) {} + explicit ThumbnailRendererStep(CommonThumbnailRenderer* renderer) : m_renderer(renderer) {} virtual ~ThumbnailRendererStep() = default; //! Start is called when step begins execution @@ -29,7 +29,7 @@ namespace AZ virtual void Stop() {} protected: - ThumbnailRendererContext* m_context; + CommonThumbnailRenderer* m_renderer; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp index 4f32bc4b68..53a5b596d4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp @@ -7,9 +7,7 @@ */ #include "Thumbnails/ThumbnailerBus.h" - -#include -#include +#include #include #include @@ -19,81 +17,33 @@ namespace AZ { namespace Thumbnails { - WaitForAssetsToLoadStep::WaitForAssetsToLoadStep(ThumbnailRendererContext* context) - : ThumbnailRendererStep(context) + WaitForAssetsToLoadStep::WaitForAssetsToLoadStep(CommonThumbnailRenderer* renderer) + : ThumbnailRendererStep(renderer) { } void WaitForAssetsToLoadStep::Start() { - LoadNextAsset(); + m_renderer->LoadAssets(); + m_timeRemainingS = TimeOutS; + TickBus::Handler::BusConnect(); } void WaitForAssetsToLoadStep::Stop() { - Data::AssetBus::Handler::BusDisconnect(); TickBus::Handler::BusDisconnect(); - m_context->GetData()->m_assetsToLoad.clear(); - } - - void WaitForAssetsToLoadStep::LoadNextAsset() - { - if (m_context->GetData()->m_assetsToLoad.empty()) - { - // When all assets are loaded, render the thumbnail itself - m_context->SetStep(Step::Capture); - } - else - { - // Pick the the next asset and wait until its ready - const auto assetIdIt = m_context->GetData()->m_assetsToLoad.begin(); - m_context->GetData()->m_assetsToLoad.erase(assetIdIt); - m_assetId = *assetIdIt; - Data::AssetBus::Handler::BusConnect(m_assetId); - // If asset is already loaded, then AssetEvents will call OnAssetReady instantly and we don't need to wait this time - if (Data::AssetBus::Handler::BusIsConnected()) - { - TickBus::Handler::BusConnect(); - m_timeRemainingS = TimeOutS; - } - } - } - - void WaitForAssetsToLoadStep::OnAssetReady([[maybe_unused]] Data::Asset asset) - { - Data::AssetBus::Handler::BusDisconnect(); - LoadNextAsset(); - } - - void WaitForAssetsToLoadStep::OnAssetError([[maybe_unused]] Data::Asset asset) - { - Data::AssetBus::Handler::BusDisconnect(); - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - m_context->SetStep(Step::FindThumbnailToRender); - } - - void WaitForAssetsToLoadStep::OnAssetCanceled([[maybe_unused]] Data::AssetId assetId) - { - Data::AssetBus::Handler::BusDisconnect(); - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - m_context->SetStep(Step::FindThumbnailToRender); } void WaitForAssetsToLoadStep::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { m_timeRemainingS -= deltaTime; - if (m_timeRemainingS < 0) + if (m_timeRemainingS > 0.0f) { - auto assetIdStr = m_assetId.ToString(); - AZ_Warning("CommonThumbnailRenderer", false, "Timed out waiting for asset %s to load.", assetIdStr.c_str()); - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_context->GetData()->m_thumbnailKeyRendered, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - m_context->SetStep(Step::FindThumbnailToRender); + m_renderer->UpdateLoadAssets(); + } + else + { + m_renderer->CancelLoadAssets(); } } } // namespace Thumbnails diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h index 921d1511ca..0202ef1045 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h @@ -8,7 +8,6 @@ #pragma once -#include #include namespace AZ @@ -20,29 +19,20 @@ namespace AZ //! WaitForAssetsToLoadStep pauses further rendering until all assets used for rendering a thumbnail have been loaded class WaitForAssetsToLoadStep : public ThumbnailRendererStep - , private Data::AssetBus::Handler , private TickBus::Handler { public: - WaitForAssetsToLoadStep(ThumbnailRendererContext* context); + WaitForAssetsToLoadStep(CommonThumbnailRenderer* renderer); void Start() override; void Stop() override; private: - void LoadNextAsset(); - - // AZ::Data::AssetBus::Handler - void OnAssetReady(Data::Asset asset) override; - void OnAssetError(Data::Asset asset) override; - void OnAssetCanceled(Data::AssetId assetId) override; - //! AZ::TickBus::Handler interface overrides... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - static constexpr float TimeOutS = 3.0f; - Data::AssetId m_assetId; - float m_timeRemainingS = 0; + static constexpr float TimeOutS = 5.0f; + float m_timeRemainingS = TimeOutS; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 174eb30b31..ffc3f257b0 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -104,19 +104,13 @@ set(FILES Source/Thumbnails/Preview/CommonPreviewerFactory.h Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp Source/Thumbnails/Rendering/CommonThumbnailRenderer.h - Source/Thumbnails/Rendering/ThumbnailRendererData.h - Source/Thumbnails/Rendering/ThumbnailRendererContext.h Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.cpp - Source/Thumbnails/Rendering/ThumbnailRendererSteps/InitializeStep.h Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.cpp - Source/Thumbnails/Rendering/ThumbnailRendererSteps/ReleaseResourcesStep.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From dd5272c2ae5365a5b69db9280756df19ca0a65ed Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 7 Oct 2021 12:21:48 -0500 Subject: [PATCH 02/52] Renaming/moving preview renderer files Signed-off-by: Guthrie Adams --- .../{CommonThumbnailRenderer.cpp => CommonPreviewRenderer.cpp} | 0 .../{CommonThumbnailRenderer.h => CommonPreviewRenderer.h} | 0 .../CaptureStep.cpp => CommonPreviewRendererCaptureState.cpp} | 0 .../CaptureStep.h => CommonPreviewRendererCaptureState.h} | 0 ...umbnailToRenderStep.cpp => CommonPreviewRendererIdleState.cpp} | 0 ...ndThumbnailToRenderStep.h => CommonPreviewRendererIdleState.h} | 0 ...ForAssetsToLoadStep.cpp => CommonPreviewRendererLoadState.cpp} | 0 ...WaitForAssetsToLoadStep.h => CommonPreviewRendererLoadState.h} | 0 .../ThumbnailRendererStep.h => CommonPreviewRendererState.h} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{CommonThumbnailRenderer.cpp => CommonPreviewRenderer.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{CommonThumbnailRenderer.h => CommonPreviewRenderer.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/CaptureStep.cpp => CommonPreviewRendererCaptureState.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/CaptureStep.h => CommonPreviewRendererCaptureState.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp => CommonPreviewRendererIdleState.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/FindThumbnailToRenderStep.h => CommonPreviewRendererIdleState.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp => CommonPreviewRendererLoadState.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/WaitForAssetsToLoadStep.h => CommonPreviewRendererLoadState.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/{ThumbnailRendererSteps/ThumbnailRendererStep.h => CommonPreviewRendererState.h} (100%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonThumbnailRenderer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h From 58194b70c0e72675cd78cda101284af8ddf52c68 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 7 Oct 2021 13:27:14 -0500 Subject: [PATCH 03/52] Updated code to compile and reflect changes after renaming files Signed-off-by: Guthrie Adams --- ...=> PreviewerFeatureProcessorProviderBus.h} | 10 +- .../EditorCommonFeaturesSystemComponent.cpp | 2 +- .../EditorCommonFeaturesSystemComponent.h | 6 +- .../Code/Source/Material/MaterialThumbnail.h | 2 +- .../Rendering/CommonPreviewRenderer.cpp | 92 +++++++++---------- .../Rendering/CommonPreviewRenderer.h | 34 +++---- .../CommonPreviewRendererCaptureState.cpp | 16 ++-- .../CommonPreviewRendererCaptureState.h | 10 +- .../CommonPreviewRendererIdleState.cpp | 14 +-- .../CommonPreviewRendererIdleState.h | 10 +- .../CommonPreviewRendererLoadState.cpp | 16 ++-- .../CommonPreviewRendererLoadState.h | 11 ++- .../Rendering/CommonPreviewRendererState.h | 16 ++-- ...egration_commonfeatures_editor_files.cmake | 20 ++-- 14 files changed, 129 insertions(+), 130 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/{ThumbnailFeatureProcessorProviderBus.h => PreviewerFeatureProcessorProviderBus.h} (67%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h similarity index 67% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h index a4d76809ba..ef0e586348 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h @@ -16,18 +16,18 @@ namespace AZ { namespace Thumbnails { - //! ThumbnailFeatureProcessorProviderRequests allows registering custom Feature Processors for thumbnail generation + //! PreviewerFeatureProcessorProviderRequests allows registering custom Feature Processors for thumbnail generation //! Duplicates will be ignored - //! You can check minimal feature processors that are already registered in CommonThumbnailRenderer.cpp - class ThumbnailFeatureProcessorProviderRequests + //! You can check minimal feature processors that are already registered in CommonPreviewRenderer.cpp + class PreviewerFeatureProcessorProviderRequests : public AZ::EBusTraits { public: //! Get a list of custom feature processors to register with thumbnail renderer - virtual void GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; + virtual void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; }; - using ThumbnailFeatureProcessorProviderBus = AZ::EBus; + using PreviewerFeatureProcessorProviderBus = AZ::EBus; } // namespace Thumbnails } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 8be947ae26..0355351654 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -194,7 +194,7 @@ namespace AZ void EditorCommonFeaturesSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) { AZ::TickBus::QueueFunction([this](){ - m_renderer = AZStd::make_unique(); + m_renderer = AZStd::make_unique(); m_previewerFactory = AZStd::make_unique(); }); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h index d26886c4ae..90dc5fcf2e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h @@ -11,10 +11,10 @@ #include #include #include -#include #include -#include +#include #include +#include namespace AZ { @@ -73,7 +73,7 @@ namespace AZ AZStd::string m_atomLevelDefaultAssetPath{ "LevelAssets/default.slice" }; float m_envProbeHeight{ 200.0f }; - AZStd::unique_ptr m_renderer; + AZStd::unique_ptr m_renderer; AZStd::unique_ptr m_previewerFactory; }; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h index dba922a1b2..d323a04a1f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h @@ -13,7 +13,7 @@ #include #include #include -#include +#include #endif namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp index d12d9df892..b24de64b42 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp @@ -37,10 +37,10 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include namespace AZ @@ -49,13 +49,13 @@ namespace AZ { namespace Thumbnails { - CommonThumbnailRenderer::CommonThumbnailRenderer() + CommonPreviewRenderer::CommonPreviewRenderer() { - // CommonThumbnailRenderer supports both models and materials, but we connect on materialAssetType + // CommonPreviewRenderer supports both models and materials, but we connect on materialAssetType // since MaterialOrModelThumbnail dispatches event on materialAssetType address too AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); - ThumbnailFeatureProcessorProviderBus::Handler::BusConnect(); + PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); SystemTickBus::Handler::BusConnect(); m_entityContext = AZStd::make_unique(); @@ -63,8 +63,8 @@ namespace AZ // Create and register a scene with all required feature processors AZStd::unordered_set featureProcessors; - ThumbnailFeatureProcessorProviderBus::Broadcast( - &ThumbnailFeatureProcessorProviderBus::Handler::GetCustomFeatureProcessors, featureProcessors); + PreviewerFeatureProcessorProviderBus::Broadcast( + &PreviewerFeatureProcessorProviderBus::Handler::GetRequiredFeatureProcessors, featureProcessors); RPI::SceneDescriptor sceneDesc; sceneDesc.m_featureProcessorNames.assign(featureProcessors.begin(), featureProcessors.end()); @@ -118,19 +118,19 @@ namespace AZ m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); m_defaultModelAsset.Create(DefaultModelAssetId, true); - m_steps[CommonThumbnailRenderer::Step::FindThumbnailToRender] = AZStd::make_shared(this); - m_steps[CommonThumbnailRenderer::Step::WaitForAssetsToLoad] = AZStd::make_shared(this); - m_steps[CommonThumbnailRenderer::Step::Capture] = AZStd::make_shared(this); - SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + m_steps[CommonPreviewRenderer::State::IdleState] = AZStd::make_shared(this); + m_steps[CommonPreviewRenderer::State::LoadState] = AZStd::make_shared(this); + m_steps[CommonPreviewRenderer::State::CaptureState] = AZStd::make_shared(this); + SetState(CommonPreviewRenderer::State::IdleState); } - CommonThumbnailRenderer::~CommonThumbnailRenderer() + CommonPreviewRenderer::~CommonPreviewRenderer() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); SystemTickBus::Handler::BusDisconnect(); - ThumbnailFeatureProcessorProviderBus::Handler::BusDisconnect(); + PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); - SetStep(CommonThumbnailRenderer::Step::None); + SetState(CommonPreviewRenderer::State::None); if (m_modelEntity) { @@ -146,29 +146,29 @@ namespace AZ m_frameworkScene->UnsetSubsystem(m_entityContext.get()); } - void CommonThumbnailRenderer::SetStep(Step step) + void CommonPreviewRenderer::SetState(State state) { - auto stepItr = m_steps.find(m_currentStep); + auto stepItr = m_steps.find(m_currentState); if (stepItr != m_steps.end()) { stepItr->second->Stop(); } - m_currentStep = step; + m_currentState = state; - stepItr = m_steps.find(m_currentStep); + stepItr = m_steps.find(m_currentState); if (stepItr != m_steps.end()) { stepItr->second->Start(); } } - CommonThumbnailRenderer::Step CommonThumbnailRenderer::GetStep() const + CommonPreviewRenderer::State CommonPreviewRenderer::GetState() const { - return m_currentStep; + return m_currentState; } - void CommonThumbnailRenderer::SelectThumbnail() + void CommonPreviewRenderer::SelectThumbnail() { if (!m_thumbnailInfoQueue.empty()) { @@ -176,23 +176,23 @@ namespace AZ m_currentThubnailInfo = m_thumbnailInfoQueue.front(); m_thumbnailInfoQueue.pop(); - SetStep(CommonThumbnailRenderer::Step::WaitForAssetsToLoad); + SetState(CommonPreviewRenderer::State::LoadState); } } - void CommonThumbnailRenderer::CancelThumbnail() + void CommonPreviewRenderer::CancelThumbnail() { AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( m_currentThubnailInfo.m_key, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + SetState(CommonPreviewRenderer::State::IdleState); } - void CommonThumbnailRenderer::CompleteThumbnail() + void CommonPreviewRenderer::CompleteThumbnail() { - SetStep(CommonThumbnailRenderer::Step::FindThumbnailToRender); + SetState(CommonPreviewRenderer::State::IdleState); } - void CommonThumbnailRenderer::LoadAssets() + void CommonPreviewRenderer::LoadAssets() { // Determine if thumbnailkey contains a material asset or set a default material const Data::AssetId materialAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::MaterialAsset::RTTI_Type()); @@ -207,11 +207,11 @@ namespace AZ m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, true); } - void CommonThumbnailRenderer::UpdateLoadAssets() + void CommonPreviewRenderer::UpdateLoadAssets() { if (m_materialAsset.IsReady() && m_modelAsset.IsReady() && m_lightingPresetAsset.IsReady()) { - SetStep(CommonThumbnailRenderer::Step::Capture); + SetState(CommonPreviewRenderer::State::CaptureState); return; } @@ -222,28 +222,28 @@ namespace AZ } } - void CommonThumbnailRenderer::CancelLoadAssets() + void CommonPreviewRenderer::CancelLoadAssets() { AZ_Warning( - "CommonThumbnailRenderer", m_materialAsset.IsReady(), "Asset failed to load in time: %s", + "CommonPreviewRenderer", m_materialAsset.IsReady(), "Asset failed to load in time: %s", m_materialAsset.ToString().c_str()); AZ_Warning( - "CommonThumbnailRenderer", m_modelAsset.IsReady(), "Asset failed to load in time: %s", + "CommonPreviewRenderer", m_modelAsset.IsReady(), "Asset failed to load in time: %s", m_modelAsset.ToString().c_str()); AZ_Warning( - "CommonThumbnailRenderer", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", + "CommonPreviewRenderer", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", m_lightingPresetAsset.ToString().c_str()); CancelThumbnail(); } - void CommonThumbnailRenderer::UpdateScene() + void CommonPreviewRenderer::UpdateScene() { UpdateModel(); UpdateLighting(); UpdateCamera(); } - void CommonThumbnailRenderer::UpdateModel() + void CommonPreviewRenderer::UpdateModel() { Render::MaterialComponentRequestBus::Event( m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, @@ -253,7 +253,7 @@ namespace AZ m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); } - void CommonThumbnailRenderer::UpdateLighting() + void CommonPreviewRenderer::UpdateLighting() { auto preset = m_lightingPresetAsset->GetDataAs(); if (preset) @@ -283,7 +283,7 @@ namespace AZ } } - void CommonThumbnailRenderer::UpdateCamera() + void CommonPreviewRenderer::UpdateCamera() { // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it Vector3 center = {}; @@ -297,7 +297,7 @@ namespace AZ m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); } - RPI::AttachmentReadback::CallbackFunction CommonThumbnailRenderer::GetCaptureCallback() + RPI::AttachmentReadback::CallbackFunction CommonPreviewRenderer::GetCaptureCallback() { return [this](const RPI::AttachmentReadback::ReadbackResult& result) { @@ -320,7 +320,7 @@ namespace AZ }; } - bool CommonThumbnailRenderer::StartCapture() + bool CommonPreviewRenderer::StartCapture() { if (auto renderToTexturePass = azrtti_cast(m_renderPipeline->GetRootPass().get())) { @@ -336,22 +336,22 @@ namespace AZ return startedCapture; } - void CommonThumbnailRenderer::EndCapture() + void CommonPreviewRenderer::EndCapture() { m_renderPipeline->RemoveFromRenderTick(); } - bool CommonThumbnailRenderer::Installed() const + bool CommonPreviewRenderer::Installed() const { return true; } - void CommonThumbnailRenderer::OnSystemTick() + void CommonPreviewRenderer::OnSystemTick() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); } - void CommonThumbnailRenderer::GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const + void CommonPreviewRenderer::GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const { featureProcessors.insert({ "AZ::Render::TransformServiceFeatureProcessor", @@ -373,7 +373,7 @@ namespace AZ "AZ::Render::SkyBoxFeatureProcessor" }); } - void CommonThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) + void CommonPreviewRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) { m_thumbnailInfoQueue.push({ thumbnailKey, thumbnailSize }); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h index 2b1ccbd4e6..259063cfdf 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include #include @@ -37,30 +37,30 @@ namespace AZ { namespace Thumbnails { - class ThumbnailRendererStep; + class CommonPreviewRendererState; //! Provides custom rendering of material and model thumbnails - class CommonThumbnailRenderer + class CommonPreviewRenderer : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler , public SystemTickBus::Handler - , public ThumbnailFeatureProcessorProviderBus::Handler + , public PreviewerFeatureProcessorProviderBus::Handler { public: - AZ_CLASS_ALLOCATOR(CommonThumbnailRenderer, AZ::SystemAllocator, 0) + AZ_CLASS_ALLOCATOR(CommonPreviewRenderer, AZ::SystemAllocator, 0) - CommonThumbnailRenderer(); - ~CommonThumbnailRenderer(); + CommonPreviewRenderer(); + ~CommonPreviewRenderer(); - enum class Step : AZ::s8 + enum class State : AZ::s8 { None, - FindThumbnailToRender, - WaitForAssetsToLoad, - Capture + IdleState, + LoadState, + CaptureState }; - void SetStep(Step step); - Step GetStep() const; + void SetState(State state); + State GetState() const; void SelectThumbnail(); void CancelThumbnail(); @@ -87,8 +87,8 @@ namespace AZ //! SystemTickBus::Handler interface overrides... void OnSystemTick() override; - //! Render::ThumbnailFeatureProcessorProviderBus::Handler interface overrides... - void GetCustomFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; + //! Render::PreviewerFeatureProcessorProviderBus::Handler interface overrides... + void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; static constexpr float AspectRatio = 1.0f; static constexpr float NearDist = 0.001f; @@ -114,8 +114,8 @@ namespace AZ AZStd::queue m_thumbnailInfoQueue; ThumbnailInfo m_currentThubnailInfo; - AZStd::unordered_map> m_steps; - Step m_currentStep = CommonThumbnailRenderer::Step::None; + AZStd::unordered_map> m_steps; + State m_currentState = CommonPreviewRenderer::State::None; static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp index 0686ffb971..e77b9709ac 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp @@ -6,8 +6,8 @@ * */ -#include -#include +#include +#include namespace AZ { @@ -15,26 +15,26 @@ namespace AZ { namespace Thumbnails { - CaptureStep::CaptureStep(CommonThumbnailRenderer* renderer) - : ThumbnailRendererStep(renderer) + CommonPreviewRendererCaptureState::CommonPreviewRendererCaptureState(CommonPreviewRenderer* renderer) + : CommonPreviewRendererState(renderer) { } - void CaptureStep::Start() + void CommonPreviewRendererCaptureState::Start() { m_ticksToCapture = 1; m_renderer->UpdateScene(); TickBus::Handler::BusConnect(); } - void CaptureStep::Stop() + void CommonPreviewRendererCaptureState::Stop() { m_renderer->EndCapture(); TickBus::Handler::BusDisconnect(); Render::FrameCaptureNotificationBus::Handler::BusDisconnect(); } - void CaptureStep::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) + void CommonPreviewRendererCaptureState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) { if (m_ticksToCapture-- <= 0) { @@ -47,7 +47,7 @@ namespace AZ } } - void CaptureStep::OnCaptureFinished( + void CommonPreviewRendererCaptureState::OnCaptureFinished( [[maybe_unused]] Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) { m_renderer->CompleteThumbnail(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h index 46d642ce53..c19f12d9bb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { @@ -18,14 +18,14 @@ namespace AZ { namespace Thumbnails { - //! CaptureStep renders a thumbnail to a pixmap and notifies MaterialOrModelThumbnail once finished - class CaptureStep - : public ThumbnailRendererStep + //! CommonPreviewRendererCaptureState renders a thumbnail to a pixmap and notifies MaterialOrModelThumbnail once finished + class CommonPreviewRendererCaptureState + : public CommonPreviewRendererState , private TickBus::Handler , private Render::FrameCaptureNotificationBus::Handler { public: - CaptureStep(CommonThumbnailRenderer* renderer); + CommonPreviewRendererCaptureState(CommonPreviewRenderer* renderer); void Start() override; void Stop() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp index d9c978605a..b272faef30 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp @@ -6,8 +6,8 @@ * */ -#include -#include +#include +#include namespace AZ { @@ -15,22 +15,22 @@ namespace AZ { namespace Thumbnails { - FindThumbnailToRenderStep::FindThumbnailToRenderStep(CommonThumbnailRenderer* renderer) - : ThumbnailRendererStep(renderer) + CommonPreviewRendererIdleState::CommonPreviewRendererIdleState(CommonPreviewRenderer* renderer) + : CommonPreviewRendererState(renderer) { } - void FindThumbnailToRenderStep::Start() + void CommonPreviewRendererIdleState::Start() { TickBus::Handler::BusConnect(); } - void FindThumbnailToRenderStep::Stop() + void CommonPreviewRendererIdleState::Stop() { TickBus::Handler::BusDisconnect(); } - void FindThumbnailToRenderStep::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) + void CommonPreviewRendererIdleState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) { m_renderer->SelectThumbnail(); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h index 6ba9b974a1..3278149b98 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h @@ -8,7 +8,7 @@ #pragma once -#include +#include namespace AZ { @@ -16,13 +16,13 @@ namespace AZ { namespace Thumbnails { - //! FindThumbnailToRenderStep checks whether there are any new thumbnails that need to be rendered every tick - class FindThumbnailToRenderStep - : public ThumbnailRendererStep + //! CommonPreviewRendererIdleState checks whether there are any new thumbnails that need to be rendered every tick + class CommonPreviewRendererIdleState + : public CommonPreviewRendererState , private TickBus::Handler { public: - FindThumbnailToRenderStep(CommonThumbnailRenderer* renderer); + CommonPreviewRendererIdleState(CommonPreviewRenderer* renderer); void Start() override; void Stop() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp index 53a5b596d4..dcac673de2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp @@ -6,10 +6,8 @@ * */ -#include "Thumbnails/ThumbnailerBus.h" -#include -#include -#include +#include +#include namespace AZ { @@ -17,24 +15,24 @@ namespace AZ { namespace Thumbnails { - WaitForAssetsToLoadStep::WaitForAssetsToLoadStep(CommonThumbnailRenderer* renderer) - : ThumbnailRendererStep(renderer) + CommonPreviewRendererLoadState::CommonPreviewRendererLoadState(CommonPreviewRenderer* renderer) + : CommonPreviewRendererState(renderer) { } - void WaitForAssetsToLoadStep::Start() + void CommonPreviewRendererLoadState::Start() { m_renderer->LoadAssets(); m_timeRemainingS = TimeOutS; TickBus::Handler::BusConnect(); } - void WaitForAssetsToLoadStep::Stop() + void CommonPreviewRendererLoadState::Stop() { TickBus::Handler::BusDisconnect(); } - void WaitForAssetsToLoadStep::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + void CommonPreviewRendererLoadState::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { m_timeRemainingS -= deltaTime; if (m_timeRemainingS > 0.0f) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h index 0202ef1045..438fd774ca 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h @@ -8,7 +8,8 @@ #pragma once -#include +#include +#include namespace AZ { @@ -16,13 +17,13 @@ namespace AZ { namespace Thumbnails { - //! WaitForAssetsToLoadStep pauses further rendering until all assets used for rendering a thumbnail have been loaded - class WaitForAssetsToLoadStep - : public ThumbnailRendererStep + //! CommonPreviewRendererLoadState pauses further rendering until all assets used for rendering a thumbnail have been loaded + class CommonPreviewRendererLoadState + : public CommonPreviewRendererState , private TickBus::Handler { public: - WaitForAssetsToLoadStep(CommonThumbnailRenderer* renderer); + CommonPreviewRendererLoadState(CommonPreviewRenderer* renderer); void Start() override; void Stop() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h index 0a629e7e25..9dbf50ab0e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h @@ -14,22 +14,22 @@ namespace AZ { namespace Thumbnails { - class CommonThumbnailRenderer; + class CommonPreviewRenderer; - //! ThumbnailRendererStep decouples CommonThumbnailRenderer logic into easy-to-understand and debug pieces - class ThumbnailRendererStep + //! CommonPreviewRendererState decouples CommonPreviewRenderer logic into easy-to-understand and debug pieces + class CommonPreviewRendererState { public: - explicit ThumbnailRendererStep(CommonThumbnailRenderer* renderer) : m_renderer(renderer) {} - virtual ~ThumbnailRendererStep() = default; + explicit CommonPreviewRendererState(CommonPreviewRenderer* renderer) : m_renderer(renderer) {} + virtual ~CommonPreviewRendererState() = default; - //! Start is called when step begins execution + //! Start is called when state begins execution virtual void Start() {} - //! Stop is called when step ends execution + //! Stop is called when state ends execution virtual void Stop() {} protected: - CommonThumbnailRenderer* m_renderer; + CommonPreviewRenderer* m_renderer; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index ffc3f257b0..e96f199f5e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -9,7 +9,7 @@ set(FILES Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h - Include/AtomLyIntegration/CommonFeatures/Thumbnails/ThumbnailFeatureProcessorProviderBus.h + Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h Source/Module.cpp Source/Animation/EditorAttachmentComponent.h Source/Animation/EditorAttachmentComponent.cpp @@ -102,15 +102,15 @@ set(FILES Source/Thumbnails/Preview/CommonPreviewer.ui Source/Thumbnails/Preview/CommonPreviewerFactory.cpp Source/Thumbnails/Preview/CommonPreviewerFactory.h - Source/Thumbnails/Rendering/CommonThumbnailRenderer.cpp - Source/Thumbnails/Rendering/CommonThumbnailRenderer.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/ThumbnailRendererStep.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.cpp - Source/Thumbnails/Rendering/ThumbnailRendererSteps/FindThumbnailToRenderStep.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.cpp - Source/Thumbnails/Rendering/ThumbnailRendererSteps/WaitForAssetsToLoadStep.h - Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.cpp - Source/Thumbnails/Rendering/ThumbnailRendererSteps/CaptureStep.h + Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp + Source/Thumbnails/Rendering/CommonPreviewRenderer.h + Source/Thumbnails/Rendering/CommonPreviewRendererState.h + Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp + Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h + Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp + Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h + Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp + Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From f43b3b9fbefa56b0500da096b900809c0dedeb23 Mon Sep 17 00:00:00 2001 From: Mikhail Naumov Date: Thu, 7 Oct 2021 20:35:23 -0500 Subject: [PATCH 04/52] Fixing crash creating new level when simulate mode is on Signed-off-by: Mikhail Naumov --- Code/Editor/CryEdit.cpp | 10 ++++++++++ .../AzFramework/Spawnable/RootSpawnableInterface.h | 4 ++++ .../AzFramework/Spawnable/SpawnableSystemComponent.cpp | 9 +++++++-- .../AzFramework/Spawnable/SpawnableSystemComponent.h | 1 + 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 4aa3d22114..d2a448bd34 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -57,6 +57,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include // AzToolsFramework #include @@ -3019,6 +3020,15 @@ CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelNam bool bIsDocModified = GetIEditor()->GetDocument()->IsModified(); OnSwitchPhysics(); GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified); + + if (usePrefabSystemForLevels) + { + auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get(); + if (rootSpawnableInterface) + { + rootSpawnableInterface->ProcessSpawnableQueue(); + } + } } const QScopedValueRollback rollback(m_creatingNewLevel); diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/RootSpawnableInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/RootSpawnableInterface.h index bb1f137ba2..72a3031e3e 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/RootSpawnableInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/RootSpawnableInterface.h @@ -61,6 +61,10 @@ namespace AzFramework //! be deleted and the spawnable asset to be released. This call is automatically done when //! AssignRootSpawnable is called while a root spawnable is assigned. virtual void ReleaseRootSpawnable() = 0; + //! Force processing all SpawnableEntitiesManager requests immediately + //! This is useful when loading a different level while SpawnableEntitiesManager still has + //! pending requests + virtual void ProcessSpawnableQueue() = 0; }; using RootSpawnableInterface = AZ::Interface; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp index f6130c9e31..af41fdd6ba 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp @@ -45,8 +45,7 @@ namespace AzFramework void SpawnableSystemComponent::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) { - m_entitiesManager.ProcessQueue( - SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular); + ProcessSpawnableQueue(); RootSpawnableNotificationBus::ExecuteQueuedEvents(); } @@ -121,6 +120,12 @@ namespace AzFramework m_rootSpawnableId = AZ::Data::AssetId(); } + void SpawnableSystemComponent::ProcessSpawnableQueue() + { + m_entitiesManager.ProcessQueue( + SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular); + } + void SpawnableSystemComponent::OnRootSpawnableAssigned([[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h index 5b5fb1b7ee..74e255d624 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.h @@ -75,6 +75,7 @@ namespace AzFramework uint64_t AssignRootSpawnable(AZ::Data::Asset rootSpawnable) override; void ReleaseRootSpawnable() override; + void ProcessSpawnableQueue() override; // // RootSpawnbleNotificationBus From c90e1da475db44d2cd9be82a5cef7d832dabdc6e Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Thu, 7 Oct 2021 21:05:10 -0500 Subject: [PATCH 05/52] =?UTF-8?q?=E2=80=A2=20Moved=20everything=20related?= =?UTF-8?q?=20to=20the=20subject=20being=20captured=20by=20the=20preview?= =?UTF-8?q?=20renderer=20into=20a=20preview=20render=20content=20class=20w?= =?UTF-8?q?hich=20will=20become=20an=20interface=20in=20the=20next=20itera?= =?UTF-8?q?tion=20=E2=80=A2=20Extracted=20all=20of=20the=20thumbnail=20spe?= =?UTF-8?q?cific=20code=20from=20the=20common=20preview=20render=20class?= =?UTF-8?q?=20as=20a=20step=20towards=20separating=20it=20from=20the=20thu?= =?UTF-8?q?mbnail=20system=20completely=20=E2=80=A2=20Created=20a=20captur?= =?UTF-8?q?e=20request=20structure=20that=20stores=20all=20of=20the=20info?= =?UTF-8?q?=20related=20to=20the=20content=20being=20captured=20and=20call?= =?UTF-8?q?backs=20for=20success=20and=20failure=20=E2=80=A2=20Request=20t?= =?UTF-8?q?o=20capture=20any=20kind=20of=20content=20can=20be=20added=20to?= =?UTF-8?q?=20the=20renderer=20using=20this=20structure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Guthrie Adams --- .../PreviewerFeatureProcessorProviderBus.h | 4 +- .../Rendering/CommonPreviewContent.cpp | 170 +++++++++++++ .../Rendering/CommonPreviewContent.h | 79 ++++++ .../Rendering/CommonPreviewRenderer.cpp | 239 ++++++------------ .../Rendering/CommonPreviewRenderer.h | 67 ++--- .../CommonPreviewRendererCaptureState.cpp | 2 +- .../CommonPreviewRendererIdleState.cpp | 2 +- ...egration_commonfeatures_editor_files.cmake | 2 + 8 files changed, 349 insertions(+), 216 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h index ef0e586348..bae49db89d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h @@ -16,14 +16,14 @@ namespace AZ { namespace Thumbnails { - //! PreviewerFeatureProcessorProviderRequests allows registering custom Feature Processors for thumbnail generation + //! PreviewerFeatureProcessorProviderRequests allows registering custom Feature Processors for preview image generation //! Duplicates will be ignored //! You can check minimal feature processors that are already registered in CommonPreviewRenderer.cpp class PreviewerFeatureProcessorProviderRequests : public AZ::EBusTraits { public: - //! Get a list of custom feature processors to register with thumbnail renderer + //! Get a list of custom feature processors to register with preview image renderer virtual void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; }; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp new file mode 100644 index 0000000000..12caac1e90 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + CommonPreviewContent::CommonPreviewContent( + RPI::ScenePtr scene, + RPI::ViewPtr view, + AZ::Uuid entityContextId, + const Data::AssetId& modelAssetId, + const Data::AssetId& materialAssetId, + const Data::AssetId& lightingPresetAssetId) + : m_scene(scene) + , m_view(view) + , m_entityContextId(entityContextId) + { + // Connect camera to pipeline's default view after camera entity activated + Matrix4x4 viewToClipMatrix; + MakePerspectiveFovMatrixRH(viewToClipMatrix, FieldOfView, AspectRatio, NearDist, FarDist, true); + m_view->SetViewToClipMatrix(viewToClipMatrix); + + // Create preview model + AzFramework::EntityContextRequestBus::EventResult( + m_modelEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ThumbnailPreviewModel"); + m_modelEntity->CreateComponent(Render::MeshComponentTypeId); + m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); + m_modelEntity->CreateComponent(azrtti_typeid()); + m_modelEntity->Init(); + m_modelEntity->Activate(); + + m_defaultModelAsset.Create(DefaultModelAssetId, true); + m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); + m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + + m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, false); + m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, false); + m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, false); + } + + CommonPreviewContent::~CommonPreviewContent() + { + if (m_modelEntity) + { + AzFramework::EntityContextRequestBus::Event( + m_entityContextId, &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); + m_modelEntity = nullptr; + } + } + + void CommonPreviewContent::Load() + { + m_modelAsset.QueueLoad(); + m_materialAsset.QueueLoad(); + m_lightingPresetAsset.QueueLoad(); + } + + bool CommonPreviewContent::IsReady() const + { + return m_modelAsset.IsReady() && m_materialAsset.IsReady() && m_lightingPresetAsset.IsReady(); + } + + bool CommonPreviewContent::IsError() const + { + return m_modelAsset.IsError() || m_materialAsset.IsError() || m_lightingPresetAsset.IsError(); + } + + void CommonPreviewContent::ReportErrors() + { + AZ_Warning( + "CommonPreviewContent", m_modelAsset.IsReady(), "Asset failed to load in time: %s", + m_modelAsset.ToString().c_str()); + AZ_Warning( + "CommonPreviewContent", m_materialAsset.IsReady(), "Asset failed to load in time: %s", + m_materialAsset.ToString().c_str()); + AZ_Warning( + "CommonPreviewContent", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", + m_lightingPresetAsset.ToString().c_str()); + } + + void CommonPreviewContent::UpdateScene() + { + UpdateModel(); + UpdateLighting(); + UpdateCamera(); + } + + void CommonPreviewContent::UpdateModel() + { + Render::MeshComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); + + Render::MaterialComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, + m_materialAsset.GetId()); + } + + void CommonPreviewContent::UpdateLighting() + { + auto preset = m_lightingPresetAsset->GetDataAs(); + if (preset) + { + auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); + auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); + auto directionalLightFeatureProcessor = + m_scene->GetFeatureProcessor(); + auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); + skyboxFeatureProcessor->Enable(true); + skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); + + Camera::Configuration cameraConfig; + cameraConfig.m_fovRadians = FieldOfView; + cameraConfig.m_nearClipDistance = NearDist; + cameraConfig.m_farClipDistance = FarDist; + cameraConfig.m_frustumWidth = 100.0f; + cameraConfig.m_frustumHeight = 100.0f; + + AZStd::vector lightHandles; + + preset->ApplyLightingPreset( + iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, + cameraConfig, lightHandles); + } + } + + void CommonPreviewContent::UpdateCamera() + { + // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it + Vector3 center = {}; + float radius = {}; + m_modelAsset->GetAabb().GetAsSphere(center, radius); + + const auto distance = radius + NearDist; + const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); + const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); + const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); + m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); + } + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h new file mode 100644 index 0000000000..6c8f0c5565 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + //! Provides custom rendering of material and model thumbnails + class CommonPreviewContent + { + public: + AZ_CLASS_ALLOCATOR(CommonPreviewContent, AZ::SystemAllocator, 0); + + CommonPreviewContent( + RPI::ScenePtr scene, + RPI::ViewPtr view, + AZ::Uuid entityContextId, + const Data::AssetId& modelAssetId, + const Data::AssetId& materialAssetId, + const Data::AssetId& lightingPresetAssetId); + ~CommonPreviewContent(); + + void Load(); + bool IsReady() const; + bool IsError() const; + void ReportErrors(); + void UpdateScene(); + + private: + void UpdateModel(); + void UpdateLighting(); + void UpdateCamera(); + + static constexpr float AspectRatio = 1.0f; + static constexpr float NearDist = 0.001f; + static constexpr float FarDist = 100.0f; + static constexpr float FieldOfView = Constants::HalfPi; + static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; + + RPI::ScenePtr m_scene; + RPI::ViewPtr m_view; + AZ::Uuid m_entityContextId; + Entity* m_modelEntity = nullptr; + + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; + Data::Asset m_lightingPresetAsset; + + //! Model asset about to be rendered + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; + Data::Asset m_modelAsset; + + //! Material asset about to be rendered + static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; + const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); + Data::Asset m_defaultMaterialAsset; + Data::Asset m_materialAsset; + }; + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp index b24de64b42..37a9bab378 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp @@ -6,33 +6,17 @@ * */ -#include -#include -#include #include -#include #include #include #include #include #include #include -#include -#include -#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include #include #include -#include #include #include #include @@ -51,8 +35,7 @@ namespace AZ { CommonPreviewRenderer::CommonPreviewRenderer() { - // CommonPreviewRenderer supports both models and materials, but we connect on materialAssetType - // since MaterialOrModelThumbnail dispatches event on materialAssetType address too + // CommonPreviewRenderer supports both models and materials AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); @@ -72,7 +55,7 @@ namespace AZ // Bind m_frameworkScene to the entity context's AzFramework::Scene auto sceneSystem = AzFramework::SceneSystemInterface::Get(); - AZ_Assert(sceneSystem, "Thumbnail system failed to get scene system implementation."); + AZ_Assert(sceneSystem, "Failed to get scene system implementation."); Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(m_sceneName); AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); @@ -104,23 +87,9 @@ namespace AZ m_view->SetViewToClipMatrix(viewToClipMatrix); m_renderPipeline->SetDefaultView(m_view); - // Create preview model - AzFramework::EntityContextRequestBus::EventResult( - m_modelEntity, m_entityContext->GetContextId(), &AzFramework::EntityContextRequestBus::Events::CreateEntity, - "ThumbnailPreviewModel"); - m_modelEntity->CreateComponent(Render::MeshComponentTypeId); - m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); - m_modelEntity->CreateComponent(azrtti_typeid()); - m_modelEntity->Init(); - m_modelEntity->Activate(); - - m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); - m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); - m_defaultModelAsset.Create(DefaultModelAssetId, true); - - m_steps[CommonPreviewRenderer::State::IdleState] = AZStd::make_shared(this); - m_steps[CommonPreviewRenderer::State::LoadState] = AZStd::make_shared(this); - m_steps[CommonPreviewRenderer::State::CaptureState] = AZStd::make_shared(this); + m_states[CommonPreviewRenderer::State::IdleState] = AZStd::make_shared(this); + m_states[CommonPreviewRenderer::State::LoadState] = AZStd::make_shared(this); + m_states[CommonPreviewRenderer::State::CaptureState] = AZStd::make_shared(this); SetState(CommonPreviewRenderer::State::IdleState); } @@ -131,13 +100,8 @@ namespace AZ PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); SetState(CommonPreviewRenderer::State::None); - - if (m_modelEntity) - { - AzFramework::EntityContextRequestBus::Event( - m_entityContext->GetContextId(), &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); - m_modelEntity = nullptr; - } + m_currentCaptureRequest = {}; + m_captureRequestQueue = {}; m_scene->Deactivate(); m_scene->RemoveRenderPipeline(m_renderPipeline->GetId()); @@ -146,18 +110,23 @@ namespace AZ m_frameworkScene->UnsetSubsystem(m_entityContext.get()); } + void CommonPreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) + { + m_captureRequestQueue.push(captureRequest); + } + void CommonPreviewRenderer::SetState(State state) { - auto stepItr = m_steps.find(m_currentState); - if (stepItr != m_steps.end()) + auto stepItr = m_states.find(m_currentState); + if (stepItr != m_states.end()) { stepItr->second->Stop(); } m_currentState = state; - stepItr = m_steps.find(m_currentState); - if (stepItr != m_steps.end()) + stepItr = m_states.find(m_currentState); + if (stepItr != m_states.end()) { stepItr->second->Start(); } @@ -168,54 +137,43 @@ namespace AZ return m_currentState; } - void CommonPreviewRenderer::SelectThumbnail() + void CommonPreviewRenderer::SelectCaptureRequest() { - if (!m_thumbnailInfoQueue.empty()) + if (!m_captureRequestQueue.empty()) { - // pop the next thumbnailkey to be rendered from the queue - m_currentThubnailInfo = m_thumbnailInfoQueue.front(); - m_thumbnailInfoQueue.pop(); + // pop the next request to be rendered from the queue + m_currentCaptureRequest = m_captureRequestQueue.front(); + m_captureRequestQueue.pop(); SetState(CommonPreviewRenderer::State::LoadState); } } - void CommonPreviewRenderer::CancelThumbnail() + void CommonPreviewRenderer::CancelCaptureRequest() { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_currentThubnailInfo.m_key, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + m_currentCaptureRequest.m_captureFailedCallback(); SetState(CommonPreviewRenderer::State::IdleState); } - void CommonPreviewRenderer::CompleteThumbnail() + void CommonPreviewRenderer::CompleteCaptureRequest() { SetState(CommonPreviewRenderer::State::IdleState); } void CommonPreviewRenderer::LoadAssets() { - // Determine if thumbnailkey contains a material asset or set a default material - const Data::AssetId materialAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::MaterialAsset::RTTI_Type()); - m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, true); - - // Determine if thumbnailkey contains a model asset or set a default model - const Data::AssetId modelAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::ModelAsset::RTTI_Type()); - m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, true); - - // Determine if thumbnailkey contains a lighting preset asset or set a default lighting preset - const Data::AssetId lightingPresetAssetId = GetAssetId(m_currentThubnailInfo.m_key, RPI::AnyAsset::RTTI_Type()); - m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, true); + m_currentCaptureRequest.m_content->Load(); } void CommonPreviewRenderer::UpdateLoadAssets() { - if (m_materialAsset.IsReady() && m_modelAsset.IsReady() && m_lightingPresetAsset.IsReady()) + if (m_currentCaptureRequest.m_content->IsReady()) { SetState(CommonPreviewRenderer::State::CaptureState); return; } - if (m_materialAsset.IsError() || m_modelAsset.IsError() || m_lightingPresetAsset.IsError()) + if (m_currentCaptureRequest.m_content->IsError()) { CancelLoadAssets(); return; @@ -224,107 +182,35 @@ namespace AZ void CommonPreviewRenderer::CancelLoadAssets() { - AZ_Warning( - "CommonPreviewRenderer", m_materialAsset.IsReady(), "Asset failed to load in time: %s", - m_materialAsset.ToString().c_str()); - AZ_Warning( - "CommonPreviewRenderer", m_modelAsset.IsReady(), "Asset failed to load in time: %s", - m_modelAsset.ToString().c_str()); - AZ_Warning( - "CommonPreviewRenderer", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", - m_lightingPresetAsset.ToString().c_str()); - CancelThumbnail(); + m_currentCaptureRequest.m_content->ReportErrors(); + CancelCaptureRequest(); } void CommonPreviewRenderer::UpdateScene() { - UpdateModel(); - UpdateLighting(); - UpdateCamera(); - } - - void CommonPreviewRenderer::UpdateModel() - { - Render::MaterialComponentRequestBus::Event( - m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, - m_materialAsset.GetId()); - - Render::MeshComponentRequestBus::Event( - m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); - } - - void CommonPreviewRenderer::UpdateLighting() - { - auto preset = m_lightingPresetAsset->GetDataAs(); - if (preset) - { - auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); - auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); - auto directionalLightFeatureProcessor = - m_scene->GetFeatureProcessor(); - auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); - skyboxFeatureProcessor->Enable(true); - skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); - - Camera::Configuration cameraConfig; - cameraConfig.m_fovRadians = FieldOfView; - cameraConfig.m_nearClipDistance = NearDist; - cameraConfig.m_farClipDistance = FarDist; - cameraConfig.m_frustumWidth = 100.0f; - cameraConfig.m_frustumHeight = 100.0f; - - AZStd::vector lightHandles; - - preset->ApplyLightingPreset( - iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, - cameraConfig, lightHandles); - } - } - - void CommonPreviewRenderer::UpdateCamera() - { - // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it - Vector3 center = {}; - float radius = {}; - m_modelAsset->GetAabb().GetAsSphere(center, radius); - - const auto distance = radius + NearDist; - const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); - const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); - const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); - m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); - } - - RPI::AttachmentReadback::CallbackFunction CommonPreviewRenderer::GetCaptureCallback() - { - return [this](const RPI::AttachmentReadback::ReadbackResult& result) - { - if (result.m_dataBuffer) - { - QImage image( - result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, - result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888); - - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_currentThubnailInfo.m_key, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, QPixmap::fromImage(image)); - } - else - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - m_currentThubnailInfo.m_key, - &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - } - }; + m_currentCaptureRequest.m_content->UpdateScene(); } bool CommonPreviewRenderer::StartCapture() { + auto captureCallback = + [currentCaptureRequest = m_currentCaptureRequest](const RPI::AttachmentReadback::ReadbackResult& result) + { + if (result.m_dataBuffer) + { + currentCaptureRequest.m_captureCompleteCallback(QImage( + result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, + result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888)); + } + else + { + currentCaptureRequest.m_captureFailedCallback(); + } + }; + if (auto renderToTexturePass = azrtti_cast(m_renderPipeline->GetRootPass().get())) { - renderToTexturePass->ResizeOutput(m_currentThubnailInfo.m_size, m_currentThubnailInfo.m_size); + renderToTexturePass->ResizeOutput(m_currentCaptureRequest.m_size, m_currentCaptureRequest.m_size); } m_renderPipeline->AddToRenderTickOnce(); @@ -332,7 +218,7 @@ namespace AZ bool startedCapture = false; Render::FrameCaptureRequestBus::BroadcastResult( startedCapture, &Render::FrameCaptureRequestBus::Events::CapturePassAttachmentWithCallback, m_passHierarchy, - AZStd::string("Output"), GetCaptureCallback(), RPI::PassAttachmentReadbackOption::Output); + AZStd::string("Output"), captureCallback, RPI::PassAttachmentReadbackOption::Output); return startedCapture; } @@ -341,11 +227,6 @@ namespace AZ m_renderPipeline->RemoveFromRenderTick(); } - bool CommonPreviewRenderer::Installed() const - { - return true; - } - void CommonPreviewRenderer::OnSystemTick() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); @@ -372,10 +253,32 @@ namespace AZ "AZ::Render::PostProcessFeatureProcessor", "AZ::Render::SkyBoxFeatureProcessor" }); } - + void CommonPreviewRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) { - m_thumbnailInfoQueue.push({ thumbnailKey, thumbnailSize }); + AddCaptureRequest( + { thumbnailSize, + AZStd::make_shared( + m_scene, m_view, m_entityContext->GetContextId(), + GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type()), + GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type()), + GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type())), + [thumbnailKey]() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + }, + [thumbnailKey](const QImage& image) + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, + QPixmap::fromImage(image)); + } }); + } + + bool CommonPreviewRenderer::Installed() const + { + return true; } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h index 259063cfdf..124a6987cc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h @@ -10,13 +10,11 @@ #include #include -#include -#include -#include #include #include #include #include +#include #include namespace AzFramework @@ -46,11 +44,21 @@ namespace AZ , public PreviewerFeatureProcessorProviderBus::Handler { public: - AZ_CLASS_ALLOCATOR(CommonPreviewRenderer, AZ::SystemAllocator, 0) + AZ_CLASS_ALLOCATOR(CommonPreviewRenderer, AZ::SystemAllocator, 0); CommonPreviewRenderer(); ~CommonPreviewRenderer(); + struct CaptureRequest + { + int m_size = 512; + AZStd::shared_ptr m_content; + AZStd::function m_captureFailedCallback; + AZStd::function m_captureCompleteCallback; + }; + + void AddCaptureRequest(const CaptureRequest& captureRequest); + enum class State : AZ::s8 { None, @@ -62,39 +70,34 @@ namespace AZ void SetState(State state); State GetState() const; - void SelectThumbnail(); - void CancelThumbnail(); - void CompleteThumbnail(); + void SelectCaptureRequest(); + void CancelCaptureRequest(); + void CompleteCaptureRequest(); void LoadAssets(); void UpdateLoadAssets(); void CancelLoadAssets(); void UpdateScene(); - void UpdateModel(); - void UpdateLighting(); - void UpdateCamera(); - RPI::AttachmentReadback::CallbackFunction GetCaptureCallback(); bool StartCapture(); void EndCapture(); private: - //! ThumbnailerRendererRequestsBus::Handler interface overrides... - void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; - bool Installed() const override; - //! SystemTickBus::Handler interface overrides... void OnSystemTick() override; //! Render::PreviewerFeatureProcessorProviderBus::Handler interface overrides... void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; + //! ThumbnailerRendererRequestsBus::Handler interface overrides... + void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; + bool Installed() const override; + static constexpr float AspectRatio = 1.0f; static constexpr float NearDist = 0.001f; static constexpr float FarDist = 100.0f; static constexpr float FieldOfView = Constants::HalfPi; - static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; RPI::ScenePtr m_scene; AZStd::string m_sceneName = "Material Thumbnail Scene"; @@ -105,36 +108,12 @@ namespace AZ AZStd::vector m_passHierarchy; AZStd::unique_ptr m_entityContext; - //! Incoming thumbnail requests are appended to this queue and processed one at a time in OnTick function. - struct ThumbnailInfo - { - AzToolsFramework::Thumbnailer::SharedThumbnailKey m_key; - int m_size = 512; - }; - AZStd::queue m_thumbnailInfoQueue; - ThumbnailInfo m_currentThubnailInfo; + //! Incoming requests are appended to this queue and processed one at a time in OnTick function. + AZStd::queue m_captureRequestQueue; + CaptureRequest m_currentCaptureRequest; - AZStd::unordered_map> m_steps; + AZStd::unordered_map> m_states; State m_currentState = CommonPreviewRenderer::State::None; - - static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); - Data::Asset m_defaultLightingPresetAsset; - Data::Asset m_lightingPresetAsset; - - //! Model asset about to be rendered - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); - Data::Asset m_defaultModelAsset; - Data::Asset m_modelAsset; - - //! Material asset about to be rendered - static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; - const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); - Data::Asset m_defaultMaterialAsset; - Data::Asset m_materialAsset; - - Entity* m_modelEntity = nullptr; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp index e77b9709ac..fc74e9f43b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp @@ -50,7 +50,7 @@ namespace AZ void CommonPreviewRendererCaptureState::OnCaptureFinished( [[maybe_unused]] Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) { - m_renderer->CompleteThumbnail(); + m_renderer->CompleteCaptureRequest(); } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp index b272faef30..12a38fc93f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp @@ -32,7 +32,7 @@ namespace AZ void CommonPreviewRendererIdleState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) { - m_renderer->SelectThumbnail(); + m_renderer->SelectCaptureRequest(); } } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index e96f199f5e..f135bc1132 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -102,6 +102,8 @@ set(FILES Source/Thumbnails/Preview/CommonPreviewer.ui Source/Thumbnails/Preview/CommonPreviewerFactory.cpp Source/Thumbnails/Preview/CommonPreviewerFactory.h + Source/Thumbnails/Rendering/CommonPreviewContent.cpp + Source/Thumbnails/Rendering/CommonPreviewContent.h Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp Source/Thumbnails/Rendering/CommonPreviewRenderer.h Source/Thumbnails/Rendering/CommonPreviewRendererState.h From ab5547fdf7f694f2783647846f1b3fe2265fe569 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 8 Oct 2021 02:46:00 -0500 Subject: [PATCH 06/52] =?UTF-8?q?=E2=80=A2=20Created=20interface=20for=20p?= =?UTF-8?q?review=20rendering=20content=20=E2=80=A2=20moved=20all=20thumbn?= =?UTF-8?q?ail=20classes=20and=20registration=20back=20to=20the=20common?= =?UTF-8?q?=20feature=20editor=20component=20=E2=80=A2=20added=20lighting?= =?UTF-8?q?=20preset=20thumbnail=20as=20a=20quick=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Guthrie Adams --- .../EditorCommonFeaturesSystemComponent.cpp | 58 ++++++++- .../EditorCommonFeaturesSystemComponent.h | 13 +- .../EditorMaterialSystemComponent.cpp | 36 ------ .../Material/EditorMaterialSystemComponent.h | 10 -- .../Source/Mesh/EditorMeshSystemComponent.cpp | 41 +------ .../Source/Mesh/EditorMeshSystemComponent.h | 10 -- ....cpp => CommonThumbnailPreviewContent.cpp} | 38 +++--- .../CommonThumbnailPreviewContent.h | 82 +++++++++++++ .../Thumbnails/CommonThumbnailRenderer.cpp | 71 +++++++++++ .../Thumbnails/CommonThumbnailRenderer.h | 46 +++++++ .../Thumbnails/LightingPresetThumbnail.cpp | 115 ++++++++++++++++++ .../LightingPresetThumbnail.h} | 23 ++-- .../MaterialThumbnail.cpp | 22 ++-- .../MaterialThumbnail.h | 12 +- .../ModelThumbnail.cpp} | 51 ++++---- .../Code/Source/Thumbnails/ModelThumbnail.h | 67 ++++++++++ .../Preview/CommonPreviewerFactory.cpp | 29 ++++- .../Rendering/CommonPreviewContent.h | 62 ++-------- .../Rendering/CommonPreviewRenderer.cpp | 56 +++------ .../Rendering/CommonPreviewRenderer.h | 32 ++--- ...egration_commonfeatures_editor_files.cmake | 15 ++- 21 files changed, 576 insertions(+), 313 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/{Rendering/CommonPreviewContent.cpp => CommonThumbnailPreviewContent.cpp} (81%) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Mesh/MeshThumbnail.h => Thumbnails/LightingPresetThumbnail.h} (72%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Material => Thumbnails}/MaterialThumbnail.cpp (80%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Material => Thumbnails}/MaterialThumbnail.h (83%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Mesh/MeshThumbnail.cpp => Thumbnails/ModelThumbnail.cpp} (59%) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 0355351654..c04702ff90 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -9,12 +9,18 @@ #include #include -#include #include #include +#include +#include #include #include #include +#include + +#include +#include +#include #include @@ -68,7 +74,7 @@ namespace AZ void EditorCommonFeaturesSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - AZ_UNUSED(required); + required.push_back(AZ_CRC_CE("ThumbnailerService")); } void EditorCommonFeaturesSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) @@ -98,8 +104,7 @@ namespace AZ AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusDisconnect(); m_skinnedMeshDebugDisplay.reset(); - m_previewerFactory.reset(); - m_renderer.reset(); + TeardownThumbnails(); } void EditorCommonFeaturesSystemComponent::OnNewLevelCreated() @@ -194,8 +199,7 @@ namespace AZ void EditorCommonFeaturesSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) { AZ::TickBus::QueueFunction([this](){ - m_renderer = AZStd::make_unique(); - m_previewerFactory = AZStd::make_unique(); + SetupThumbnails(); }); } @@ -207,7 +211,49 @@ namespace AZ void EditorCommonFeaturesSystemComponent::OnApplicationAboutToStop() { + TeardownThumbnails(); + } + + void EditorCommonFeaturesSystemComponent::SetupThumbnails() + { + using namespace AzToolsFramework::Thumbnailer; + using namespace LyIntegration; + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::MaterialThumbnailCache), + ThumbnailContext::DefaultContext); + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::ModelThumbnailCache), + ThumbnailContext::DefaultContext); + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::LightingPresetThumbnailCache), + ThumbnailContext::DefaultContext); + + m_renderer = AZStd::make_unique(); + m_previewerFactory = AZStd::make_unique(); + } + + void EditorCommonFeaturesSystemComponent::TeardownThumbnails() + { + using namespace AzToolsFramework::Thumbnailer; + using namespace LyIntegration; + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::MaterialThumbnailCache::ProviderName, + ThumbnailContext::DefaultContext); + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::ModelThumbnailCache::ProviderName, + ThumbnailContext::DefaultContext); + + ThumbnailerRequestsBus::Broadcast( + &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::LightingPresetThumbnailCache::ProviderName, + ThumbnailContext::DefaultContext); + m_renderer.reset(); + m_previewerFactory.reset(); } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h index 90dc5fcf2e..ed6b3eb426 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h @@ -14,7 +14,7 @@ #include #include #include -#include +#include namespace AZ { @@ -54,18 +54,23 @@ namespace AZ void OnNewLevelCreated() override; // SliceEditorEntityOwnershipServiceBus overrides ... - void OnSliceInstantiated(const AZ::Data::AssetId&, AZ::SliceComponent::SliceInstanceAddress&, const AzFramework::SliceInstantiationTicket&) override; + void OnSliceInstantiated( + const AZ::Data::AssetId&, AZ::SliceComponent::SliceInstanceAddress&, const AzFramework::SliceInstantiationTicket&) override; void OnSliceInstantiationFailed(const AZ::Data::AssetId&, const AzFramework::SliceInstantiationTicket&) override; // AzFramework::AssetCatalogEventBus::Handler overrides ... void OnCatalogLoaded(const char* catalogFile) override; // AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler overrides... - const AzToolsFramework::AssetBrowser::PreviewerFactory* GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; + const AzToolsFramework::AssetBrowser::PreviewerFactory* GetPreviewerFactory( + const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; // AzFramework::ApplicationLifecycleEvents overrides... void OnApplicationAboutToStop() override; + void SetupThumbnails(); + void TeardownThumbnails(); + private: AZStd::unique_ptr m_skinnedMeshDebugDisplay; @@ -73,7 +78,7 @@ namespace AZ AZStd::string m_atomLevelDefaultAssetPath{ "LevelAssets/default.slice" }; float m_envProbeHeight{ 200.0f }; - AZStd::unique_ptr m_renderer; + AZStd::unique_ptr m_renderer; AZStd::unique_ptr m_previewerFactory; }; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index a6b595940f..9efa8eb333 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -16,11 +16,9 @@ #include #include #include -#include #include #include #include -#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class @@ -72,11 +70,6 @@ namespace AZ incompatible.push_back(AZ_CRC("EditorMaterialSystem", 0x5c93bc4e)); } - void EditorMaterialSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("ThumbnailerService", 0x65422b97)); - } - void EditorMaterialSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { AZ_UNUSED(dependent); @@ -90,24 +83,20 @@ namespace AZ void EditorMaterialSystemComponent::Activate() { EditorMaterialSystemComponentRequestBus::Handler::BusConnect(); - AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); - SetupThumbnails(); m_materialBrowserInteractions.reset(aznew MaterialBrowserInteractions); } void EditorMaterialSystemComponent::Deactivate() { EditorMaterialSystemComponentRequestBus::Handler::BusDisconnect(); - AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); - TeardownThumbnails(); m_materialBrowserInteractions.reset(); if (m_openMaterialEditorAction) @@ -154,11 +143,6 @@ namespace AZ } } - void EditorMaterialSystemComponent::OnApplicationAboutToStop() - { - TeardownThumbnails(); - } - void EditorMaterialSystemComponent::OnPopulateToolMenuItems() { if (!m_openMaterialEditorAction) @@ -201,26 +185,6 @@ namespace AZ "Material Property Inspector", LyViewPane::CategoryTools, inspectorOptions); } - void EditorMaterialSystemComponent::SetupThumbnails() - { - using namespace AzToolsFramework::Thumbnailer; - using namespace LyIntegration; - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::MaterialThumbnailCache), - ThumbnailContext::DefaultContext); - } - - void EditorMaterialSystemComponent::TeardownThumbnails() - { - using namespace AzToolsFramework::Thumbnailer; - using namespace LyIntegration; - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::MaterialThumbnailCache::ProviderName, - ThumbnailContext::DefaultContext); - } - AzToolsFramework::AssetBrowser::SourceFileDetails EditorMaterialSystemComponent::GetSourceFileDetails( const char* fullSourceFileName) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h index 7fa43ea309..60e489f55e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h @@ -8,10 +8,8 @@ #pragma once #include -#include #include #include -#include #include #include @@ -26,7 +24,6 @@ namespace AZ class EditorMaterialSystemComponent : public AZ::Component , private EditorMaterialSystemComponentRequestBus::Handler - , private AzFramework::ApplicationLifecycleEvents::Bus::Handler , private AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler , private AzToolsFramework::EditorMenuNotificationBus::Handler , private AzToolsFramework::EditorEvents::Bus::Handler @@ -38,7 +35,6 @@ namespace AZ static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); protected: @@ -52,9 +48,6 @@ namespace AZ void OpenMaterialEditor(const AZStd::string& sourcePath) override; void OpenMaterialInspector(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; - // AzFramework::ApplicationLifecycleEvents overrides... - void OnApplicationAboutToStop() override; - //! AssetBrowserInteractionNotificationBus::Handler overrides... AzToolsFramework::AssetBrowser::SourceFileDetails GetSourceFileDetails(const char* fullSourceFileName) override; @@ -65,9 +58,6 @@ namespace AZ // AztoolsFramework::EditorEvents::Bus::Handler overrides... void NotifyRegisterViews() override; - void SetupThumbnails(); - void TeardownThumbnails(); - QAction* m_openMaterialEditorAction = nullptr; AZStd::unique_ptr m_materialBrowserInteractions; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.cpp index 8b2f6c8a11..c6a7ff1f50 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.cpp @@ -6,13 +6,10 @@ * */ -#include #include #include -#include -#include -#include -#include +#include +#include namespace AZ { @@ -47,11 +44,6 @@ namespace AZ incompatible.push_back(AZ_CRC_CE("EditorMeshSystem")); } - void EditorMeshSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC_CE("ThumbnailerService")); - } - void EditorMeshSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { AZ_UNUSED(dependent); @@ -59,39 +51,10 @@ namespace AZ void EditorMeshSystemComponent::Activate() { - AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); - SetupThumbnails(); } void EditorMeshSystemComponent::Deactivate() { - TeardownThumbnails(); - AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); - } - - void EditorMeshSystemComponent::OnApplicationAboutToStop() - { - TeardownThumbnails(); - } - - void EditorMeshSystemComponent::SetupThumbnails() - { - using namespace AzToolsFramework::Thumbnailer; - using namespace LyIntegration; - - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, - MAKE_TCACHE(Thumbnails::MeshThumbnailCache), - ThumbnailContext::DefaultContext); - } - - void EditorMeshSystemComponent::TeardownThumbnails() - { - using namespace AzToolsFramework::Thumbnailer; - using namespace LyIntegration; - - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::UnregisterThumbnailProvider, - Thumbnails::MeshThumbnailCache::ProviderName, - ThumbnailContext::DefaultContext); } } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.h index 64d72bc33d..a784785830 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshSystemComponent.h @@ -8,7 +8,6 @@ #pragma once #include -#include namespace AZ { @@ -17,7 +16,6 @@ namespace AZ //! System component that sets up necessary logic related to EditorMeshComponent. class EditorMeshSystemComponent : public AZ::Component - , private AzFramework::ApplicationLifecycleEvents::Bus::Handler { public: AZ_COMPONENT(EditorMeshSystemComponent, "{4D332E3D-C4FC-410B-A915-8E234CBDD4EC}"); @@ -26,20 +24,12 @@ namespace AZ static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); protected: // AZ::Component interface overrides... void Activate() override; void Deactivate() override; - - private: - // AzFramework::ApplicationLifecycleEvents overrides... - void OnApplicationAboutToStop() override; - - void SetupThumbnails(); - void TeardownThumbnails(); }; } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp similarity index 81% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp index 12caac1e90..f8c508a493 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include namespace AZ { @@ -31,7 +31,7 @@ namespace AZ { namespace Thumbnails { - CommonPreviewContent::CommonPreviewContent( + CommonThumbnailPreviewContent::CommonThumbnailPreviewContent( RPI::ScenePtr scene, RPI::ViewPtr view, AZ::Uuid entityContextId, @@ -65,7 +65,7 @@ namespace AZ m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, false); } - CommonPreviewContent::~CommonPreviewContent() + CommonThumbnailPreviewContent::~CommonThumbnailPreviewContent() { if (m_modelEntity) { @@ -75,44 +75,46 @@ namespace AZ } } - void CommonPreviewContent::Load() + void CommonThumbnailPreviewContent::Load() { m_modelAsset.QueueLoad(); m_materialAsset.QueueLoad(); m_lightingPresetAsset.QueueLoad(); } - bool CommonPreviewContent::IsReady() const + bool CommonThumbnailPreviewContent::IsReady() const { - return m_modelAsset.IsReady() && m_materialAsset.IsReady() && m_lightingPresetAsset.IsReady(); + return (!m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady()) && + (!m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady()) && + (!m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady()); } - bool CommonPreviewContent::IsError() const + bool CommonThumbnailPreviewContent::IsError() const { return m_modelAsset.IsError() || m_materialAsset.IsError() || m_lightingPresetAsset.IsError(); } - void CommonPreviewContent::ReportErrors() + void CommonThumbnailPreviewContent::ReportErrors() { AZ_Warning( - "CommonPreviewContent", m_modelAsset.IsReady(), "Asset failed to load in time: %s", - m_modelAsset.ToString().c_str()); + "CommonThumbnailPreviewContent", !m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady(), + "Asset failed to load in time: %s", m_modelAsset.ToString().c_str()); AZ_Warning( - "CommonPreviewContent", m_materialAsset.IsReady(), "Asset failed to load in time: %s", - m_materialAsset.ToString().c_str()); + "CommonThumbnailPreviewContent", !m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady(), + "Asset failed to load in time: %s", m_materialAsset.ToString().c_str()); AZ_Warning( - "CommonPreviewContent", m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", - m_lightingPresetAsset.ToString().c_str()); + "CommonThumbnailPreviewContent", !m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady(), + "Asset failed to load in time: %s", m_lightingPresetAsset.ToString().c_str()); } - void CommonPreviewContent::UpdateScene() + void CommonThumbnailPreviewContent::UpdateScene() { UpdateModel(); UpdateLighting(); UpdateCamera(); } - void CommonPreviewContent::UpdateModel() + void CommonThumbnailPreviewContent::UpdateModel() { Render::MeshComponentRequestBus::Event( m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); @@ -122,7 +124,7 @@ namespace AZ m_materialAsset.GetId()); } - void CommonPreviewContent::UpdateLighting() + void CommonThumbnailPreviewContent::UpdateLighting() { auto preset = m_lightingPresetAsset->GetDataAs(); if (preset) @@ -152,7 +154,7 @@ namespace AZ } } - void CommonPreviewContent::UpdateCamera() + void CommonThumbnailPreviewContent::UpdateCamera() { // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it Vector3 center = {}; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h new file mode 100644 index 0000000000..59556e03d1 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + //! Provides custom rendering of material and model previews + class CommonThumbnailPreviewContent final + : public CommonPreviewContent + { + public: + AZ_CLASS_ALLOCATOR(CommonThumbnailPreviewContent, AZ::SystemAllocator, 0); + + CommonThumbnailPreviewContent( + RPI::ScenePtr scene, + RPI::ViewPtr view, + AZ::Uuid entityContextId, + const Data::AssetId& modelAssetId, + const Data::AssetId& materialAssetId, + const Data::AssetId& lightingPresetAssetId); + + ~CommonThumbnailPreviewContent() override; + + void Load() override; + bool IsReady() const override; + bool IsError() const override; + void ReportErrors() override; + void UpdateScene() override; + + private: + void UpdateModel(); + void UpdateLighting(); + void UpdateCamera(); + + static constexpr float AspectRatio = 1.0f; + static constexpr float NearDist = 0.001f; + static constexpr float FarDist = 100.0f; + static constexpr float FieldOfView = Constants::HalfPi; + static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; + + RPI::ScenePtr m_scene; + RPI::ViewPtr m_view; + AZ::Uuid m_entityContextId; + Entity* m_modelEntity = nullptr; + + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; + Data::Asset m_lightingPresetAsset; + + //! Model asset about to be rendered + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; + Data::Asset m_modelAsset; + + //! Material asset about to be rendered + static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; + const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); + Data::Asset m_defaultMaterialAsset; + Data::Asset m_materialAsset; + }; + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp new file mode 100644 index 0000000000..63b36b9e14 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + CommonThumbnailRenderer::CommonThumbnailRenderer() + { + // CommonThumbnailRenderer supports both models and materials + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::AnyAsset::RTTI_Type()); + SystemTickBus::Handler::BusConnect(); + } + + CommonThumbnailRenderer::~CommonThumbnailRenderer() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); + SystemTickBus::Handler::BusDisconnect(); + } + + void CommonThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) + { + m_previewRenderer.AddCaptureRequest( + { thumbnailSize, + AZStd::make_shared( + m_previewRenderer.GetScene(), + m_previewRenderer.GetView(), + m_previewRenderer.GetEntityContextId(), + GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type()), + GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type()), + GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type())), + [thumbnailKey]() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + }, + [thumbnailKey](const QImage& image) + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, + QPixmap::fromImage(image)); + } }); + } + + bool CommonThumbnailRenderer::Installed() const + { + return true; + } + + void CommonThumbnailRenderer::OnSystemTick() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); + } + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h new file mode 100644 index 0000000000..fb683c1aff --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + //! Provides custom rendering of material and model thumbnails + class CommonThumbnailRenderer + : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler + , public SystemTickBus::Handler + { + public: + AZ_CLASS_ALLOCATOR(CommonThumbnailRenderer, AZ::SystemAllocator, 0); + + CommonThumbnailRenderer(); + ~CommonThumbnailRenderer(); + + private: + //! ThumbnailerRendererRequestsBus::Handler interface overrides... + void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; + bool Installed() const override; + + //! SystemTickBus::Handler interface overrides... + void OnSystemTick() override; + + CommonPreviewRenderer m_previewRenderer; + }; + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp new file mode 100644 index 0000000000..8fe4b1998d --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + static constexpr const int LightingPresetThumbnailSize = 512; // 512 is the default size in render to texture pass + + ////////////////////////////////////////////////////////////////////////// + // LightingPresetThumbnail + ////////////////////////////////////////////////////////////////////////// + LightingPresetThumbnail::LightingPresetThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + : Thumbnail(key) + { + m_assetId = GetAssetId(key, RPI::AnyAsset::RTTI_Type()); + if (!m_assetId.IsValid()) + { + AZ_Error("LightingPresetThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); + m_state = State::Failed; + return; + } + + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); + } + + void LightingPresetThumbnail::LoadThread() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( + RPI::AnyAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, + LightingPresetThumbnailSize); + // wait for response from thumbnail renderer + m_renderWait.acquire(); + } + + LightingPresetThumbnail::~LightingPresetThumbnail() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); + AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); + } + + void LightingPresetThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + { + m_pixmap = thumbnailImage; + m_renderWait.release(); + } + + void LightingPresetThumbnail::ThumbnailFailedToRender() + { + m_state = State::Failed; + m_renderWait.release(); + } + + void LightingPresetThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) + { + if (m_assetId == assetId && m_state == State::Ready) + { + m_state = State::Unloaded; + Load(); + } + } + + ////////////////////////////////////////////////////////////////////////// + // LightingPresetThumbnailCache + ////////////////////////////////////////////////////////////////////////// + LightingPresetThumbnailCache::LightingPresetThumbnailCache() + : ThumbnailCache() + { + } + + LightingPresetThumbnailCache::~LightingPresetThumbnailCache() = default; + + int LightingPresetThumbnailCache::GetPriority() const + { + // Thumbnails override default source thumbnails, so carry higher priority + return 1; + } + + const char* LightingPresetThumbnailCache::GetProviderName() const + { + return ProviderName; + } + + bool LightingPresetThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const + { + const auto assetId = Thumbnails::GetAssetId(key, RPI::AnyAsset::RTTI_Type()); + if (assetId.IsValid()) + { + AZ::Data::AssetInfo assetInfo; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); + return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); + } + + return false; + } + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ + +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.h similarity index 72% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.h index 2975b6950c..efbfe5b7d5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.h @@ -21,18 +21,16 @@ namespace AZ { namespace Thumbnails { - /** - * Custom material or model thumbnail that detects when an asset changes and updates the thumbnail - */ - class MeshThumbnail + //! Custom thumbnail that detects when an asset changes and updates the thumbnail + class LightingPresetThumbnail : public AzToolsFramework::Thumbnailer::Thumbnail , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler , private AzFramework::AssetCatalogEventBus::Handler { Q_OBJECT public: - MeshThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - ~MeshThumbnail() override; + LightingPresetThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + ~LightingPresetThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... void ThumbnailRendered(QPixmap& thumbnailImage) override; @@ -49,20 +47,17 @@ namespace AZ Data::AssetId m_assetId; }; - /** - * Cache configuration for large material thumbnails - */ - class MeshThumbnailCache - : public AzToolsFramework::Thumbnailer::ThumbnailCache + //! Cache configuration for large thumbnails + class LightingPresetThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache { public: - MeshThumbnailCache(); - ~MeshThumbnailCache() override; + LightingPresetThumbnailCache(); + ~LightingPresetThumbnailCache() override; int GetPriority() const override; const char* GetProviderName() const override; - static constexpr const char* ProviderName = "Mesh Thumbnails"; + static constexpr const char* ProviderName = "LightingPreset Thumbnails"; protected: bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp similarity index 80% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp index 0723859ff5..69bcffde06 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp @@ -6,10 +6,11 @@ * */ +#include #include #include -#include -#include +#include +#include namespace AZ { @@ -40,9 +41,7 @@ namespace AZ void MaterialThumbnail::LoadThread() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - RPI::MaterialAsset::RTTI_Type(), - &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, - m_key, + RPI::MaterialAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, MaterialThumbnailSize); // wait for response from thumbnail renderer m_renderWait.acquire(); @@ -68,8 +67,7 @@ namespace AZ void MaterialThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) { - if (m_assetId == assetId && - m_state == State::Ready) + if (m_assetId == assetId && m_state == State::Ready) { m_state = State::Unloaded; Load(); @@ -88,7 +86,7 @@ namespace AZ int MaterialThumbnailCache::GetPriority() const { - // Material thumbnails override default source thumbnails, so carry higher priority + // Thumbnails override default source thumbnails, so carry higher priority return 1; } @@ -99,14 +97,10 @@ namespace AZ bool MaterialThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const { - return - GetAssetId(key, RPI::MaterialAsset::RTTI_Type()).IsValid() && - // in case it's a source scene file, it will contain both material and model products - // model thumbnails are handled by MeshThumbnail - !GetAssetId(key, RPI::ModelAsset::RTTI_Type()).IsValid(); + return GetAssetId(key, RPI::MaterialAsset::RTTI_Type()).IsValid(); } } // namespace Thumbnails } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.h similarity index 83% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.h index d323a04a1f..9a580d07ce 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.h @@ -13,7 +13,6 @@ #include #include #include -#include #endif namespace AZ @@ -22,9 +21,7 @@ namespace AZ { namespace Thumbnails { - /** - * Custom material or model thumbnail that detects when an asset changes and updates the thumbnail - */ + //! Custom thumbnail that detects when an asset changes and updates the thumbnail class MaterialThumbnail : public AzToolsFramework::Thumbnailer::Thumbnail , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler @@ -50,11 +47,8 @@ namespace AZ Data::AssetId m_assetId; }; - /** - * Cache configuration for large material thumbnails - */ - class MaterialThumbnailCache - : public AzToolsFramework::Thumbnailer::ThumbnailCache + //! Cache configuration for large thumbnails + class MaterialThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache { public: MaterialThumbnailCache(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp similarity index 59% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp index 658d420a16..bc47ec04b8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp @@ -6,11 +6,11 @@ * */ -#include #include +#include #include -#include -#include +#include +#include namespace AZ { @@ -18,18 +18,18 @@ namespace AZ { namespace Thumbnails { - static constexpr const int MeshThumbnailSize = 512; // 512 is the default size in render to texture pass + static constexpr const int ModelThumbnailSize = 512; // 512 is the default size in render to texture pass ////////////////////////////////////////////////////////////////////////// - // MeshThumbnail + // ModelThumbnail ////////////////////////////////////////////////////////////////////////// - MeshThumbnail::MeshThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + ModelThumbnail::ModelThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) : Thumbnail(key) { m_assetId = GetAssetId(key, RPI::ModelAsset::RTTI_Type()); if (!m_assetId.IsValid()) { - AZ_Error("MeshThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); + AZ_Error("ModelThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); m_state = State::Failed; return; } @@ -38,39 +38,36 @@ namespace AZ AzFramework::AssetCatalogEventBus::Handler::BusConnect(); } - void MeshThumbnail::LoadThread() + void ModelThumbnail::LoadThread() { AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - RPI::ModelAsset::RTTI_Type(), - &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, - m_key, - MeshThumbnailSize); + RPI::ModelAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, + ModelThumbnailSize); // wait for response from thumbnail renderer m_renderWait.acquire(); } - MeshThumbnail::~MeshThumbnail() + ModelThumbnail::~ModelThumbnail() { AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); } - void MeshThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + void ModelThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) { m_pixmap = thumbnailImage; m_renderWait.release(); } - void MeshThumbnail::ThumbnailFailedToRender() + void ModelThumbnail::ThumbnailFailedToRender() { m_state = State::Failed; m_renderWait.release(); } - void MeshThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) + void ModelThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) { - if (m_assetId == assetId && - m_state == State::Ready) + if (m_assetId == assetId && m_state == State::Ready) { m_state = State::Unloaded; Load(); @@ -78,27 +75,27 @@ namespace AZ } ////////////////////////////////////////////////////////////////////////// - // MeshThumbnailCache + // ModelThumbnailCache ////////////////////////////////////////////////////////////////////////// - MeshThumbnailCache::MeshThumbnailCache() - : ThumbnailCache() + ModelThumbnailCache::ModelThumbnailCache() + : ThumbnailCache() { } - MeshThumbnailCache::~MeshThumbnailCache() = default; + ModelThumbnailCache::~ModelThumbnailCache() = default; - int MeshThumbnailCache::GetPriority() const + int ModelThumbnailCache::GetPriority() const { - // Material thumbnails override default source thumbnails, so carry higher priority + // Thumbnails override default source thumbnails, so carry higher priority return 1; } - const char* MeshThumbnailCache::GetProviderName() const + const char* ModelThumbnailCache::GetProviderName() const { return ProviderName; } - bool MeshThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const + bool ModelThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const { return GetAssetId(key, RPI::ModelAsset::RTTI_Type()).IsValid(); } @@ -106,4 +103,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h new file mode 100644 index 0000000000..2925abe36e --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#if !defined(Q_MOC_RUN) +#include +#include +#include +#include +#endif + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + //! Custom thumbnail that detects when an asset changes and updates the thumbnail + class ModelThumbnail + : public AzToolsFramework::Thumbnailer::Thumbnail + , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler + , private AzFramework::AssetCatalogEventBus::Handler + { + Q_OBJECT + public: + ModelThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + ~ModelThumbnail() override; + + //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... + void ThumbnailRendered(QPixmap& thumbnailImage) override; + void ThumbnailFailedToRender() override; + + protected: + void LoadThread() override; + + private: + // AzFramework::AssetCatalogEventBus::Handler interface overrides... + void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; + + AZStd::binary_semaphore m_renderWait; + Data::AssetId m_assetId; + }; + + //! Cache configuration for large thumbnails + class ModelThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache + { + public: + ModelThumbnailCache(); + ~ModelThumbnailCache() override; + + int GetPriority() const override; + const char* GetProviderName() const override; + + static constexpr const char* ProviderName = "Model Thumbnails"; + + protected: + bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; + }; + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp index 856d38d6cb..5b7ef4bfa6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp @@ -6,9 +6,11 @@ * */ -#include +#include #include #include +#include +#include #include #include #include @@ -24,9 +26,28 @@ namespace AZ bool CommonPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const { - return - Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::MaterialAsset::RTTI_Type()).IsValid() || - Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::ModelAsset::RTTI_Type()).IsValid(); + AZ::Data::AssetId assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::ModelAsset::RTTI_Type()); + if (assetId.IsValid()) + { + return true; + } + + assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::MaterialAsset::RTTI_Type()); + if (assetId.IsValid()) + { + return true; + } + + assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::AnyAsset::RTTI_Type()); + if (assetId.IsValid()) + { + AZ::Data::AssetInfo assetInfo; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); + return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); + } + + return false; } const QString& CommonPreviewerFactory::GetName() const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h index 6c8f0c5565..891c7f2d01 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h @@ -8,11 +8,7 @@ #pragma once -#include -#include -#include -#include -#include +#include namespace AZ { @@ -20,59 +16,19 @@ namespace AZ { namespace Thumbnails { - //! Provides custom rendering of material and model thumbnails + //! Provides custom rendering of preeview images class CommonPreviewContent { public: AZ_CLASS_ALLOCATOR(CommonPreviewContent, AZ::SystemAllocator, 0); - CommonPreviewContent( - RPI::ScenePtr scene, - RPI::ViewPtr view, - AZ::Uuid entityContextId, - const Data::AssetId& modelAssetId, - const Data::AssetId& materialAssetId, - const Data::AssetId& lightingPresetAssetId); - ~CommonPreviewContent(); - - void Load(); - bool IsReady() const; - bool IsError() const; - void ReportErrors(); - void UpdateScene(); - - private: - void UpdateModel(); - void UpdateLighting(); - void UpdateCamera(); - - static constexpr float AspectRatio = 1.0f; - static constexpr float NearDist = 0.001f; - static constexpr float FarDist = 100.0f; - static constexpr float FieldOfView = Constants::HalfPi; - static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; - - RPI::ScenePtr m_scene; - RPI::ViewPtr m_view; - AZ::Uuid m_entityContextId; - Entity* m_modelEntity = nullptr; - - static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); - Data::Asset m_defaultLightingPresetAsset; - Data::Asset m_lightingPresetAsset; - - //! Model asset about to be rendered - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); - Data::Asset m_defaultModelAsset; - Data::Asset m_modelAsset; - - //! Material asset about to be rendered - static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; - const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); - Data::Asset m_defaultMaterialAsset; - Data::Asset m_materialAsset; + CommonPreviewContent() = default; + virtual ~CommonPreviewContent() = default; + virtual void Load() = 0; + virtual bool IsReady() const = 0; + virtual bool IsError() const = 0; + virtual void ReportErrors() = 0; + virtual void UpdateScene() = 0; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp index 37a9bab378..d21387c925 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp @@ -19,13 +19,10 @@ #include #include #include -#include -#include #include #include #include #include -#include namespace AZ { @@ -35,11 +32,7 @@ namespace AZ { CommonPreviewRenderer::CommonPreviewRenderer() { - // CommonPreviewRenderer supports both models and materials - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); - SystemTickBus::Handler::BusConnect(); m_entityContext = AZStd::make_unique(); m_entityContext->InitContext(); @@ -95,8 +88,6 @@ namespace AZ CommonPreviewRenderer::~CommonPreviewRenderer() { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); - SystemTickBus::Handler::BusDisconnect(); PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); SetState(CommonPreviewRenderer::State::None); @@ -110,6 +101,21 @@ namespace AZ m_frameworkScene->UnsetSubsystem(m_entityContext.get()); } + RPI::ScenePtr CommonPreviewRenderer::GetScene() const + { + return m_scene; + } + + RPI::ViewPtr CommonPreviewRenderer::GetView() const + { + return m_view; + } + + AZ::Uuid CommonPreviewRenderer::GetEntityContextId() const + { + return m_entityContext->GetContextId(); + } + void CommonPreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) { m_captureRequestQueue.push(captureRequest); @@ -227,11 +233,6 @@ namespace AZ m_renderPipeline->RemoveFromRenderTick(); } - void CommonPreviewRenderer::OnSystemTick() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); - } - void CommonPreviewRenderer::GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const { featureProcessors.insert({ @@ -253,33 +254,6 @@ namespace AZ "AZ::Render::PostProcessFeatureProcessor", "AZ::Render::SkyBoxFeatureProcessor" }); } - - void CommonPreviewRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) - { - AddCaptureRequest( - { thumbnailSize, - AZStd::make_shared( - m_scene, m_view, m_entityContext->GetContextId(), - GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type()), - GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type()), - GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type())), - [thumbnailKey]() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - }, - [thumbnailKey](const QImage& image) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, - QPixmap::fromImage(image)); - } }); - } - - bool CommonPreviewRenderer::Installed() const - { - return true; - } } // namespace Thumbnails } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h index 124a6987cc..dd0c3c4898 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h @@ -12,22 +12,15 @@ #include #include #include -#include -#include #include -#include +#include namespace AzFramework { class Scene; } -// Disables warning messages triggered by the Qt library -// 4251: class needs to have dll-interface to be used by clients of class -// 4800: forcing value to bool 'true' or 'false' (performance warning) -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include -AZ_POP_DISABLE_WARNING +class QImage; namespace AZ { @@ -35,13 +28,9 @@ namespace AZ { namespace Thumbnails { - class CommonPreviewRendererState; - //! Provides custom rendering of material and model thumbnails - class CommonPreviewRenderer - : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler - , public SystemTickBus::Handler - , public PreviewerFeatureProcessorProviderBus::Handler + class CommonPreviewRenderer final + : public PreviewerFeatureProcessorProviderBus::Handler { public: AZ_CLASS_ALLOCATOR(CommonPreviewRenderer, AZ::SystemAllocator, 0); @@ -49,7 +38,7 @@ namespace AZ CommonPreviewRenderer(); ~CommonPreviewRenderer(); - struct CaptureRequest + struct CaptureRequest final { int m_size = 512; AZStd::shared_ptr m_content; @@ -57,6 +46,10 @@ namespace AZ AZStd::function m_captureCompleteCallback; }; + RPI::ScenePtr GetScene() const; + RPI::ViewPtr GetView() const; + AZ::Uuid GetEntityContextId() const; + void AddCaptureRequest(const CaptureRequest& captureRequest); enum class State : AZ::s8 @@ -84,16 +77,9 @@ namespace AZ void EndCapture(); private: - //! SystemTickBus::Handler interface overrides... - void OnSystemTick() override; - //! Render::PreviewerFeatureProcessorProviderBus::Handler interface overrides... void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; - //! ThumbnailerRendererRequestsBus::Handler interface overrides... - void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; - bool Installed() const override; - static constexpr float AspectRatio = 1.0f; static constexpr float NearDist = 0.001f; static constexpr float FarDist = 100.0f; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index f135bc1132..3b6212e0eb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -45,8 +45,6 @@ set(FILES Source/Material/EditorMaterialSystemComponent.h Source/Material/MaterialBrowserInteractions.h Source/Material/MaterialBrowserInteractions.cpp - Source/Material/MaterialThumbnail.cpp - Source/Material/MaterialThumbnail.h Source/Mesh/EditorMeshComponent.h Source/Mesh/EditorMeshComponent.cpp Source/Mesh/EditorMeshStats.h @@ -55,8 +53,6 @@ set(FILES Source/Mesh/EditorMeshSystemComponent.h Source/Mesh/EditorMeshStatsSerializer.cpp Source/Mesh/EditorMeshStatsSerializer.h - Source/Mesh/MeshThumbnail.h - Source/Mesh/MeshThumbnail.cpp Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.h Source/OcclusionCullingPlane/EditorOcclusionCullingPlaneComponent.cpp Source/PostProcess/EditorPostFxLayerComponent.cpp @@ -102,7 +98,6 @@ set(FILES Source/Thumbnails/Preview/CommonPreviewer.ui Source/Thumbnails/Preview/CommonPreviewerFactory.cpp Source/Thumbnails/Preview/CommonPreviewerFactory.h - Source/Thumbnails/Rendering/CommonPreviewContent.cpp Source/Thumbnails/Rendering/CommonPreviewContent.h Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp Source/Thumbnails/Rendering/CommonPreviewRenderer.h @@ -113,6 +108,16 @@ set(FILES Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h + Source/Thumbnails/CommonThumbnailPreviewContent.cpp + Source/Thumbnails/CommonThumbnailPreviewContent.h + Source/Thumbnails/CommonThumbnailRenderer.cpp + Source/Thumbnails/CommonThumbnailRenderer.h + Source/Thumbnails/MaterialThumbnail.cpp + Source/Thumbnails/MaterialThumbnail.h + Source/Thumbnails/ModelThumbnail.cpp + Source/Thumbnails/ModelThumbnail.h + Source/Thumbnails/LightingPresetThumbnail.cpp + Source/Thumbnails/LightingPresetThumbnail.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From 569318e9e1b18e7b796da209d23a0b8de40feeca Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 8 Oct 2021 02:56:24 -0500 Subject: [PATCH 07/52] Moved preview renderer files to atom tools framework Signed-off-by: Guthrie Adams --- .../Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h} | 0 .../Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h} | 0 .../Code/Source/PreviewRenderer/PreviewRenderer.cpp} | 0 .../Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp} | 0 .../Code/Source/PreviewRenderer/PreviewRendererCaptureState.h} | 0 .../Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp} | 0 .../Code/Source/PreviewRenderer/PreviewRendererIdleState.h} | 0 .../Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp} | 0 .../Code/Source/PreviewRenderer/PreviewRendererLoadState.h} | 0 .../Code/Source/PreviewRenderer/PreviewRendererState.h} | 0 10 files changed, 0 insertions(+), 0 deletions(-) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h => Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h => Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h} (100%) rename Gems/{AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h => Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h} (100%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewContent.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Rendering/CommonPreviewRendererState.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h From 76b4dafbb3e848ad0f7f48b392ec97bbf0974ff9 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 8 Oct 2021 04:33:45 -0500 Subject: [PATCH 08/52] Everything compiling again after moving preview renderer to atom tools framework Signed-off-by: Guthrie Adams --- .../AtomToolsFramework/Code/CMakeLists.txt | 1 + .../PreviewRenderer/PreviewContent.h | 34 +- .../PreviewRenderer/PreviewRenderer.h | 131 +++--- .../PreviewRenderer/PreviewRendererState.h | 35 ++ .../PreviewerFeatureProcessorProviderBus.h | 25 + .../Viewport/RenderViewportWidget.h | 4 +- .../PreviewRenderer/PreviewRenderer.cpp | 443 +++++++++--------- .../PreviewRendererCaptureState.cpp | 78 ++- .../PreviewRendererCaptureState.h | 47 +- .../PreviewRendererIdleState.cpp | 44 +- .../PreviewRendererIdleState.h | 39 +- .../PreviewRendererLoadState.cpp | 68 ++- .../PreviewRendererLoadState.h | 41 +- .../PreviewRenderer/PreviewRendererState.h | 37 -- .../Code/atomtoolsframework_files.cmake | 11 + .../PreviewerFeatureProcessorProviderBus.h | 33 -- .../CommonThumbnailPreviewContent.h | 4 +- .../Thumbnails/CommonThumbnailRenderer.h | 4 +- .../Thumbnails/Preview/CommonPreviewer.cpp | 8 +- ...egration_commonfeatures_editor_files.cmake | 11 - 20 files changed, 515 insertions(+), 583 deletions(-) create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewerFeatureProcessorProviderBus.h delete mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt index add499f080..ea5b65be7c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt @@ -36,6 +36,7 @@ ly_add_target( Gem::Atom_RPI.Edit Gem::Atom_RPI.Public Gem::Atom_RHI.Reflect + Gem::Atom_Feature_Common.Static Gem::Atom_Bootstrap.Headers ) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h index 891c7f2d01..17445835ba 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h @@ -10,26 +10,20 @@ #include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + //! Provides custom rendering of previefw images + class PreviewContent { - namespace Thumbnails - { - //! Provides custom rendering of preeview images - class CommonPreviewContent - { - public: - AZ_CLASS_ALLOCATOR(CommonPreviewContent, AZ::SystemAllocator, 0); + public: + AZ_CLASS_ALLOCATOR(PreviewContent, AZ::SystemAllocator, 0); - CommonPreviewContent() = default; - virtual ~CommonPreviewContent() = default; - virtual void Load() = 0; - virtual bool IsReady() const = 0; - virtual bool IsError() const = 0; - virtual void ReportErrors() = 0; - virtual void UpdateScene() = 0; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + PreviewContent() = default; + virtual ~PreviewContent() = default; + virtual void Load() = 0; + virtual bool IsReady() const = 0; + virtual bool IsError() const = 0; + virtual void ReportErrors() = 0; + virtual void UpdateScene() = 0; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h index dd0c3c4898..b772bfcaf2 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h @@ -10,10 +10,10 @@ #include #include -#include +#include +#include +#include #include -#include -#include namespace AzFramework { @@ -22,85 +22,78 @@ namespace AzFramework class QImage; -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + //! Provides custom rendering of preview images + class PreviewRenderer final : public PreviewerFeatureProcessorProviderBus::Handler { - namespace Thumbnails + public: + AZ_CLASS_ALLOCATOR(PreviewRenderer, AZ::SystemAllocator, 0); + + PreviewRenderer(); + ~PreviewRenderer(); + + struct CaptureRequest final { - //! Provides custom rendering of material and model thumbnails - class CommonPreviewRenderer final - : public PreviewerFeatureProcessorProviderBus::Handler - { - public: - AZ_CLASS_ALLOCATOR(CommonPreviewRenderer, AZ::SystemAllocator, 0); + int m_size = 512; + AZStd::shared_ptr m_content; + AZStd::function m_captureFailedCallback; + AZStd::function m_captureCompleteCallback; + }; - CommonPreviewRenderer(); - ~CommonPreviewRenderer(); + AZ::RPI::ScenePtr GetScene() const; + AZ::RPI::ViewPtr GetView() const; + AZ::Uuid GetEntityContextId() const; - struct CaptureRequest final - { - int m_size = 512; - AZStd::shared_ptr m_content; - AZStd::function m_captureFailedCallback; - AZStd::function m_captureCompleteCallback; - }; + void AddCaptureRequest(const CaptureRequest& captureRequest); - RPI::ScenePtr GetScene() const; - RPI::ViewPtr GetView() const; - AZ::Uuid GetEntityContextId() const; + enum class State : AZ::s8 + { + None, + IdleState, + LoadState, + CaptureState + }; - void AddCaptureRequest(const CaptureRequest& captureRequest); + void SetState(State state); + State GetState() const; - enum class State : AZ::s8 - { - None, - IdleState, - LoadState, - CaptureState - }; + void SelectCaptureRequest(); + void CancelCaptureRequest(); + void CompleteCaptureRequest(); - void SetState(State state); - State GetState() const; + void LoadAssets(); + void UpdateLoadAssets(); + void CancelLoadAssets(); - void SelectCaptureRequest(); - void CancelCaptureRequest(); - void CompleteCaptureRequest(); + void UpdateScene(); - void LoadAssets(); - void UpdateLoadAssets(); - void CancelLoadAssets(); + bool StartCapture(); + void EndCapture(); - void UpdateScene(); + private: + //! AZ::Render::PreviewerFeatureProcessorProviderBus::Handler interface overrides... + void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; - bool StartCapture(); - void EndCapture(); + static constexpr float AspectRatio = 1.0f; + static constexpr float NearDist = 0.001f; + static constexpr float FarDist = 100.0f; + static constexpr float FieldOfView = AZ::Constants::HalfPi; - private: - //! Render::PreviewerFeatureProcessorProviderBus::Handler interface overrides... - void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const override; + AZ::RPI::ScenePtr m_scene; + AZStd::string m_sceneName = "Preview Renderer Scene"; + AZStd::string m_pipelineName = "Preview Renderer Pipeline"; + AZStd::shared_ptr m_frameworkScene; + AZ::RPI::RenderPipelinePtr m_renderPipeline; + AZ::RPI::ViewPtr m_view; + AZStd::vector m_passHierarchy; + AZStd::unique_ptr m_entityContext; - static constexpr float AspectRatio = 1.0f; - static constexpr float NearDist = 0.001f; - static constexpr float FarDist = 100.0f; - static constexpr float FieldOfView = Constants::HalfPi; + //! Incoming requests are appended to this queue and processed one at a time in OnTick function. + AZStd::queue m_captureRequestQueue; + CaptureRequest m_currentCaptureRequest; - RPI::ScenePtr m_scene; - AZStd::string m_sceneName = "Material Thumbnail Scene"; - AZStd::string m_pipelineName = "Material Thumbnail Pipeline"; - AZStd::shared_ptr m_frameworkScene; - RPI::RenderPipelinePtr m_renderPipeline; - RPI::ViewPtr m_view; - AZStd::vector m_passHierarchy; - AZStd::unique_ptr m_entityContext; - - //! Incoming requests are appended to this queue and processed one at a time in OnTick function. - AZStd::queue m_captureRequestQueue; - CaptureRequest m_currentCaptureRequest; - - AZStd::unordered_map> m_states; - State m_currentState = CommonPreviewRenderer::State::None; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + AZStd::unordered_map> m_states; + State m_currentState = PreviewRenderer::State::None; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h new file mode 100644 index 0000000000..264c37a122 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +namespace AtomToolsFramework +{ + class PreviewRenderer; + + //! PreviewRendererState decouples PreviewRenderer logic into easy-to-understand and debug pieces + class PreviewRendererState + { + public: + explicit PreviewRendererState(PreviewRenderer* renderer) + : m_renderer(renderer) + { + } + + virtual ~PreviewRendererState() = default; + + //! Start is called when state begins execution + virtual void Start() = 0; + + //! Stop is called when state ends execution + virtual void Stop() = 0; + + protected: + PreviewRenderer* m_renderer = {}; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewerFeatureProcessorProviderBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewerFeatureProcessorProviderBus.h new file mode 100644 index 0000000000..fe1980b39b --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewerFeatureProcessorProviderBus.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include + +namespace AtomToolsFramework +{ + //! PreviewerFeatureProcessorProviderRequests allows registering custom Feature Processors for preview image generation + class PreviewerFeatureProcessorProviderRequests : public AZ::EBusTraits + { + public: + //! Get a list of custom feature processors to register with preview image renderer + virtual void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; + }; + + using PreviewerFeatureProcessorProviderBus = AZ::EBus; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index 623d759c9f..22d9dcfc6b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -25,7 +25,7 @@ namespace AtomToolsFramework { //! The RenderViewportWidget class is a Qt wrapper around an Atom viewport. - //! RenderViewportWidget renders to an internal window using RPI::ViewportContext + //! RenderViewportWidget renders to an internal window using AZ::RPI::ViewportContext //! and delegates input via its internal ViewportControllerList. //! @see AZ::RPI::ViewportContext for Atom's API for setting up class RenderViewportWidget @@ -39,7 +39,7 @@ namespace AtomToolsFramework public: //! Creates a RenderViewportWidget. //! Requires the Atom RPI to be initialized in order - //! to internally construct an RPI::ViewportContext. + //! to internally construct an AZ::RPI::ViewportContext. //! If initializeViewportContext is set to false, nothing will be displayed on-screen until InitiliazeViewportContext is called. explicit RenderViewportWidget(QWidget* parent = nullptr, bool shouldInitializeViewportContext = true); ~RenderViewportWidget(); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index d21387c925..dfefd0203e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -15,245 +15,238 @@ #include #include #include +#include #include #include #include #include -#include -#include -#include -#include +#include +#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + PreviewRenderer::PreviewRenderer() { - namespace Thumbnails + PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); + + m_entityContext = AZStd::make_unique(); + m_entityContext->InitContext(); + + // Create and register a scene with all required feature processors + AZStd::unordered_set featureProcessors; + PreviewerFeatureProcessorProviderBus::Broadcast( + &PreviewerFeatureProcessorProviderBus::Handler::GetRequiredFeatureProcessors, featureProcessors); + + AZ::RPI::SceneDescriptor sceneDesc; + sceneDesc.m_featureProcessorNames.assign(featureProcessors.begin(), featureProcessors.end()); + m_scene = AZ::RPI::Scene::CreateScene(sceneDesc); + + // Bind m_frameworkScene to the entity context's AzFramework::Scene + auto sceneSystem = AzFramework::SceneSystemInterface::Get(); + AZ_Assert(sceneSystem, "Failed to get scene system implementation."); + + AZ::Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(m_sceneName); + AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); + + m_frameworkScene = createSceneOutcome.TakeValue(); + m_frameworkScene->SetSubsystem(m_scene); + m_frameworkScene->SetSubsystem(m_entityContext.get()); + + // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene + AZ::RPI::RenderPipelineDescriptor pipelineDesc; + pipelineDesc.m_mainViewTagName = "MainCamera"; + pipelineDesc.m_name = m_pipelineName; + pipelineDesc.m_rootPassTemplate = "MainPipelineRenderToTexture"; + + // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue + // [GFX TODO] [ATOM-13551] Default value sand validation required to prevent pipeline crash and device lost + pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; + m_renderPipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc); + m_scene->AddRenderPipeline(m_renderPipeline); + m_scene->Activate(); + AZ::RPI::RPISystemInterface::Get()->RegisterScene(m_scene); + m_passHierarchy.push_back(m_pipelineName); + m_passHierarchy.push_back("CopyToSwapChain"); + + // Connect camera to pipeline's default view after camera entity activated + AZ::Matrix4x4 viewToClipMatrix; + AZ::MakePerspectiveFovMatrixRH(viewToClipMatrix, FieldOfView, AspectRatio, NearDist, FarDist, true); + m_view = AZ::RPI::View::CreateView(AZ::Name("MainCamera"), AZ::RPI::View::UsageCamera); + m_view->SetViewToClipMatrix(viewToClipMatrix); + m_renderPipeline->SetDefaultView(m_view); + + m_states[PreviewRenderer::State::IdleState] = AZStd::make_shared(this); + m_states[PreviewRenderer::State::LoadState] = AZStd::make_shared(this); + m_states[PreviewRenderer::State::CaptureState] = AZStd::make_shared(this); + SetState(PreviewRenderer::State::IdleState); + } + + PreviewRenderer::~PreviewRenderer() + { + PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); + + SetState(PreviewRenderer::State::None); + m_currentCaptureRequest = {}; + m_captureRequestQueue = {}; + + m_scene->Deactivate(); + m_scene->RemoveRenderPipeline(m_renderPipeline->GetId()); + AZ::RPI::RPISystemInterface::Get()->UnregisterScene(m_scene); + m_frameworkScene->UnsetSubsystem(m_scene); + m_frameworkScene->UnsetSubsystem(m_entityContext.get()); + } + + AZ::RPI::ScenePtr PreviewRenderer::GetScene() const + { + return m_scene; + } + + AZ::RPI::ViewPtr PreviewRenderer::GetView() const + { + return m_view; + } + + AZ::Uuid PreviewRenderer::GetEntityContextId() const + { + return m_entityContext->GetContextId(); + } + + void PreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) + { + m_captureRequestQueue.push(captureRequest); + } + + void PreviewRenderer::SetState(State state) + { + auto stepItr = m_states.find(m_currentState); + if (stepItr != m_states.end()) { - CommonPreviewRenderer::CommonPreviewRenderer() + stepItr->second->Stop(); + } + + m_currentState = state; + + stepItr = m_states.find(m_currentState); + if (stepItr != m_states.end()) + { + stepItr->second->Start(); + } + } + + PreviewRenderer::State PreviewRenderer::GetState() const + { + return m_currentState; + } + + void PreviewRenderer::SelectCaptureRequest() + { + if (!m_captureRequestQueue.empty()) + { + // pop the next request to be rendered from the queue + m_currentCaptureRequest = m_captureRequestQueue.front(); + m_captureRequestQueue.pop(); + + SetState(PreviewRenderer::State::LoadState); + } + } + + void PreviewRenderer::CancelCaptureRequest() + { + m_currentCaptureRequest.m_captureFailedCallback(); + SetState(PreviewRenderer::State::IdleState); + } + + void PreviewRenderer::CompleteCaptureRequest() + { + SetState(PreviewRenderer::State::IdleState); + } + + void PreviewRenderer::LoadAssets() + { + m_currentCaptureRequest.m_content->Load(); + } + + void PreviewRenderer::UpdateLoadAssets() + { + if (m_currentCaptureRequest.m_content->IsReady()) + { + SetState(PreviewRenderer::State::CaptureState); + return; + } + + if (m_currentCaptureRequest.m_content->IsError()) + { + CancelLoadAssets(); + return; + } + } + + void PreviewRenderer::CancelLoadAssets() + { + m_currentCaptureRequest.m_content->ReportErrors(); + CancelCaptureRequest(); + } + + void PreviewRenderer::UpdateScene() + { + m_currentCaptureRequest.m_content->UpdateScene(); + } + + bool PreviewRenderer::StartCapture() + { + auto captureCallback = [currentCaptureRequest = m_currentCaptureRequest](const AZ::RPI::AttachmentReadback::ReadbackResult& result) + { + if (result.m_dataBuffer) { - PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); - - m_entityContext = AZStd::make_unique(); - m_entityContext->InitContext(); - - // Create and register a scene with all required feature processors - AZStd::unordered_set featureProcessors; - PreviewerFeatureProcessorProviderBus::Broadcast( - &PreviewerFeatureProcessorProviderBus::Handler::GetRequiredFeatureProcessors, featureProcessors); - - RPI::SceneDescriptor sceneDesc; - sceneDesc.m_featureProcessorNames.assign(featureProcessors.begin(), featureProcessors.end()); - m_scene = RPI::Scene::CreateScene(sceneDesc); - - // Bind m_frameworkScene to the entity context's AzFramework::Scene - auto sceneSystem = AzFramework::SceneSystemInterface::Get(); - AZ_Assert(sceneSystem, "Failed to get scene system implementation."); - - Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(m_sceneName); - AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); - - m_frameworkScene = createSceneOutcome.TakeValue(); - m_frameworkScene->SetSubsystem(m_scene); - m_frameworkScene->SetSubsystem(m_entityContext.get()); - - // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene - RPI::RenderPipelineDescriptor pipelineDesc; - pipelineDesc.m_mainViewTagName = "MainCamera"; - pipelineDesc.m_name = m_pipelineName; - pipelineDesc.m_rootPassTemplate = "MainPipelineRenderToTexture"; - - // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue - // [GFX TODO] [ATOM-13551] Default value sand validation required to prevent pipeline crash and device lost - pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; - m_renderPipeline = RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc); - m_scene->AddRenderPipeline(m_renderPipeline); - m_scene->Activate(); - RPI::RPISystemInterface::Get()->RegisterScene(m_scene); - m_passHierarchy.push_back(m_pipelineName); - m_passHierarchy.push_back("CopyToSwapChain"); - - // Connect camera to pipeline's default view after camera entity activated - Matrix4x4 viewToClipMatrix; - MakePerspectiveFovMatrixRH(viewToClipMatrix, FieldOfView, AspectRatio, NearDist, FarDist, true); - m_view = RPI::View::CreateView(Name("MainCamera"), RPI::View::UsageCamera); - m_view->SetViewToClipMatrix(viewToClipMatrix); - m_renderPipeline->SetDefaultView(m_view); - - m_states[CommonPreviewRenderer::State::IdleState] = AZStd::make_shared(this); - m_states[CommonPreviewRenderer::State::LoadState] = AZStd::make_shared(this); - m_states[CommonPreviewRenderer::State::CaptureState] = AZStd::make_shared(this); - SetState(CommonPreviewRenderer::State::IdleState); + currentCaptureRequest.m_captureCompleteCallback(QImage( + result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, result.m_imageDescriptor.m_size.m_height, + QImage::Format_RGBA8888)); } - - CommonPreviewRenderer::~CommonPreviewRenderer() + else { - PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); - - SetState(CommonPreviewRenderer::State::None); - m_currentCaptureRequest = {}; - m_captureRequestQueue = {}; - - m_scene->Deactivate(); - m_scene->RemoveRenderPipeline(m_renderPipeline->GetId()); - RPI::RPISystemInterface::Get()->UnregisterScene(m_scene); - m_frameworkScene->UnsetSubsystem(m_scene); - m_frameworkScene->UnsetSubsystem(m_entityContext.get()); + currentCaptureRequest.m_captureFailedCallback(); } + }; - RPI::ScenePtr CommonPreviewRenderer::GetScene() const - { - return m_scene; - } + if (auto renderToTexturePass = azrtti_cast(m_renderPipeline->GetRootPass().get())) + { + renderToTexturePass->ResizeOutput(m_currentCaptureRequest.m_size, m_currentCaptureRequest.m_size); + } - RPI::ViewPtr CommonPreviewRenderer::GetView() const - { - return m_view; - } + m_renderPipeline->AddToRenderTickOnce(); - AZ::Uuid CommonPreviewRenderer::GetEntityContextId() const - { - return m_entityContext->GetContextId(); - } + bool startedCapture = false; + AZ::Render::FrameCaptureRequestBus::BroadcastResult( + startedCapture, &AZ::Render::FrameCaptureRequestBus::Events::CapturePassAttachmentWithCallback, m_passHierarchy, + AZStd::string("Output"), captureCallback, AZ::RPI::PassAttachmentReadbackOption::Output); + return startedCapture; + } - void CommonPreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) - { - m_captureRequestQueue.push(captureRequest); - } + void PreviewRenderer::EndCapture() + { + m_renderPipeline->RemoveFromRenderTick(); + } - void CommonPreviewRenderer::SetState(State state) - { - auto stepItr = m_states.find(m_currentState); - if (stepItr != m_states.end()) - { - stepItr->second->Stop(); - } - - m_currentState = state; - - stepItr = m_states.find(m_currentState); - if (stepItr != m_states.end()) - { - stepItr->second->Start(); - } - } - - CommonPreviewRenderer::State CommonPreviewRenderer::GetState() const - { - return m_currentState; - } - - void CommonPreviewRenderer::SelectCaptureRequest() - { - if (!m_captureRequestQueue.empty()) - { - // pop the next request to be rendered from the queue - m_currentCaptureRequest = m_captureRequestQueue.front(); - m_captureRequestQueue.pop(); - - SetState(CommonPreviewRenderer::State::LoadState); - } - } - - void CommonPreviewRenderer::CancelCaptureRequest() - { - m_currentCaptureRequest.m_captureFailedCallback(); - SetState(CommonPreviewRenderer::State::IdleState); - } - - void CommonPreviewRenderer::CompleteCaptureRequest() - { - SetState(CommonPreviewRenderer::State::IdleState); - } - - void CommonPreviewRenderer::LoadAssets() - { - m_currentCaptureRequest.m_content->Load(); - } - - void CommonPreviewRenderer::UpdateLoadAssets() - { - if (m_currentCaptureRequest.m_content->IsReady()) - { - SetState(CommonPreviewRenderer::State::CaptureState); - return; - } - - if (m_currentCaptureRequest.m_content->IsError()) - { - CancelLoadAssets(); - return; - } - } - - void CommonPreviewRenderer::CancelLoadAssets() - { - m_currentCaptureRequest.m_content->ReportErrors(); - CancelCaptureRequest(); - } - - void CommonPreviewRenderer::UpdateScene() - { - m_currentCaptureRequest.m_content->UpdateScene(); - } - - bool CommonPreviewRenderer::StartCapture() - { - auto captureCallback = - [currentCaptureRequest = m_currentCaptureRequest](const RPI::AttachmentReadback::ReadbackResult& result) - { - if (result.m_dataBuffer) - { - currentCaptureRequest.m_captureCompleteCallback(QImage( - result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, - result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888)); - } - else - { - currentCaptureRequest.m_captureFailedCallback(); - } - }; - - if (auto renderToTexturePass = azrtti_cast(m_renderPipeline->GetRootPass().get())) - { - renderToTexturePass->ResizeOutput(m_currentCaptureRequest.m_size, m_currentCaptureRequest.m_size); - } - - m_renderPipeline->AddToRenderTickOnce(); - - bool startedCapture = false; - Render::FrameCaptureRequestBus::BroadcastResult( - startedCapture, &Render::FrameCaptureRequestBus::Events::CapturePassAttachmentWithCallback, m_passHierarchy, - AZStd::string("Output"), captureCallback, RPI::PassAttachmentReadbackOption::Output); - return startedCapture; - } - - void CommonPreviewRenderer::EndCapture() - { - m_renderPipeline->RemoveFromRenderTick(); - } - - void CommonPreviewRenderer::GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const - { - featureProcessors.insert({ - "AZ::Render::TransformServiceFeatureProcessor", - "AZ::Render::MeshFeatureProcessor", - "AZ::Render::SimplePointLightFeatureProcessor", - "AZ::Render::SimpleSpotLightFeatureProcessor", - "AZ::Render::PointLightFeatureProcessor", - // There is currently a bug where having multiple DirectionalLightFeatureProcessors active can result in shadow - // flickering [ATOM-13568] - // as well as continually rebuilding MeshDrawPackets [ATOM-13633]. Lets just disable the directional light FP for now. - // Possibly re-enable with [GFX TODO][ATOM-13639] - // "AZ::Render::DirectionalLightFeatureProcessor", - "AZ::Render::DiskLightFeatureProcessor", - "AZ::Render::CapsuleLightFeatureProcessor", - "AZ::Render::QuadLightFeatureProcessor", - "AZ::Render::DecalTextureArrayFeatureProcessor", - "AZ::Render::ImageBasedLightFeatureProcessor", - "AZ::Render::PostProcessFeatureProcessor", - "AZ::Render::SkyBoxFeatureProcessor" }); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + void PreviewRenderer::GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const + { + featureProcessors.insert({ + "AZ::Render::TransformServiceFeatureProcessor", + "AZ::Render::MeshFeatureProcessor", + "AZ::Render::SimplePointLightFeatureProcessor", + "AZ::Render::SimpleSpotLightFeatureProcessor", + "AZ::Render::PointLightFeatureProcessor", + // There is currently a bug where having multiple DirectionalLightFeatureProcessors active can result in shadow + // flickering [ATOM-13568] + // as well as continually rebuilding MeshDrawPackets [ATOM-13633]. Lets just disable the directional light FP for now. + // Possibly re-enable with [GFX TODO][ATOM-13639] + // "AZ::Render::DirectionalLightFeatureProcessor", + "AZ::Render::DiskLightFeatureProcessor", + "AZ::Render::CapsuleLightFeatureProcessor", + "AZ::Render::QuadLightFeatureProcessor", + "AZ::Render::DecalTextureArrayFeatureProcessor", + "AZ::Render::ImageBasedLightFeatureProcessor", + "AZ::Render::PostProcessFeatureProcessor", + "AZ::Render::SkyBoxFeatureProcessor" }); + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp index fc74e9f43b..f3414bc29f 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp @@ -6,52 +6,46 @@ * */ -#include -#include +#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + PreviewRendererCaptureState::PreviewRendererCaptureState(PreviewRenderer* renderer) + : PreviewRendererState(renderer) { - namespace Thumbnails + } + + void PreviewRendererCaptureState::Start() + { + m_ticksToCapture = 1; + m_renderer->UpdateScene(); + AZ::TickBus::Handler::BusConnect(); + } + + void PreviewRendererCaptureState::Stop() + { + m_renderer->EndCapture(); + AZ::TickBus::Handler::BusDisconnect(); + AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect(); + } + + void PreviewRendererCaptureState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + if (m_ticksToCapture-- <= 0) { - CommonPreviewRendererCaptureState::CommonPreviewRendererCaptureState(CommonPreviewRenderer* renderer) - : CommonPreviewRendererState(renderer) + // Reset the capture flag if the capture request was successful. Otherwise try capture it again next tick. + if (m_renderer->StartCapture()) { + AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(); + AZ::TickBus::Handler::BusDisconnect(); } + } + } - void CommonPreviewRendererCaptureState::Start() - { - m_ticksToCapture = 1; - m_renderer->UpdateScene(); - TickBus::Handler::BusConnect(); - } - - void CommonPreviewRendererCaptureState::Stop() - { - m_renderer->EndCapture(); - TickBus::Handler::BusDisconnect(); - Render::FrameCaptureNotificationBus::Handler::BusDisconnect(); - } - - void CommonPreviewRendererCaptureState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) - { - if (m_ticksToCapture-- <= 0) - { - // Reset the capture flag if the capture request was successful. Otherwise try capture it again next tick. - if (m_renderer->StartCapture()) - { - Render::FrameCaptureNotificationBus::Handler::BusConnect(); - TickBus::Handler::BusDisconnect(); - } - } - } - - void CommonPreviewRendererCaptureState::OnCaptureFinished( - [[maybe_unused]] Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) - { - m_renderer->CompleteCaptureRequest(); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + void PreviewRendererCaptureState::OnCaptureFinished( + [[maybe_unused]] AZ::Render::FrameCaptureResult result, [[maybe_unused]] const AZStd::string& info) + { + m_renderer->CompleteCaptureRequest(); + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h index c19f12d9bb..190cb919df 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h @@ -9,38 +9,31 @@ #pragma once #include +#include #include -#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + //! PreviewRendererCaptureState renders a thumbnail to a pixmap and notifies MaterialOrModelThumbnail once finished + class PreviewRendererCaptureState final + : public PreviewRendererState + , public AZ::TickBus::Handler + , public AZ::Render::FrameCaptureNotificationBus::Handler { - namespace Thumbnails - { - //! CommonPreviewRendererCaptureState renders a thumbnail to a pixmap and notifies MaterialOrModelThumbnail once finished - class CommonPreviewRendererCaptureState - : public CommonPreviewRendererState - , private TickBus::Handler - , private Render::FrameCaptureNotificationBus::Handler - { - public: - CommonPreviewRendererCaptureState(CommonPreviewRenderer* renderer); + public: + PreviewRendererCaptureState(PreviewRenderer* renderer); - void Start() override; - void Stop() override; + void Start() override; + void Stop() override; - private: - //! AZ::TickBus::Handler interface overrides... - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + private: + //! AZ::TickBus::Handler interface overrides... + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - //! Render::FrameCaptureNotificationBus::Handler overrides... - void OnCaptureFinished(Render::FrameCaptureResult result, const AZStd::string& info) override; - - //! This is necessary to suspend capture to allow a frame for Material and Mesh components to assign materials - int m_ticksToCapture = 0; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + //! AZ::Render::FrameCaptureNotificationBus::Handler overrides... + void OnCaptureFinished(AZ::Render::FrameCaptureResult result, const AZStd::string& info) override; + //! This is necessary to suspend capture to allow a frame for Material and Mesh components to assign materials + int m_ticksToCapture = 0; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp index 12a38fc93f..db91bedce1 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp @@ -6,34 +6,28 @@ * */ -#include -#include +#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + PreviewRendererIdleState::PreviewRendererIdleState(PreviewRenderer* renderer) + : PreviewRendererState(renderer) { - namespace Thumbnails - { - CommonPreviewRendererIdleState::CommonPreviewRendererIdleState(CommonPreviewRenderer* renderer) - : CommonPreviewRendererState(renderer) - { - } + } - void CommonPreviewRendererIdleState::Start() - { - TickBus::Handler::BusConnect(); - } + void PreviewRendererIdleState::Start() + { + AZ::TickBus::Handler::BusConnect(); + } - void CommonPreviewRendererIdleState::Stop() - { - TickBus::Handler::BusDisconnect(); - } + void PreviewRendererIdleState::Stop() + { + AZ::TickBus::Handler::BusDisconnect(); + } - void CommonPreviewRendererIdleState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) - { - m_renderer->SelectCaptureRequest(); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + void PreviewRendererIdleState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + m_renderer->SelectCaptureRequest(); + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h index 3278149b98..9e5380e734 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h @@ -8,31 +8,24 @@ #pragma once -#include +#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + //! PreviewRendererIdleState checks whether there are any new thumbnails that need to be rendered every tick + class PreviewRendererIdleState final + : public PreviewRendererState + , public AZ::TickBus::Handler { - namespace Thumbnails - { - //! CommonPreviewRendererIdleState checks whether there are any new thumbnails that need to be rendered every tick - class CommonPreviewRendererIdleState - : public CommonPreviewRendererState - , private TickBus::Handler - { - public: - CommonPreviewRendererIdleState(CommonPreviewRenderer* renderer); + public: + PreviewRendererIdleState(PreviewRenderer* renderer); - void Start() override; - void Stop() override; - - private: - - //! AZ::TickBus::Handler interface overrides... - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + void Start() override; + void Stop() override; + private: + //! AZ::TickBus::Handler interface overrides... + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp index dcac673de2..b5d219636e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp @@ -6,44 +6,38 @@ * */ -#include -#include +#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + PreviewRendererLoadState::PreviewRendererLoadState(PreviewRenderer* renderer) + : PreviewRendererState(renderer) { - namespace Thumbnails + } + + void PreviewRendererLoadState::Start() + { + m_renderer->LoadAssets(); + m_timeRemainingS = TimeOutS; + AZ::TickBus::Handler::BusConnect(); + } + + void PreviewRendererLoadState::Stop() + { + AZ::TickBus::Handler::BusDisconnect(); + } + + void PreviewRendererLoadState::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + m_timeRemainingS -= deltaTime; + if (m_timeRemainingS > 0.0f) { - CommonPreviewRendererLoadState::CommonPreviewRendererLoadState(CommonPreviewRenderer* renderer) - : CommonPreviewRendererState(renderer) - { - } - - void CommonPreviewRendererLoadState::Start() - { - m_renderer->LoadAssets(); - m_timeRemainingS = TimeOutS; - TickBus::Handler::BusConnect(); - } - - void CommonPreviewRendererLoadState::Stop() - { - TickBus::Handler::BusDisconnect(); - } - - void CommonPreviewRendererLoadState::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) - { - m_timeRemainingS -= deltaTime; - if (m_timeRemainingS > 0.0f) - { - m_renderer->UpdateLoadAssets(); - } - else - { - m_renderer->CancelLoadAssets(); - } - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + m_renderer->UpdateLoadAssets(); + } + else + { + m_renderer->CancelLoadAssets(); + } + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h index 438fd774ca..623d6cbdfc 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h @@ -9,33 +9,26 @@ #pragma once #include -#include +#include -namespace AZ +namespace AtomToolsFramework { - namespace LyIntegration + //! PreviewRendererLoadState pauses further rendering until all assets used for rendering a thumbnail have been loaded + class PreviewRendererLoadState final + : public PreviewRendererState + , public AZ::TickBus::Handler { - namespace Thumbnails - { - //! CommonPreviewRendererLoadState pauses further rendering until all assets used for rendering a thumbnail have been loaded - class CommonPreviewRendererLoadState - : public CommonPreviewRendererState - , private TickBus::Handler - { - public: - CommonPreviewRendererLoadState(CommonPreviewRenderer* renderer); + public: + PreviewRendererLoadState(PreviewRenderer* renderer); - void Start() override; - void Stop() override; + void Start() override; + void Stop() override; - private: - //! AZ::TickBus::Handler interface overrides... - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - - static constexpr float TimeOutS = 5.0f; - float m_timeRemainingS = TimeOutS; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ + private: + //! AZ::TickBus::Handler interface overrides... + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + static constexpr float TimeOutS = 5.0f; + float m_timeRemainingS = TimeOutS; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h deleted file mode 100644 index 9dbf50ab0e..0000000000 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererState.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - class CommonPreviewRenderer; - - //! CommonPreviewRendererState decouples CommonPreviewRenderer logic into easy-to-understand and debug pieces - class CommonPreviewRendererState - { - public: - explicit CommonPreviewRendererState(CommonPreviewRenderer* renderer) : m_renderer(renderer) {} - virtual ~CommonPreviewRendererState() = default; - - //! Start is called when state begins execution - virtual void Start() {} - //! Stop is called when state ends execution - virtual void Stop() {} - - protected: - CommonPreviewRenderer* m_renderer; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 3d4bb82eec..df0dba2678 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -58,4 +58,15 @@ set(FILES Source/Window/AtomToolsMainWindow.cpp Source/Window/AtomToolsMainWindowSystemComponent.cpp Source/Window/AtomToolsMainWindowSystemComponent.h + Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h + Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h + Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h + Include/AtomToolsFramework/PreviewRenderer/PreviewerFeatureProcessorProviderBus.h + Source/PreviewRenderer/PreviewRenderer.cpp + Source/PreviewRenderer/PreviewRendererIdleState.cpp + Source/PreviewRenderer/PreviewRendererIdleState.h + Source/PreviewRenderer/PreviewRendererLoadState.cpp + Source/PreviewRenderer/PreviewRendererLoadState.h + Source/PreviewRenderer/PreviewRendererCaptureState.cpp + Source/PreviewRenderer/PreviewRendererCaptureState.h ) \ No newline at end of file diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h deleted file mode 100644 index bae49db89d..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! PreviewerFeatureProcessorProviderRequests allows registering custom Feature Processors for preview image generation - //! Duplicates will be ignored - //! You can check minimal feature processors that are already registered in CommonPreviewRenderer.cpp - class PreviewerFeatureProcessorProviderRequests - : public AZ::EBusTraits - { - public: - //! Get a list of custom feature processors to register with preview image renderer - virtual void GetRequiredFeatureProcessors(AZStd::unordered_set& featureProcessors) const = 0; - }; - - using PreviewerFeatureProcessorProviderBus = AZ::EBus; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h index 59556e03d1..8520d6053a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace AZ { @@ -23,7 +23,7 @@ namespace AZ { //! Provides custom rendering of material and model previews class CommonThumbnailPreviewContent final - : public CommonPreviewContent + : public AtomToolsFramework::PreviewContent { public: AZ_CLASS_ALLOCATOR(CommonThumbnailPreviewContent, AZ::SystemAllocator, 0); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h index fb683c1aff..0497521d44 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h @@ -8,10 +8,10 @@ #pragma once +#include #include #include #include -#include #include namespace AZ @@ -39,7 +39,7 @@ namespace AZ //! SystemTickBus::Handler interface overrides... void OnSystemTick() override; - CommonPreviewRenderer m_previewRenderer; + AtomToolsFramework::PreviewRenderer m_previewRenderer; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp index 9730c7d4a9..a8692b5eb4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp @@ -14,14 +14,14 @@ #include #include -#include -#include +#include +#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include +#include #include #include AZ_POP_DISABLE_WARNING @@ -73,4 +73,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 3b6212e0eb..db42b663c8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -9,7 +9,6 @@ set(FILES Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h - Include/AtomLyIntegration/CommonFeatures/Thumbnails/PreviewerFeatureProcessorProviderBus.h Source/Module.cpp Source/Animation/EditorAttachmentComponent.h Source/Animation/EditorAttachmentComponent.cpp @@ -98,16 +97,6 @@ set(FILES Source/Thumbnails/Preview/CommonPreviewer.ui Source/Thumbnails/Preview/CommonPreviewerFactory.cpp Source/Thumbnails/Preview/CommonPreviewerFactory.h - Source/Thumbnails/Rendering/CommonPreviewContent.h - Source/Thumbnails/Rendering/CommonPreviewRenderer.cpp - Source/Thumbnails/Rendering/CommonPreviewRenderer.h - Source/Thumbnails/Rendering/CommonPreviewRendererState.h - Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.cpp - Source/Thumbnails/Rendering/CommonPreviewRendererIdleState.h - Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.cpp - Source/Thumbnails/Rendering/CommonPreviewRendererLoadState.h - Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.cpp - Source/Thumbnails/Rendering/CommonPreviewRendererCaptureState.h Source/Thumbnails/CommonThumbnailPreviewContent.cpp Source/Thumbnails/CommonThumbnailPreviewContent.h Source/Thumbnails/CommonThumbnailRenderer.cpp From 4c3d7a7e04de0d9573557bd5a3ba93c3c48c8473 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 8 Oct 2021 16:02:57 -0500 Subject: [PATCH 09/52] Reorganized thumbnail and preview are files into common folder Signed-off-by: Guthrie Adams --- .../EditorCommonFeaturesSystemComponent.cpp | 6 +- .../EditorCommonFeaturesSystemComponent.h | 4 +- .../Source/Previewer/CommonPreviewContent.cpp | 165 +++++++++++++++++ .../Source/Previewer/CommonPreviewContent.h | 78 ++++++++ .../Preview => Previewer}/CommonPreviewer.cpp | 14 +- .../Preview => Previewer}/CommonPreviewer.h | 0 .../Preview => Previewer}/CommonPreviewer.ui | 0 .../CommonPreviewerFactory.cpp | 6 +- .../CommonPreviewerFactory.h | 0 .../CommonThumbnailRenderer.cpp | 8 +- .../CommonThumbnailRenderer.h | 0 .../LightingPresetThumbnail.cpp | 6 +- .../LightingPresetThumbnail.h | 0 .../MaterialThumbnail.cpp | 6 +- .../MaterialThumbnail.h | 0 .../ModelThumbnail.cpp | 6 +- .../ModelThumbnail.h | 0 .../ThumbnailUtils.cpp | 2 +- .../ThumbnailUtils.h | 0 .../CommonThumbnailPreviewContent.cpp | 172 ------------------ .../CommonThumbnailPreviewContent.h | 82 --------- ...egration_commonfeatures_editor_files.cmake | 34 ++-- 22 files changed, 288 insertions(+), 301 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails/Preview => Previewer}/CommonPreviewer.cpp (92%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails/Preview => Previewer}/CommonPreviewer.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails/Preview => Previewer}/CommonPreviewer.ui (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails/Preview => Previewer}/CommonPreviewerFactory.cpp (92%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails/Preview => Previewer}/CommonPreviewerFactory.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/CommonThumbnailRenderer.cpp (93%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/CommonThumbnailRenderer.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/LightingPresetThumbnail.cpp (96%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/LightingPresetThumbnail.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/MaterialThumbnail.cpp (96%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/MaterialThumbnail.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/ModelThumbnail.cpp (96%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/ModelThumbnail.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/ThumbnailUtils.cpp (98%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Thumbnails => Previewer}/ThumbnailUtils.h (100%) delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index c04702ff90..19a7eda24b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -18,9 +18,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h index ed6b3eb426..b9a4151955 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h @@ -13,8 +13,8 @@ #include #include #include -#include -#include +#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp new file mode 100644 index 0000000000..6890fabb01 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + CommonPreviewContent::CommonPreviewContent( + RPI::ScenePtr scene, + RPI::ViewPtr view, + AZ::Uuid entityContextId, + const Data::AssetId& modelAssetId, + const Data::AssetId& materialAssetId, + const Data::AssetId& lightingPresetAssetId) + : m_scene(scene) + , m_view(view) + , m_entityContextId(entityContextId) + { + // Create preview model + AzFramework::EntityContextRequestBus::EventResult( + m_modelEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ThumbnailPreviewModel"); + m_modelEntity->CreateComponent(Render::MeshComponentTypeId); + m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); + m_modelEntity->CreateComponent(azrtti_typeid()); + m_modelEntity->Init(); + m_modelEntity->Activate(); + + m_defaultModelAsset.Create(DefaultModelAssetId, true); + m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); + m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + + m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, false); + m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, false); + m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, false); + } + + CommonPreviewContent::~CommonPreviewContent() + { + if (m_modelEntity) + { + AzFramework::EntityContextRequestBus::Event( + m_entityContextId, &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); + m_modelEntity = nullptr; + } + } + + void CommonPreviewContent::Load() + { + m_modelAsset.QueueLoad(); + m_materialAsset.QueueLoad(); + m_lightingPresetAsset.QueueLoad(); + } + + bool CommonPreviewContent::IsReady() const + { + return (!m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady()) && + (!m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady()) && + (!m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady()); + } + + bool CommonPreviewContent::IsError() const + { + return m_modelAsset.IsError() || m_materialAsset.IsError() || m_lightingPresetAsset.IsError(); + } + + void CommonPreviewContent::ReportErrors() + { + AZ_Warning( + "CommonPreviewContent", !m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady(), "Asset failed to load in time: %s", + m_modelAsset.ToString().c_str()); + AZ_Warning( + "CommonPreviewContent", !m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady(), "Asset failed to load in time: %s", + m_materialAsset.ToString().c_str()); + AZ_Warning( + "CommonPreviewContent", !m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady(), + "Asset failed to load in time: %s", m_lightingPresetAsset.ToString().c_str()); + } + + void CommonPreviewContent::UpdateScene() + { + UpdateModel(); + UpdateLighting(); + UpdateCamera(); + } + + void CommonPreviewContent::UpdateModel() + { + Render::MeshComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); + + Render::MaterialComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, m_materialAsset.GetId()); + } + + void CommonPreviewContent::UpdateLighting() + { + auto preset = m_lightingPresetAsset->GetDataAs(); + if (preset) + { + auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); + auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); + auto directionalLightFeatureProcessor = m_scene->GetFeatureProcessor(); + auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); + skyboxFeatureProcessor->Enable(true); + skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); + + Camera::Configuration cameraConfig; + cameraConfig.m_fovRadians = FieldOfView; + cameraConfig.m_nearClipDistance = NearDist; + cameraConfig.m_farClipDistance = FarDist; + cameraConfig.m_frustumWidth = 100.0f; + cameraConfig.m_frustumHeight = 100.0f; + + AZStd::vector lightHandles; + + preset->ApplyLightingPreset( + iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, + cameraConfig, lightHandles); + } + } + + void CommonPreviewContent::UpdateCamera() + { + // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it + Vector3 center = {}; + float radius = {}; + if (m_modelAsset.IsReady()) + { + m_modelAsset->GetAabb().GetAsSphere(center, radius); + } + + const auto distance = radius + NearDist; + const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); + const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); + const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); + m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); + } + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h new file mode 100644 index 0000000000..482dde2986 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + //! Provides custom rendering of material and model previews + class CommonPreviewContent final : public AtomToolsFramework::PreviewContent + { + public: + AZ_CLASS_ALLOCATOR(CommonPreviewContent, AZ::SystemAllocator, 0); + + CommonPreviewContent( + RPI::ScenePtr scene, + RPI::ViewPtr view, + AZ::Uuid entityContextId, + const Data::AssetId& modelAssetId, + const Data::AssetId& materialAssetId, + const Data::AssetId& lightingPresetAssetId); + + ~CommonPreviewContent() override; + + void Load() override; + bool IsReady() const override; + bool IsError() const override; + void ReportErrors() override; + void UpdateScene() override; + + private: + void UpdateModel(); + void UpdateLighting(); + void UpdateCamera(); + + static constexpr float AspectRatio = 1.0f; + static constexpr float NearDist = 0.001f; + static constexpr float FarDist = 100.0f; + static constexpr float FieldOfView = Constants::HalfPi; + static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; + + RPI::ScenePtr m_scene; + RPI::ViewPtr m_view; + AZ::Uuid m_entityContextId; + Entity* m_modelEntity = nullptr; + + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; + Data::Asset m_lightingPresetAsset; + + //! Model asset about to be rendered + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; + Data::Asset m_modelAsset; + + //! Material asset about to be rendered + static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; + const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); + Data::Asset m_defaultMaterialAsset; + Data::Asset m_materialAsset; + }; + } // namespace LyIntegration +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp similarity index 92% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp index a8692b5eb4..2b5ea7843a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp @@ -7,21 +7,19 @@ */ #include - +#include #include #include -#include -#include #include - -#include -#include +#include +#include +#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include +#include #include #include AZ_POP_DISABLE_WARNING @@ -73,4 +71,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.ui b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.ui similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewer.ui rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.ui diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp similarity index 92% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp index 5b7ef4bfa6..3a6fd2a424 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp @@ -11,9 +11,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/Preview/CommonPreviewerFactory.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp similarity index 93% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp index 63b36b9e14..e9eba7a08d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp @@ -8,9 +8,9 @@ #include #include -#include -#include -#include +#include +#include +#include namespace AZ { @@ -37,7 +37,7 @@ namespace AZ { m_previewRenderer.AddCaptureRequest( { thumbnailSize, - AZStd::make_shared( + AZStd::make_shared( m_previewRenderer.GetScene(), m_previewRenderer.GetView(), m_previewRenderer.GetEntityContextId(), diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailRenderer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp similarity index 96% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp index 8fe4b1998d..566a8d7b58 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp @@ -9,8 +9,8 @@ #include #include #include -#include -#include +#include +#include namespace AZ { @@ -112,4 +112,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/LightingPresetThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp similarity index 96% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp index 69bcffde06..b6a93aa59c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp @@ -9,8 +9,8 @@ #include #include #include -#include -#include +#include +#include namespace AZ { @@ -103,4 +103,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/MaterialThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp similarity index 96% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp index bc47ec04b8..6fe490e9dc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp @@ -9,8 +9,8 @@ #include #include #include -#include -#include +#include +#include namespace AZ { @@ -103,4 +103,4 @@ namespace AZ } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ModelThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp similarity index 98% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ThumbnailUtils.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp index c8f67138ef..8293b33763 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ThumbnailUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/ThumbnailUtils.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp deleted file mode 100644 index f8c508a493..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - CommonThumbnailPreviewContent::CommonThumbnailPreviewContent( - RPI::ScenePtr scene, - RPI::ViewPtr view, - AZ::Uuid entityContextId, - const Data::AssetId& modelAssetId, - const Data::AssetId& materialAssetId, - const Data::AssetId& lightingPresetAssetId) - : m_scene(scene) - , m_view(view) - , m_entityContextId(entityContextId) - { - // Connect camera to pipeline's default view after camera entity activated - Matrix4x4 viewToClipMatrix; - MakePerspectiveFovMatrixRH(viewToClipMatrix, FieldOfView, AspectRatio, NearDist, FarDist, true); - m_view->SetViewToClipMatrix(viewToClipMatrix); - - // Create preview model - AzFramework::EntityContextRequestBus::EventResult( - m_modelEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ThumbnailPreviewModel"); - m_modelEntity->CreateComponent(Render::MeshComponentTypeId); - m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); - m_modelEntity->CreateComponent(azrtti_typeid()); - m_modelEntity->Init(); - m_modelEntity->Activate(); - - m_defaultModelAsset.Create(DefaultModelAssetId, true); - m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); - m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); - - m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, false); - m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, false); - m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, false); - } - - CommonThumbnailPreviewContent::~CommonThumbnailPreviewContent() - { - if (m_modelEntity) - { - AzFramework::EntityContextRequestBus::Event( - m_entityContextId, &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); - m_modelEntity = nullptr; - } - } - - void CommonThumbnailPreviewContent::Load() - { - m_modelAsset.QueueLoad(); - m_materialAsset.QueueLoad(); - m_lightingPresetAsset.QueueLoad(); - } - - bool CommonThumbnailPreviewContent::IsReady() const - { - return (!m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady()) && - (!m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady()) && - (!m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady()); - } - - bool CommonThumbnailPreviewContent::IsError() const - { - return m_modelAsset.IsError() || m_materialAsset.IsError() || m_lightingPresetAsset.IsError(); - } - - void CommonThumbnailPreviewContent::ReportErrors() - { - AZ_Warning( - "CommonThumbnailPreviewContent", !m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady(), - "Asset failed to load in time: %s", m_modelAsset.ToString().c_str()); - AZ_Warning( - "CommonThumbnailPreviewContent", !m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady(), - "Asset failed to load in time: %s", m_materialAsset.ToString().c_str()); - AZ_Warning( - "CommonThumbnailPreviewContent", !m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady(), - "Asset failed to load in time: %s", m_lightingPresetAsset.ToString().c_str()); - } - - void CommonThumbnailPreviewContent::UpdateScene() - { - UpdateModel(); - UpdateLighting(); - UpdateCamera(); - } - - void CommonThumbnailPreviewContent::UpdateModel() - { - Render::MeshComponentRequestBus::Event( - m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); - - Render::MaterialComponentRequestBus::Event( - m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, - m_materialAsset.GetId()); - } - - void CommonThumbnailPreviewContent::UpdateLighting() - { - auto preset = m_lightingPresetAsset->GetDataAs(); - if (preset) - { - auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); - auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); - auto directionalLightFeatureProcessor = - m_scene->GetFeatureProcessor(); - auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); - skyboxFeatureProcessor->Enable(true); - skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); - - Camera::Configuration cameraConfig; - cameraConfig.m_fovRadians = FieldOfView; - cameraConfig.m_nearClipDistance = NearDist; - cameraConfig.m_farClipDistance = FarDist; - cameraConfig.m_frustumWidth = 100.0f; - cameraConfig.m_frustumHeight = 100.0f; - - AZStd::vector lightHandles; - - preset->ApplyLightingPreset( - iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, - cameraConfig, lightHandles); - } - } - - void CommonThumbnailPreviewContent::UpdateCamera() - { - // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it - Vector3 center = {}; - float radius = {}; - m_modelAsset->GetAabb().GetAsSphere(center, radius); - - const auto distance = radius + NearDist; - const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); - const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); - const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); - m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h deleted file mode 100644 index 8520d6053a..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Thumbnails/CommonThumbnailPreviewContent.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! Provides custom rendering of material and model previews - class CommonThumbnailPreviewContent final - : public AtomToolsFramework::PreviewContent - { - public: - AZ_CLASS_ALLOCATOR(CommonThumbnailPreviewContent, AZ::SystemAllocator, 0); - - CommonThumbnailPreviewContent( - RPI::ScenePtr scene, - RPI::ViewPtr view, - AZ::Uuid entityContextId, - const Data::AssetId& modelAssetId, - const Data::AssetId& materialAssetId, - const Data::AssetId& lightingPresetAssetId); - - ~CommonThumbnailPreviewContent() override; - - void Load() override; - bool IsReady() const override; - bool IsError() const override; - void ReportErrors() override; - void UpdateScene() override; - - private: - void UpdateModel(); - void UpdateLighting(); - void UpdateCamera(); - - static constexpr float AspectRatio = 1.0f; - static constexpr float NearDist = 0.001f; - static constexpr float FarDist = 100.0f; - static constexpr float FieldOfView = Constants::HalfPi; - static constexpr float CameraRotationAngle = Constants::QuarterPi / 2.0f; - - RPI::ScenePtr m_scene; - RPI::ViewPtr m_view; - AZ::Uuid m_entityContextId; - Entity* m_modelEntity = nullptr; - - static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); - Data::Asset m_defaultLightingPresetAsset; - Data::Asset m_lightingPresetAsset; - - //! Model asset about to be rendered - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); - Data::Asset m_defaultModelAsset; - Data::Asset m_modelAsset; - - //! Material asset about to be rendered - static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; - const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); - Data::Asset m_defaultMaterialAsset; - Data::Asset m_materialAsset; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index db42b663c8..32f1bd882e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -90,23 +90,23 @@ set(FILES Source/SkyBox/EditorHDRiSkyboxComponent.h Source/SkyBox/EditorPhysicalSkyComponent.cpp Source/SkyBox/EditorPhysicalSkyComponent.h - Source/Thumbnails/ThumbnailUtils.h - Source/Thumbnails/ThumbnailUtils.cpp - Source/Thumbnails/Preview/CommonPreviewer.cpp - Source/Thumbnails/Preview/CommonPreviewer.h - Source/Thumbnails/Preview/CommonPreviewer.ui - Source/Thumbnails/Preview/CommonPreviewerFactory.cpp - Source/Thumbnails/Preview/CommonPreviewerFactory.h - Source/Thumbnails/CommonThumbnailPreviewContent.cpp - Source/Thumbnails/CommonThumbnailPreviewContent.h - Source/Thumbnails/CommonThumbnailRenderer.cpp - Source/Thumbnails/CommonThumbnailRenderer.h - Source/Thumbnails/MaterialThumbnail.cpp - Source/Thumbnails/MaterialThumbnail.h - Source/Thumbnails/ModelThumbnail.cpp - Source/Thumbnails/ModelThumbnail.h - Source/Thumbnails/LightingPresetThumbnail.cpp - Source/Thumbnails/LightingPresetThumbnail.h + Source/Previewer/ThumbnailUtils.h + Source/Previewer/ThumbnailUtils.cpp + Source/Previewer/CommonPreviewer.cpp + Source/Previewer/CommonPreviewer.h + Source/Previewer/CommonPreviewer.ui + Source/Previewer/CommonPreviewerFactory.cpp + Source/Previewer/CommonPreviewerFactory.h + Source/Previewer/CommonPreviewContent.cpp + Source/Previewer/CommonPreviewContent.h + Source/Previewer/CommonThumbnailRenderer.cpp + Source/Previewer/CommonThumbnailRenderer.h + Source/Previewer/MaterialThumbnail.cpp + Source/Previewer/MaterialThumbnail.h + Source/Previewer/ModelThumbnail.cpp + Source/Previewer/ModelThumbnail.h + Source/Previewer/LightingPresetThumbnail.cpp + Source/Previewer/LightingPresetThumbnail.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From 2c6cfdd7dc73a57a1ed1714c8c3a5dacdc1e9258 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sat, 9 Oct 2021 18:17:50 -0500 Subject: [PATCH 10/52] Implemented support for semi-live previews of materials in the material property inspector. Changed thumbnailer bus to use const pixmap Changed capture request call back to use const pixmap instead of image Replaced scene and pipeline members with constructor parameters Added material preview renderer to editor material system component with new requests and notifications Changed material property inspector details group to persistent heading so the preview image widget would not get destroyed during refreshes. But this was also a backlog task. Changed common preview render camera to use lookat Moved default asset caching to thumbnail renderer Signed-off-by: Guthrie Adams --- .../Thumbnails/ThumbnailerBus.h | 2 +- .../Code/Source/Thumbnail/ImageThumbnail.cpp | 2 +- .../Code/Source/Thumbnail/ImageThumbnail.h | 2 +- .../PreviewRenderer/PreviewRenderer.h | 12 +- .../PreviewRenderer/PreviewRenderer.cpp | 25 +-- ...orMaterialSystemComponentNotificationBus.h | 35 ++++ .../EditorMaterialSystemComponentRequestBus.h | 8 +- .../EditorCommonFeaturesSystemComponent.cpp | 2 +- .../EditorMaterialComponentInspector.cpp | 177 +++++++++--------- .../EditorMaterialComponentInspector.h | 21 ++- .../Material/EditorMaterialComponentSlot.cpp | 3 + .../EditorMaterialSystemComponent.cpp | 69 ++++++- .../Material/EditorMaterialSystemComponent.h | 30 ++- .../Source/Previewer/CommonPreviewContent.cpp | 69 ++++--- .../Source/Previewer/CommonPreviewContent.h | 21 +-- .../Previewer/CommonThumbnailRenderer.cpp | 41 ++-- .../Previewer/CommonThumbnailRenderer.h | 18 +- .../Previewer/LightingPresetThumbnail.cpp | 2 +- .../Previewer/LightingPresetThumbnail.h | 2 +- .../Source/Previewer/MaterialThumbnail.cpp | 2 +- .../Code/Source/Previewer/MaterialThumbnail.h | 2 +- .../Code/Source/Previewer/ModelThumbnail.cpp | 2 +- .../Code/Source/Previewer/ModelThumbnail.h | 2 +- .../Code/Source/Previewer/ThumbnailUtils.cpp | 13 +- .../Code/Source/Previewer/ThumbnailUtils.h | 5 +- ...egration_commonfeatures_editor_files.cmake | 1 + 26 files changed, 365 insertions(+), 203 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerBus.h index 6f074da878..acd8ba3966 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerBus.h @@ -90,7 +90,7 @@ namespace AzToolsFramework typedef SharedThumbnailKey BusIdType; //! notify product thumbnail that the data is ready - virtual void ThumbnailRendered(QPixmap& thumbnailImage) = 0; + virtual void ThumbnailRendered(const QPixmap& thumbnailImage) = 0; //! notify product thumbnail that the thumbnail failed to render virtual void ThumbnailFailedToRender() = 0; }; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.cpp index 084e38a2db..cdd63dca18 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.cpp @@ -67,7 +67,7 @@ namespace ImageProcessingAtom m_renderWait.acquire(); } - void ImageThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + void ImageThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) { m_pixmap = thumbnailImage; m_renderWait.release(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.h index 45fd178285..eadbfca945 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Thumbnail/ImageThumbnail.h @@ -34,7 +34,7 @@ namespace ImageProcessingAtom ~ImageThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(QPixmap& thumbnailImage) override; + void ThumbnailRendered(const QPixmap& thumbnailImage) override; void ThumbnailFailedToRender() override; protected: diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h index b772bfcaf2..acedc77751 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h @@ -20,7 +20,7 @@ namespace AzFramework class Scene; } -class QImage; +class QPixmap; namespace AtomToolsFramework { @@ -30,7 +30,7 @@ namespace AtomToolsFramework public: AZ_CLASS_ALLOCATOR(PreviewRenderer, AZ::SystemAllocator, 0); - PreviewRenderer(); + PreviewRenderer(const AZStd::string& sceneName, const AZStd::string& pipelineName); ~PreviewRenderer(); struct CaptureRequest final @@ -38,15 +38,15 @@ namespace AtomToolsFramework int m_size = 512; AZStd::shared_ptr m_content; AZStd::function m_captureFailedCallback; - AZStd::function m_captureCompleteCallback; + AZStd::function m_captureCompleteCallback; }; + void AddCaptureRequest(const CaptureRequest& captureRequest); + AZ::RPI::ScenePtr GetScene() const; AZ::RPI::ViewPtr GetView() const; AZ::Uuid GetEntityContextId() const; - void AddCaptureRequest(const CaptureRequest& captureRequest); - enum class State : AZ::s8 { None, @@ -81,8 +81,6 @@ namespace AtomToolsFramework static constexpr float FieldOfView = AZ::Constants::HalfPi; AZ::RPI::ScenePtr m_scene; - AZStd::string m_sceneName = "Preview Renderer Scene"; - AZStd::string m_pipelineName = "Preview Renderer Pipeline"; AZStd::shared_ptr m_frameworkScene; AZ::RPI::RenderPipelinePtr m_renderPipeline; AZ::RPI::ViewPtr m_view; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index dfefd0203e..06969abee4 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -24,9 +24,12 @@ #include #include +#include +#include + namespace AtomToolsFramework { - PreviewRenderer::PreviewRenderer() + PreviewRenderer::PreviewRenderer(const AZStd::string& sceneName, const AZStd::string& pipelineName) { PreviewerFeatureProcessorProviderBus::Handler::BusConnect(); @@ -46,7 +49,7 @@ namespace AtomToolsFramework auto sceneSystem = AzFramework::SceneSystemInterface::Get(); AZ_Assert(sceneSystem, "Failed to get scene system implementation."); - AZ::Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(m_sceneName); + AZ::Outcome, AZStd::string> createSceneOutcome = sceneSystem->CreateScene(sceneName); AZ_Assert(createSceneOutcome, createSceneOutcome.GetError().c_str()); m_frameworkScene = createSceneOutcome.TakeValue(); @@ -56,7 +59,7 @@ namespace AtomToolsFramework // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene AZ::RPI::RenderPipelineDescriptor pipelineDesc; pipelineDesc.m_mainViewTagName = "MainCamera"; - pipelineDesc.m_name = m_pipelineName; + pipelineDesc.m_name = pipelineName; pipelineDesc.m_rootPassTemplate = "MainPipelineRenderToTexture"; // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue @@ -66,7 +69,7 @@ namespace AtomToolsFramework m_scene->AddRenderPipeline(m_renderPipeline); m_scene->Activate(); AZ::RPI::RPISystemInterface::Get()->RegisterScene(m_scene); - m_passHierarchy.push_back(m_pipelineName); + m_passHierarchy.push_back(pipelineName); m_passHierarchy.push_back("CopyToSwapChain"); // Connect camera to pipeline's default view after camera entity activated @@ -97,6 +100,11 @@ namespace AtomToolsFramework m_frameworkScene->UnsetSubsystem(m_entityContext.get()); } + void PreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) + { + m_captureRequestQueue.push(captureRequest); + } + AZ::RPI::ScenePtr PreviewRenderer::GetScene() const { return m_scene; @@ -112,11 +120,6 @@ namespace AtomToolsFramework return m_entityContext->GetContextId(); } - void PreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) - { - m_captureRequestQueue.push(captureRequest); - } - void PreviewRenderer::SetState(State state) { auto stepItr = m_states.find(m_currentState); @@ -199,9 +202,9 @@ namespace AtomToolsFramework { if (result.m_dataBuffer) { - currentCaptureRequest.m_captureCompleteCallback(QImage( + currentCaptureRequest.m_captureCompleteCallback(QPixmap::fromImage(QImage( result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, result.m_imageDescriptor.m_size.m_height, - QImage::Format_RGBA8888)); + QImage::Format_RGBA8888))); } else { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h new file mode 100644 index 0000000000..4e655c7835 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include +#include + +class QPixmap; + +namespace AZ +{ + namespace Render + { + //! EditorMaterialSystemComponentNotifications provides an interface to communicate with EditorMaterialSystemComponent + class EditorMaterialSystemComponentNotifications : public AZ::EBusTraits + { + public: + // Only a single handler is allowed + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + + //! Notify that a material preview image is ready + virtual void OnRenderMaterialPreviewComplete( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId, const QPixmap& pixmap) = 0; + }; + using EditorMaterialSystemComponentNotificationBus = AZ::EBus; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h index 47fad038b6..059e6dec8e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h @@ -5,6 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #pragma once #include @@ -17,8 +18,7 @@ namespace AZ namespace Render { //! EditorMaterialSystemComponentRequests provides an interface to communicate with MaterialEditor - class EditorMaterialSystemComponentRequests - : public AZ::EBusTraits + class EditorMaterialSystemComponentRequests : public AZ::EBusTraits { public: // Only a single handler is allowed @@ -31,6 +31,10 @@ namespace AZ //! Open material instance editor virtual void OpenMaterialInspector( const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) = 0; + + //! Generate a material preview image + virtual void RenderMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) = 0; }; using EditorMaterialSystemComponentRequestBus = AZ::EBus; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 19a7eda24b..34cd9f59d0 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -98,9 +98,9 @@ namespace AZ void EditorCommonFeaturesSystemComponent::Deactivate() { - AzToolsFramework::EditorLevelNotificationBus::Handler::BusDisconnect(); AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); + AzToolsFramework::EditorLevelNotificationBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusDisconnect(); m_skinnedMeshDebugDisplay.reset(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 665adcd568..7562049031 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -23,10 +23,6 @@ #include #include #include -#include -#include -#include -#include #include #include #include @@ -49,29 +45,18 @@ namespace AZ MaterialPropertyInspector::MaterialPropertyInspector(QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) { - // Create the menu button - QToolButton* menuButton = new QToolButton(this); - menuButton->setAutoRaise(true); - menuButton->setIcon(QIcon(":/Cards/img/UI20/Cards/menu_ico.svg")); - menuButton->setVisible(true); - QObject::connect(menuButton, &QToolButton::clicked, this, [this]() { OpenMenu(); }); - AddHeading(menuButton); - - m_messageLabel = new QLabel(this); - m_messageLabel->setWordWrap(true); - m_messageLabel->setVisible(true); - m_messageLabel->setAlignment(Qt::AlignCenter); - m_messageLabel->setText(tr("Material not available")); - AddHeading(m_messageLabel); - + CreateHeading(); + AZ::TickBus::Handler::BusConnect(); AZ::EntitySystemBus::Handler::BusConnect(); + EditorMaterialSystemComponentNotificationBus::Handler::BusConnect(); } MaterialPropertyInspector::~MaterialPropertyInspector() { AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); - AZ::EntitySystemBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); + AZ::EntitySystemBus::Handler::BusDisconnect(); + EditorMaterialSystemComponentNotificationBus::Handler::BusDisconnect(); MaterialComponentNotificationBus::Handler::BusDisconnect(); } @@ -140,7 +125,7 @@ namespace AZ } Populate(); - m_messageLabel->setVisible(false); + LoadOverridesFromEntity(); return true; } @@ -152,8 +137,9 @@ namespace AZ m_dirtyPropertyFlags.set(); m_editorFunctors = {}; m_internalEditNotification = {}; - m_messageLabel->setVisible(true); - m_messageLabel->setText(tr("Material not available")); + m_updateUI = {}; + m_updatePreview = {}; + UpdateHeading(); } bool MaterialPropertyInspector::IsLoaded() const @@ -168,49 +154,62 @@ namespace AZ m_dirtyPropertyFlags.set(); m_internalEditNotification = {}; - AZ::TickBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorWidget::Reset(); } - void MaterialPropertyInspector::AddDetailsGroup() + void MaterialPropertyInspector::CreateHeading() { - const AZStd::string& groupName = "Details"; - const AZStd::string& groupDisplayName = "Details"; - const AZStd::string& groupDescription = ""; + // Create the menu button + QToolButton* menuButton = new QToolButton(this); + menuButton->setAutoRaise(true); + menuButton->setIcon(QIcon(":/Cards/img/UI20/Cards/menu_ico.svg")); + menuButton->setVisible(true); + QObject::connect(menuButton, &QToolButton::clicked, this, [this]() { OpenMenu(); }); + AddHeading(menuButton); - auto propertyGroupContainer = new QWidget(this); - propertyGroupContainer->setLayout(new QHBoxLayout()); + m_overviewImage = new QLabel(this); + m_overviewImage->setFixedSize(QSize(120, 120)); + m_overviewImage->setVisible(false); - AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey = - MAKE_TKEY(AzToolsFramework::AssetBrowser::ProductThumbnailKey, m_editData.m_materialAssetId); - auto thumbnailWidget = new AzToolsFramework::Thumbnailer::ThumbnailWidget(this); - thumbnailWidget->setFixedSize(QSize(120, 120)); - thumbnailWidget->setVisible(true); - thumbnailWidget->SetThumbnailKey(thumbnailKey, AzToolsFramework::Thumbnailer::ThumbnailContext::DefaultContext); - propertyGroupContainer->layout()->addWidget(thumbnailWidget); - - auto materialInfoWidget = new QLabel(this); + m_overviewText = new QLabel(this); QSizePolicy sizePolicy1(QSizePolicy::Ignored, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); - sizePolicy1.setHeightForWidth(materialInfoWidget->sizePolicy().hasHeightForWidth()); - materialInfoWidget->setSizePolicy(sizePolicy1); - materialInfoWidget->setMinimumSize(QSize(0, 0)); - materialInfoWidget->setMaximumSize(QSize(16777215, 16777215)); - materialInfoWidget->setTextFormat(Qt::AutoText); - materialInfoWidget->setScaledContents(false); - materialInfoWidget->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignTop); - materialInfoWidget->setWordWrap(true); + sizePolicy1.setHeightForWidth(m_overviewText->sizePolicy().hasHeightForWidth()); + m_overviewText->setSizePolicy(sizePolicy1); + m_overviewText->setMinimumSize(QSize(0, 0)); + m_overviewText->setMaximumSize(QSize(16777215, 16777215)); + m_overviewText->setTextFormat(Qt::AutoText); + m_overviewText->setScaledContents(false); + m_overviewText->setWordWrap(true); + m_overviewText->setVisible(true); + + auto overviewContainer = new QWidget(this); + overviewContainer->setLayout(new QHBoxLayout()); + overviewContainer->layout()->addWidget(m_overviewImage); + overviewContainer->layout()->addWidget(m_overviewText); + AddHeading(overviewContainer); + } + + void MaterialPropertyInspector::UpdateHeading() + { + if (!IsLoaded()) + { + m_overviewText->setText(tr("Material not available")); + m_overviewText->setAlignment(Qt::AlignCenter); + m_overviewImage->setVisible(false); + return; + } QFileInfo materialFileInfo(AZ::RPI::AssetUtils::GetProductPathByAssetId(m_editData.m_materialAsset.GetId()).c_str()); QFileInfo materialSourceFileInfo(m_editData.m_materialSourcePath.c_str()); QFileInfo materialTypeSourceFileInfo(m_editData.m_materialTypeSourcePath.c_str()); - QFileInfo materialParentSourceFileInfo(AZ::RPI::AssetUtils::GetSourcePathByAssetId(m_editData.m_materialParentAsset.GetId()).c_str()); + QFileInfo materialParentSourceFileInfo( + AZ::RPI::AssetUtils::GetSourcePathByAssetId(m_editData.m_materialParentAsset.GetId()).c_str()); AZStd::string entityName; - AZ::ComponentApplicationBus::BroadcastResult( - entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, m_entityId); + AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, m_entityId); AZStd::string slotName; MaterialComponentRequestBus::EventResult( @@ -226,7 +225,8 @@ namespace AZ } if (!materialTypeSourceFileInfo.fileName().isEmpty()) { - materialInfo += tr("Material Type %1").arg(materialTypeSourceFileInfo.fileName()); + materialInfo += + tr("Material Type %1").arg(materialTypeSourceFileInfo.fileName()); } if (!materialSourceFileInfo.fileName().isEmpty()) { @@ -234,14 +234,15 @@ namespace AZ } if (!materialParentSourceFileInfo.fileName().isEmpty()) { - materialInfo += tr("Material Parent %1").arg(materialParentSourceFileInfo.fileName()); + materialInfo += + tr("Material Parent %1").arg(materialParentSourceFileInfo.fileName()); } materialInfo += tr(""); - materialInfoWidget->setText(materialInfo); - propertyGroupContainer->layout()->addWidget(materialInfoWidget); - - AddGroup(groupName, groupDisplayName, groupDescription, propertyGroupContainer); + m_overviewText->setText(materialInfo); + m_overviewText->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignTop); + m_overviewImage->setVisible(true); + m_updatePreview = true; } void MaterialPropertyInspector::AddUvNamesGroup() @@ -282,13 +283,8 @@ namespace AZ AddGroup(groupName, groupDisplayName, groupDescription, propertyGroupWidget); } - void MaterialPropertyInspector::Populate() + void MaterialPropertyInspector::AddPropertiesGroup() { - AddGroupsBegin(); - - AddDetailsGroup(); - AddUvNamesGroup(); - // Copy all of the properties from the material asset to the source data that will be exported for (const auto& groupDefinition : m_editData.m_materialTypeSourceData.GetGroupDefinitionsInDisplayOrder()) { @@ -327,10 +323,14 @@ namespace AZ [this](const auto node) { return GetInstanceNodePropertyIndicator(node); }, 0); AddGroup(groupName, groupDisplayName, groupDescription, propertyGroupWidget); } + } + void MaterialPropertyInspector::Populate() + { + AddGroupsBegin(); + AddUvNamesGroup(); + AddPropertiesGroup(); AddGroupsEnd(); - - LoadOverridesFromEntity(); } void MaterialPropertyInspector::LoadOverridesFromEntity() @@ -375,6 +375,7 @@ namespace AZ m_dirtyPropertyFlags.set(); RunEditorMaterialFunctors(); RebuildAll(); + UpdateHeading(); } void MaterialPropertyInspector::SaveOverridesToEntity(bool commitChanges) @@ -398,6 +399,8 @@ namespace AZ MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited); m_internalEditNotification = false; } + + m_updatePreview = true; } void MaterialPropertyInspector::RunEditorMaterialFunctors() @@ -607,7 +610,8 @@ namespace AZ MaterialComponentRequestBus::Event( m_entityId, &MaterialComponentRequestBus::Events::SetPropertyOverrides, m_materialAssignmentId, MaterialPropertyOverrideMap()); - QueueUpdateUI(); + m_updateUI = true; + m_updatePreview = true; }); action->setEnabled(IsLoaded()); @@ -702,10 +706,7 @@ namespace AZ void MaterialPropertyInspector::OnEntityActivated(const AZ::EntityId& entityId) { - if (m_entityId == entityId) - { - QueueUpdateUI(); - } + m_updateUI |= (m_entityId == entityId); } void MaterialPropertyInspector::OnEntityDeactivated(const AZ::EntityId& entityId) @@ -719,25 +720,39 @@ namespace AZ void MaterialPropertyInspector::OnEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name) { AZ_UNUSED(name); - if (m_entityId == entityId) - { - QueueUpdateUI(); - } + m_updateUI |= (m_entityId == entityId); } void MaterialPropertyInspector::OnTick(float deltaTime, ScriptTimePoint time) { AZ_UNUSED(time); AZ_UNUSED(deltaTime); - UpdateUI(); - AZ::TickBus::Handler::BusDisconnect(); + if (m_updateUI) + { + m_updateUI = false; + UpdateUI(); + } + + if (m_updatePreview) + { + m_updatePreview = false; + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::RenderMaterialPreview, m_entityId, m_materialAssignmentId); + } } void MaterialPropertyInspector::OnMaterialsEdited() { - if (!m_internalEditNotification) + m_updateUI |= !m_internalEditNotification; + m_updatePreview = true; + } + + void MaterialPropertyInspector::OnRenderMaterialPreviewComplete( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId, const QPixmap& pixmap) + { + if (m_overviewImage && m_entityId == entityId && m_materialAssignmentId == materialAssignmentId) { - QueueUpdateUI(); + m_overviewImage->setPixmap(pixmap); } } @@ -761,14 +776,6 @@ namespace AZ LoadMaterial(m_entityId, m_materialAssignmentId); } } - - void MaterialPropertyInspector::QueueUpdateUI() - { - if (!AZ::TickBus::Handler::BusIsConnected()) - { - AZ::TickBus::Handler::BusConnect(); - } - } } // namespace EditorMaterialComponentInspector } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h index 048c1e19cb..6199fba179 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h @@ -9,6 +9,7 @@ #pragma once #if !defined(Q_MOC_RUN) +#include #include #include #include @@ -39,6 +40,7 @@ namespace AZ , public AZ::EntitySystemBus::Handler , public AZ::TickBus::Handler , public MaterialComponentNotificationBus::Handler + , public EditorMaterialSystemComponentNotificationBus::Handler { Q_OBJECT public: @@ -89,11 +91,19 @@ namespace AZ //! MaterialComponentNotificationBus::Handler overrides... void OnMaterialsEdited() override; - void UpdateUI(); - void QueueUpdateUI(); + //! EditorMaterialSystemComponentNotificationBus::Handler overrides... + void OnRenderMaterialPreviewComplete( + const AZ::EntityId& entityId, + const AZ::Render::MaterialAssignmentId& materialAssignmentId, + const QPixmap& pixmap) override; + + void UpdateUI(); + + void CreateHeading(); + void UpdateHeading(); - void AddDetailsGroup(); void AddUvNamesGroup(); + void AddPropertiesGroup(); void LoadOverridesFromEntity(); void SaveOverridesToEntity(bool commitChanges); @@ -115,7 +125,10 @@ namespace AZ AZ::RPI::MaterialPropertyFlags m_dirtyPropertyFlags = {}; AZStd::unordered_map m_groups = {}; bool m_internalEditNotification = {}; - QLabel* m_messageLabel = {}; + bool m_updateUI = {}; + bool m_updatePreview = {}; + QLabel* m_overviewText = {}; + QLabel* m_overviewImage = {}; }; } // namespace EditorMaterialComponentInspector } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index f5d38f48c4..21d045a072 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -315,6 +315,9 @@ namespace AZ AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast( &AzToolsFramework::ToolsApplicationRequests::Bus::Events::AddDirtyEntity, m_entityId); + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::RenderMaterialPreview, m_entityId, m_id); + MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited); AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index 9efa8eb333..e18cc0b907 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -6,7 +6,10 @@ * */ +#include #include +#include +#include #include #include #include @@ -19,6 +22,7 @@ #include #include #include +#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class @@ -28,6 +32,8 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") #include #include #include +#include +#include #include AZ_POP_DISABLE_WARNING @@ -86,17 +92,20 @@ namespace AZ AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); - - m_materialBrowserInteractions.reset(aznew MaterialBrowserInteractions); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); + AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); } void EditorMaterialSystemComponent::Deactivate() { + AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); + AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); EditorMaterialSystemComponentRequestBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); + m_previewRenderer.reset(); m_materialBrowserInteractions.reset(); if (m_openMaterialEditorAction) @@ -143,6 +152,47 @@ namespace AZ } } + void EditorMaterialSystemComponent::RenderMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) + { + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + + if (m_previewRenderer) + { + AZ::Data::AssetId materialAssetId = {}; + MaterialComponentRequestBus::EventResult( + materialAssetId, entityId, &MaterialComponentRequestBus::Events::GetMaterialOverride, materialAssignmentId); + if (!materialAssetId.IsValid()) + { + MaterialComponentRequestBus::EventResult( + materialAssetId, entityId, &MaterialComponentRequestBus::Events::GetDefaultMaterialAssetId, materialAssignmentId); + } + + AZ::Render::MaterialPropertyOverrideMap propertyOverrides; + AZ::Render::MaterialComponentRequestBus::EventResult( + propertyOverrides, entityId, &AZ::Render::MaterialComponentRequestBus::Events::GetPropertyOverrides, + materialAssignmentId); + + m_previewRenderer->AddCaptureRequest( + { 128, + AZStd::make_shared( + m_previewRenderer->GetScene(), m_previewRenderer->GetView(), m_previewRenderer->GetEntityContextId(), + AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath), materialAssetId, + AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath), propertyOverrides), + []() + { + // failed + }, + [entityId, materialAssignmentId](const QPixmap& pixmap) + { + AZ::Render::EditorMaterialSystemComponentNotificationBus::Broadcast( + &AZ::Render::EditorMaterialSystemComponentNotificationBus::Events::OnRenderMaterialPreviewComplete, entityId, + materialAssignmentId, pixmap); + } }); + } + } + void EditorMaterialSystemComponent::OnPopulateToolMenuItems() { if (!m_openMaterialEditorAction) @@ -185,6 +235,21 @@ namespace AZ "Material Property Inspector", LyViewPane::CategoryTools, inspectorOptions); } + void EditorMaterialSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) + { + AZ::TickBus::QueueFunction([this](){ + m_materialBrowserInteractions.reset(aznew MaterialBrowserInteractions); + m_previewRenderer.reset(aznew AtomToolsFramework::PreviewRenderer( + "EditorMaterialSystemComponent Preview Scene", "EditorMaterialSystemComponent Preview Pipeline")); + }); + } + + void EditorMaterialSystemComponent::OnApplicationAboutToStop() + { + m_previewRenderer.reset(); + m_materialBrowserInteractions.reset(); + } + AzToolsFramework::AssetBrowser::SourceFileDetails EditorMaterialSystemComponent::GetSourceFileDetails( const char* fullSourceFileName) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h index 60e489f55e..f2ccbdc435 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h @@ -7,13 +7,14 @@ */ #pragma once +#include +#include +#include #include +#include #include #include #include - -#include - #include namespace AZ @@ -21,12 +22,14 @@ namespace AZ namespace Render { //! System component that manages launching and maintaining connections with the material editor. - class EditorMaterialSystemComponent + class EditorMaterialSystemComponent final : public AZ::Component - , private EditorMaterialSystemComponentRequestBus::Handler - , private AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler - , private AzToolsFramework::EditorMenuNotificationBus::Handler - , private AzToolsFramework::EditorEvents::Bus::Handler + , public EditorMaterialSystemComponentRequestBus::Handler + , public AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler + , public AzToolsFramework::EditorMenuNotificationBus::Handler + , public AzToolsFramework::EditorEvents::Bus::Handler + , public AzFramework::AssetCatalogEventBus::Handler + , public AzFramework::ApplicationLifecycleEvents::Bus::Handler { public: AZ_COMPONENT(EditorMaterialSystemComponent, "{96652157-DA0B-420F-B49C-0207C585144C}"); @@ -47,6 +50,8 @@ namespace AZ //! EditorMaterialSystemComponentRequestBus::Handler overrides... void OpenMaterialEditor(const AZStd::string& sourcePath) override; void OpenMaterialInspector(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; + void RenderMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; //! AssetBrowserInteractionNotificationBus::Handler overrides... AzToolsFramework::AssetBrowser::SourceFileDetails GetSourceFileDetails(const char* fullSourceFileName) override; @@ -58,9 +63,16 @@ namespace AZ // AztoolsFramework::EditorEvents::Bus::Handler overrides... void NotifyRegisterViews() override; - QAction* m_openMaterialEditorAction = nullptr; + // AzFramework::AssetCatalogEventBus::Handler overrides ... + void OnCatalogLoaded(const char* catalogFile) override; + + // AzFramework::ApplicationLifecycleEvents overrides... + void OnApplicationAboutToStop() override; + + QAction* m_openMaterialEditorAction = nullptr; AZStd::unique_ptr m_materialBrowserInteractions; + AZStd::unique_ptr m_previewRenderer; }; } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp index 6890fabb01..966877317c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp @@ -35,10 +35,12 @@ namespace AZ AZ::Uuid entityContextId, const Data::AssetId& modelAssetId, const Data::AssetId& materialAssetId, - const Data::AssetId& lightingPresetAssetId) + const Data::AssetId& lightingPresetAssetId, + const Render::MaterialPropertyOverrideMap& materialPropertyOverrides) : m_scene(scene) , m_view(view) , m_entityContextId(entityContextId) + , m_materialPropertyOverrides(materialPropertyOverrides) { // Create preview model AzFramework::EntityContextRequestBus::EventResult( @@ -49,13 +51,9 @@ namespace AZ m_modelEntity->Init(); m_modelEntity->Activate(); - m_defaultModelAsset.Create(DefaultModelAssetId, true); - m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); - m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); - - m_modelAsset.Create(modelAssetId.IsValid() ? modelAssetId : DefaultModelAssetId, false); - m_materialAsset.Create(materialAssetId.IsValid() ? materialAssetId : DefaultMaterialAssetId, false); - m_lightingPresetAsset.Create(lightingPresetAssetId.IsValid() ? lightingPresetAssetId : DefaultLightingPresetAssetId, false); + m_modelAsset.Create(modelAssetId); + m_materialAsset.Create(materialAssetId); + m_lightingPresetAsset.Create(lightingPresetAssetId); } CommonPreviewContent::~CommonPreviewContent() @@ -113,35 +111,44 @@ namespace AZ m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); Render::MaterialComponentRequestBus::Event( - m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetDefaultMaterialOverride, m_materialAsset.GetId()); + m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetMaterialOverride, + Render::DefaultMaterialAssignmentId, m_materialAsset.GetId()); + + Render::MaterialComponentRequestBus::Event( + m_modelEntity->GetId(), &Render::MaterialComponentRequestBus::Events::SetPropertyOverrides, + Render::DefaultMaterialAssignmentId, m_materialPropertyOverrides); } void CommonPreviewContent::UpdateLighting() { - auto preset = m_lightingPresetAsset->GetDataAs(); - if (preset) + if (m_lightingPresetAsset.IsReady()) { - auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); - auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); - auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); - auto directionalLightFeatureProcessor = m_scene->GetFeatureProcessor(); - auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); - skyboxFeatureProcessor->Enable(true); - skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); + auto preset = m_lightingPresetAsset->GetDataAs(); + if (preset) + { + auto iblFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessFeatureProcessor = m_scene->GetFeatureProcessor(); + auto postProcessSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(EntityId()); + auto exposureControlSettingInterface = postProcessSettingInterface->GetOrCreateExposureControlSettingsInterface(); + auto directionalLightFeatureProcessor = + m_scene->GetFeatureProcessor(); + auto skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); + skyboxFeatureProcessor->Enable(true); + skyboxFeatureProcessor->SetSkyboxMode(Render::SkyBoxMode::Cubemap); - Camera::Configuration cameraConfig; - cameraConfig.m_fovRadians = FieldOfView; - cameraConfig.m_nearClipDistance = NearDist; - cameraConfig.m_farClipDistance = FarDist; - cameraConfig.m_frustumWidth = 100.0f; - cameraConfig.m_frustumHeight = 100.0f; + Camera::Configuration cameraConfig; + cameraConfig.m_fovRadians = FieldOfView; + cameraConfig.m_nearClipDistance = NearDist; + cameraConfig.m_farClipDistance = FarDist; + cameraConfig.m_frustumWidth = 100.0f; + cameraConfig.m_frustumHeight = 100.0f; - AZStd::vector lightHandles; + AZStd::vector lightHandles; - preset->ApplyLightingPreset( - iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, - cameraConfig, lightHandles); + preset->ApplyLightingPreset( + iblFeatureProcessor, skyboxFeatureProcessor, exposureControlSettingInterface, directionalLightFeatureProcessor, + cameraConfig, lightHandles); + } } } @@ -157,8 +164,8 @@ namespace AZ const auto distance = radius + NearDist; const auto cameraRotation = Quaternion::CreateFromAxisAngle(Vector3::CreateAxisZ(), CameraRotationAngle); - const auto cameraPosition = center - cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); - const auto cameraTransform = Transform::CreateFromQuaternionAndTranslation(cameraRotation, cameraPosition); + const auto cameraPosition = center + cameraRotation.TransformVector(Vector3(0.0f, distance, 0.0f)); + const auto cameraTransform = Transform::CreateLookAt(cameraPosition, center); m_view->SetCameraTransform(Matrix3x4::CreateFromTransform(cameraTransform)); } } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h index 482dde2986..a6bb2f6c4e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h @@ -8,8 +8,8 @@ #pragma once +#include #include -#include #include #include #include @@ -31,7 +31,8 @@ namespace AZ AZ::Uuid entityContextId, const Data::AssetId& modelAssetId, const Data::AssetId& materialAssetId, - const Data::AssetId& lightingPresetAssetId); + const Data::AssetId& lightingPresetAssetId, + const Render::MaterialPropertyOverrideMap& materialPropertyOverrides); ~CommonPreviewContent() override; @@ -57,22 +58,10 @@ namespace AZ AZ::Uuid m_entityContextId; Entity* m_modelEntity = nullptr; - static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); - Data::Asset m_defaultLightingPresetAsset; - Data::Asset m_lightingPresetAsset; - - //! Model asset about to be rendered - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); - Data::Asset m_defaultModelAsset; Data::Asset m_modelAsset; - - //! Material asset about to be rendered - static constexpr const char* DefaultMaterialPath = "materials/basic_grey.azmaterial"; - const Data::AssetId DefaultMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultMaterialPath); - Data::Asset m_defaultMaterialAsset; Data::Asset m_materialAsset; + Data::Asset m_lightingPresetAsset; + Render::MaterialPropertyOverrideMap m_materialPropertyOverrides; }; } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp index e9eba7a08d..f29762b563 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp @@ -20,6 +20,13 @@ namespace AZ { CommonThumbnailRenderer::CommonThumbnailRenderer() { + m_previewRenderer.reset(aznew AtomToolsFramework::PreviewRenderer( + "CommonThumbnailRenderer Preview Scene", "CommonThumbnailRenderer Preview Pipeline")); + + m_defaultModelAsset.Create(DefaultModelAssetId, true); + m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); + m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + // CommonThumbnailRenderer supports both models and materials AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); @@ -35,26 +42,24 @@ namespace AZ void CommonThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) { - m_previewRenderer.AddCaptureRequest( + m_previewRenderer->AddCaptureRequest( { thumbnailSize, AZStd::make_shared( - m_previewRenderer.GetScene(), - m_previewRenderer.GetView(), - m_previewRenderer.GetEntityContextId(), - GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type()), - GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type()), - GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type())), - [thumbnailKey]() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - }, - [thumbnailKey](const QImage& image) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, - QPixmap::fromImage(image)); - } }); + m_previewRenderer->GetScene(), m_previewRenderer->GetView(), m_previewRenderer->GetEntityContextId(), + GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type(), DefaultModelAssetId), + GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type(), DefaultMaterialAssetId), + GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type(), DefaultLightingPresetAssetId), + Render::MaterialPropertyOverrideMap()), + [thumbnailKey]() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + }, + [thumbnailKey](const QPixmap& pixmap) + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, pixmap); + } }); } bool CommonThumbnailRenderer::Installed() const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h index 0497521d44..a57c3dae8e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h @@ -8,6 +8,10 @@ #pragma once +#include +#include +#include +#include #include #include #include @@ -39,7 +43,19 @@ namespace AZ //! SystemTickBus::Handler interface overrides... void OnSystemTick() override; - AtomToolsFramework::PreviewRenderer m_previewRenderer; + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; + + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; + + static constexpr const char* DefaultMaterialPath = ""; + const Data::AssetId DefaultMaterialAssetId; + Data::Asset m_defaultMaterialAsset; + + AZStd::unique_ptr m_previewRenderer; }; } // namespace Thumbnails } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp index 566a8d7b58..6a9c2ca2ca 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp @@ -53,7 +53,7 @@ namespace AZ AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); } - void LightingPresetThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + void LightingPresetThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) { m_pixmap = thumbnailImage; m_renderWait.release(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h index efbfe5b7d5..437a372c3c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h @@ -33,7 +33,7 @@ namespace AZ ~LightingPresetThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(QPixmap& thumbnailImage) override; + void ThumbnailRendered(const QPixmap& thumbnailImage) override; void ThumbnailFailedToRender() override; protected: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp index b6a93aa59c..b9a3412d0e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp @@ -53,7 +53,7 @@ namespace AZ AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); } - void MaterialThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + void MaterialThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) { m_pixmap = thumbnailImage; m_renderWait.release(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h index 9a580d07ce..1349336245 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h @@ -33,7 +33,7 @@ namespace AZ ~MaterialThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(QPixmap& thumbnailImage) override; + void ThumbnailRendered(const QPixmap& thumbnailImage) override; void ThumbnailFailedToRender() override; protected: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp index 6fe490e9dc..e3eb7a3af6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp @@ -53,7 +53,7 @@ namespace AZ AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); } - void ModelThumbnail::ThumbnailRendered(QPixmap& thumbnailImage) + void ModelThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) { m_pixmap = thumbnailImage; m_renderWait.release(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h index 2925abe36e..5d9449e988 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h @@ -33,7 +33,7 @@ namespace AZ ~ModelThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(QPixmap& thumbnailImage) override; + void ThumbnailRendered(const QPixmap& thumbnailImage) override; void ThumbnailFailedToRender() override; protected: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp index 8293b33763..6d3d07faef 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp @@ -19,10 +19,11 @@ namespace AZ { namespace Thumbnails { - Data::AssetId GetAssetId(AzToolsFramework::Thumbnailer::SharedThumbnailKey key, const Data::AssetType& assetType) + Data::AssetId GetAssetId( + AzToolsFramework::Thumbnailer::SharedThumbnailKey key, + const Data::AssetType& assetType, + const Data::AssetId& defaultAssetId) { - static const Data::AssetId invalidAssetId; - // if it's a source thumbnail key, find first product with a matching asset type auto sourceKey = azrtti_cast(key.data()); if (sourceKey) @@ -32,7 +33,7 @@ namespace AZ AzToolsFramework::AssetSystemRequestBus::BroadcastResult(foundIt, &AzToolsFramework::AssetSystemRequestBus::Events::GetAssetsProducedBySourceUUID, sourceKey->GetSourceUuid(), productsAssetInfo); if (!foundIt) { - return invalidAssetId; + return defaultAssetId; } auto assetInfoIt = AZStd::find_if(productsAssetInfo.begin(), productsAssetInfo.end(), [&assetType](const Data::AssetInfo& assetInfo) @@ -41,7 +42,7 @@ namespace AZ }); if (assetInfoIt == productsAssetInfo.end()) { - return invalidAssetId; + return defaultAssetId; } return assetInfoIt->m_assetId; @@ -53,7 +54,7 @@ namespace AZ { return productKey->GetAssetId(); } - return invalidAssetId; + return defaultAssetId; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h index e4efcd6b49..a88a25c2b7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h @@ -21,7 +21,10 @@ namespace AZ namespace Thumbnails { //! Get assetId by assetType that belongs to either source or product thumbnail key - Data::AssetId GetAssetId(AzToolsFramework::Thumbnailer::SharedThumbnailKey key, const Data::AssetType& assetType); + Data::AssetId GetAssetId( + AzToolsFramework::Thumbnailer::SharedThumbnailKey key, + const Data::AssetType& assetType, + const Data::AssetId& defaultAssetId = {}); //! Word wrap function for previewer QLabel, since by default it does not break long words such as filenames, so manual word wrap needed QString WordWrap(const QString& string, int maxLength); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 32f1bd882e..7c7765d3af 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -7,6 +7,7 @@ # set(FILES + Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h Source/Module.cpp From afa8bb92264c2928ea40420267714c83c3d3b723 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Sat, 9 Oct 2021 21:10:08 -0700 Subject: [PATCH 11/52] chore: update intersect and improve documentation Signed-off-by: Michael Pollind --- .../AzCore/AzCore/Math/IntersectSegment.cpp | 33 +- .../AzCore/AzCore/Math/IntersectSegment.h | 648 ++++++++++-------- .../AzCore/AzCore/Math/IntersectSegment.inl | 102 +++ .../AzCore/AzCore/azcore_files.cmake | 1 + 4 files changed, 485 insertions(+), 299 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp index a7a0d5197e..2a00412689 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp @@ -157,7 +157,7 @@ Intersect::IntersectSegmentTriangle( // TestSegmentAABBOrigin // [10/21/2009] //========================================================================= -int +bool AZ::Intersect::TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends) { const Vector3 EPSILON(0.001f); // \todo this is slow load move to a const @@ -168,7 +168,7 @@ AZ::Intersect::TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& hal // Try world coordinate axes as separating axes if (!absMidpoint.IsLessEqualThan(absHalfMidpoint)) { - return 0; + return false; } // Add in an epsilon term to counteract arithmetic errors when segment is @@ -188,11 +188,11 @@ AZ::Intersect::TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& hal Vector3 ead(ey * adz + ez * ady, ex * adz + ez * adx, ex * ady + ey * adx); if (!absMDCross.IsLessEqualThan(ead)) { - return 0; + return false; } // No separating axis found; segment must be overlapping AABB - return 1; + return true; } @@ -200,7 +200,7 @@ AZ::Intersect::TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& hal // IntersectRayAABB // [10/21/2009] //========================================================================= -int +RayAABBIsectTypes AZ::Intersect::IntersectRayAABB( const Vector3& rayStart, const Vector3& dir, const Vector3& dirRCP, const Aabb& aabb, float& tStart, float& tEnd, Vector3& startNormal /*, Vector3& inter*/) @@ -352,11 +352,14 @@ AZ::Intersect::IntersectRayAABB( return ISECT_RAY_AABB_ISECT; } + + + //========================================================================= // IntersectRayAABB2 // [2/18/2011] //========================================================================= -int +RayAABBIsectTypes AZ::Intersect::IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, float& start, float& end) { float tmin, tmax, tymin, tymax, tzmin, tzmax; @@ -1166,7 +1169,7 @@ int AZ::Intersect::IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayD // IntersectSegmentCylinder // [10/21/2009] //========================================================================= -int +CylinderIsectTypes AZ::Intersect::IntersectSegmentCylinder( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t) { @@ -1225,7 +1228,7 @@ AZ::Intersect::IntersectSegmentCylinder( return RR_ISECT_RAY_CYL_NONE; // No real roots; no intersection } t = (-b - Sqrt(discr)) / a; - int result = RR_ISECT_RAY_CYL_PQ; // default along the PQ segment + CylinderIsectTypes result = RR_ISECT_RAY_CYL_PQ; // default along the PQ segment if (md + t * nd < 0.0f) { @@ -1294,7 +1297,7 @@ AZ::Intersect::IntersectSegmentCylinder( // IntersectSegmentCapsule // [10/21/2009] //========================================================================= -int +CapsuleIsectTypes AZ::Intersect::IntersectSegmentCapsule(const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t) { int result = IntersectSegmentCylinder(sa, dir, p, q, r, t); @@ -1361,7 +1364,7 @@ AZ::Intersect::IntersectSegmentCapsule(const Vector3& sa, const Vector3& dir, co // IntersectSegmentPolyhedron // [10/21/2009] //========================================================================= -int +bool AZ::Intersect::IntersectSegmentPolyhedron( const Vector3& sa, const Vector3& sBA, const Plane p[], int numPlanes, float& tfirst, float& tlast, int& iFirstPlane, int& iLastPlane) @@ -1388,7 +1391,7 @@ AZ::Intersect::IntersectSegmentPolyhedron( // If so, return "no intersection" if segment lies outside plane if (dist < 0.0f) { - return 0; + return false; } } else @@ -1417,7 +1420,7 @@ AZ::Intersect::IntersectSegmentPolyhedron( // Exit with "no intersection" if intersection becomes empty if (tfirst > tlast) { - return 0; + return false; } } } @@ -1425,11 +1428,11 @@ AZ::Intersect::IntersectSegmentPolyhedron( //DBG_Assert(iFirstPlane!=-1&&iLastPlane!=-1,("We have some bad border case to have only one plane, fix this function!")); if (iFirstPlane == -1 && iLastPlane == -1) { - return 0; + return false; } // A nonzero logical intersection, so the segment intersects the polyhedron - return 1; + return true; } //========================================================================= @@ -1442,7 +1445,7 @@ AZ::Intersect::ClosestSegmentSegment( const Vector3& segment2Start, const Vector3& segment2End, float& segment1Proportion, float& segment2Proportion, Vector3& closestPointSegment1, Vector3& closestPointSegment2, - float epsilon /*= 1e-4f*/ ) + float epsilon) { const Vector3 segment1 = segment1End - segment1Start; const Vector3 segment2 = segment2End - segment2Start; diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h index df3d5e10fb..7be35c5ae6 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h @@ -5,257 +5,262 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZCORE_MATH_SEGMENT_INTERSECTION_H -#define AZCORE_MATH_SEGMENT_INTERSECTION_H +#pragma once -#include #include #include #include - -/// \file isect_segment.h +#include namespace AZ { namespace Intersect { - //! LineToPointDistanceTime computes the time of the shortest distance from point 'p' to segment (s1,s2). - //! To calculate the point of intersection: - //! P = s1 + u (s2 - s1) - //! @param s1 segment start point - //! @param s2 segment end point - //! @param p point to find the closest time to. - //! @return time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] - inline float LineToPointDistanceTime(const Vector3& s1, const Vector3& s21, const Vector3& p) - { - // so u = (p.x - s1.x)*(s2.x - s1.x) + (p.y - s1.y)*(s2.y - s1.y) + (p.z-s1.z)*(s2.z-s1.z) / |s2-s1|^2 - return s21.Dot(p - s1) / s21.Dot(s21); - } + /** + * LineToPointDistanceTime computes the time of the shortest distance from point 'p' to segment (s1,s2). + * To calculate the point of intersection: + * P = s1 + u (s2 - s1) + * @param s1 segment start point + * @param s2 segment end point + * @param p point to find the closest time to. + * @return time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + */ + float LineToPointDistanceTime(const Vector3& s1, const Vector3& s21, const Vector3& p); - //! LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). - //! @param s1 segment start point - //! @param s2 segment end point - //! @param p point to find the closest time to. - //! @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] - //! @return the closest point - inline Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u) - { - const Vector3 s21 = s2 - s1; - // we assume seg1 and seg2 are NOT coincident - AZ_MATH_ASSERT(!s21.IsClose(Vector3(0.0f), 1e-4f), "OK we agreed that we will pass valid segments! (s1 != s2)"); + /** + * LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). + * @param s1 segment start point + * @param s2 segment end point + * @param p point to find the closest time to. + * @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + * @return the closest point + */ + Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u); - u = LineToPointDistanceTime(s1, s21, p); - - return s1 + u * s21; - } - - //! Given segment pq and triangle abc (CCW), returns whether segment intersects - //! triangle and if so, also returns the barycentric coordinates (u,v,w) - //! of the intersection point. - //! @param p segment start point - //! @param q segment end point - //! @param a triangle point 1 - //! @param b triangle point 2 - //! @param c triangle point 3 - //! @param normal at the intersection point. - //! @param t time of intersection along the segment [0.0 (p), 1.0 (q)] - //! @return 1 if the segment intersects the triangle otherwise 0 + /** + * Given segment pq and triangle abc (CCW), returns whether segment intersects + * triangle and if so, also returns the barycentric coordinates (u,v,w) + * of the intersection point. + * + * @param p segment start point + * @param q segment end point + * @param a triangle point 1 + * @param b triangle point 2 + * @param c triangle point 3 + * @param normal at the intersection point. + * @param t time of intersection along the segment [0.0 (p), 1.0 (q)] + * @return true if the segments intersects the triangle otherwise false + */ int IntersectSegmentTriangleCCW( - const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, - /*float &u, float &v, float &w,*/ Vector3& normal, float& t); + const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); - //! Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). + /** + * Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). + * + * @param p segment start point + * @param q segment end point + * @param a triangle point 1 + * @param b triangle point 2 + * @param c triangle point 3 + * @param normal at the intersection point; + * @param t time of intersection along the segment [0.0 (p), 1.0 (q)] + * @return true if the segments intersects the triangle otherwise false + */ int IntersectSegmentTriangle( - const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, - /*float &u, float &v, float &w,*/ Vector3& normal, float& t); + const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); //! Ray aabb intersection result types. - enum RayAABBIsectTypes + enum RayAABBIsectTypes : AZ::s32 { - ISECT_RAY_AABB_NONE = 0, ///< no intersection - ISECT_RAY_AABB_SA_INSIDE, ///< the ray starts inside the aabb - ISECT_RAY_AABB_ISECT, ///< intersects along the PQ segment + ISECT_RAY_AABB_NONE = 0, ///< no intersection + ISECT_RAY_AABB_SA_INSIDE, ///< the ray starts inside the aabb + ISECT_RAY_AABB_ISECT, ///< intersects along the PQ segment }; - //! Intersect ray R(t) = rayStart + t*d against AABB a. When intersecting, - //! return intersection distance tmin and point q of intersection. - //! @param rayStart ray starting point - //! @param dir ray direction and length (dir = rayEnd - rayStart) - //! @param dirRCP 1/dir (reciprocal direction - we cache this result very often so we don't need to compute it multiple times, otherwise just use dir.GetReciprocal()) - //! @param aabb Axis aligned bounding box to intersect against - //! @param tStart time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value - //! @param tEnd time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) - //! @param startNormal normal at the start point. - //! @return \ref RayAABBIsectTypes - int IntersectRayAABB( - const Vector3& rayStart, const Vector3& dir, const Vector3& dirRCP, const Aabb& aabb, - float& tStart, float& tEnd, Vector3& startNormal /*, Vector3& inter*/); + /** + * Intersect ray R(t) = rayStart + t*d against AABB a. When intersecting, + * return intersection distance tmin and point q of intersection. + * @param rayStart ray starting point + * @param dir ray direction and length (dir = rayEnd - rayStart) + * @param dirRCP 1/dir (reciprocal direction - we cache this result very often so we don't need to compute it multiple times, + * otherwise just use dir.GetReciprocal()) + * @param aabb Axis aligned bounding box to intersect against + * @param tStart time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value + * @param tEnd time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) + * @param startNormal normal at the start point. + * @return \ref RayAABBIsectTypes + */ + RayAABBIsectTypes IntersectRayAABB( + const Vector3& rayStart, + const Vector3& dir, + const Vector3& dirRCP, + const Aabb& aabb, + float& tStart, + float& tEnd, + Vector3& startNormal /*, Vector3& inter*/); - //! Intersect ray against AABB. - //! @param rayStart ray starting point. - //! @param dir ray reciprocal direction. - //! @param aabb Axis aligned bounding box to intersect against. - //! @param start length on ray of the first intersection. - //! @param end length of the of the second intersection. - //! @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and ISECT_RAY_AABB_ISECT. - //! You can check yourself for that case. - int IntersectRayAABB2( - const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, - float& start, float& end); + /** + * Intersect ray against AABB. + * + * @param rayStart ray starting point. + * @param dir ray reciprocal direction. + * @param aabb Axis aligned bounding box to intersect against. + * @param start length on ray of the first intersection. + * @param end length of the of the second intersection. + * @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and ISECT_RAY_AABB_ISECT. You can check yourself for that case. + */ + RayAABBIsectTypes IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, float& start, float& end); - //! Clip a ray to an aabb. return true if ray was clipped. The ray - //! can be inside so don't use the result if the ray intersect the box. - inline int ClipRayWithAabb( - const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd) - { - Vector3 startNormal; - float tStart, tEnd; - Vector3 dirLen = rayEnd - rayStart; - if (IntersectRayAABB(rayStart, dirLen, dirLen.GetReciprocal(), aabb, tStart, tEnd, startNormal) != ISECT_RAY_AABB_NONE) - { - // clip the ray with the box - if (tStart > 0.0f) - { - rayStart = rayStart + tStart * dirLen; - tClipStart = tStart; - } - if (tEnd < 1.0f) - { - rayEnd = rayStart + tEnd * dirLen; - tClipEnd = tEnd; - } + /** + * Clip a ray to an aabb. return true if ray was clipped. The ray + * can be inside so don't use the result if the ray intersect the box. + * + * @param aabb bounds + * @param rayStart the start of the ray + * @param rayEnd the end of the ray + * @param tClipStart[out] The proportion where the ray enterts the aabb + * @param tClipEnd[out] The proportion where the ray exits the aabb + * @return true ray was clipped else false + */ + bool ClipRayWithAabb(const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd); - return 1; - } + /** + * Test segment and aabb where the segment is defined by midpoint + * midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. + * the aabb is at the origin and defined by half extents only. + * + * @param midPoint midpoint of a line segment + * @param halfVector half vector of an aabb + * @param aabbExtends the extends of a bounded box + * @return 1 if the intersect, otherwise 0. + */ + bool TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends); - return 0; - } - - //! Test segment and aabb where the segment is defined by midpoint - //! midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. - //! the aabb is at the origin and defined by half extents only. - //! @return 1 if the intersect, otherwise 0. - int TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends); - - //! Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin - //! @return 1 if the segment and AABB intersect, otherwise 0. - inline int TestSegmentAABB(const Vector3& p0, const Vector3& p1, const Aabb& aabb) - { - Vector3 e = aabb.GetExtents(); - Vector3 d = p1 - p0; - Vector3 m = p0 + p1 - aabb.GetMin() - aabb.GetMax(); - - return TestSegmentAABBOrigin(m, d, e); - } + /** + * Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin + * + * @param p0 point 1 + * @param p1 point 2 + * @param aabb bounded box + * @return true if the segment and AABB intersect, otherwise false. + */ + bool TestSegmentAABB(const Vector3& p0, const Vector3& p1, const Aabb& aabb); //! Ray sphere intersection result types. - enum SphereIsectTypes + enum SphereIsectTypes : AZ::s32 { ISECT_RAY_SPHERE_SA_INSIDE = -1, // the ray starts inside the cylinder - ISECT_RAY_SPHERE_NONE, // no intersection - ISECT_RAY_SPHERE_ISECT, // along the PQ segment + ISECT_RAY_SPHERE_NONE, // no intersection + ISECT_RAY_SPHERE_ISECT, // along the PQ segment }; - //! IntersectRaySphereOrigin - //! return time t>=0 but not limited, so if you check a segment make sure - //! t <= segmentLen - //! @param rayStart ray start point - //! @param rayDirNormalized ray direction normalized. - //! @param shereRadius sphere radius - //! @param time of closest intersection [0,+INF] in relation to the normalized direction. - //! @return \ref SphereIsectTypes - AZ_INLINE int IntersectRaySphereOrigin( - const Vector3& rayStart, const Vector3& rayDirNormalized, - const float sphereRadius, float& t) - { - Vector3 m = rayStart; - float b = m.Dot(rayDirNormalized); - float c = m.Dot(m) - sphereRadius * sphereRadius; + /** + * IntersectRaySphereOrigin + * return time t>=0 but not limited, so if you check a segment make sure + * t <= segmentLen + * @param rayStart ray start point + * @param rayDirNormalized ray direction normalized. + * @param shereRadius sphere radius + * @param time of closest intersection [0,+INF] in relation to the normalized direction. + * @return \ref SphereIsectTypes + **/ + SphereIsectTypes IntersectRaySphereOrigin( + const Vector3& rayStart, const Vector3& rayDirNormalized, const float sphereRadius, float& t); - // Exit if r's origin outside s (c > 0)and r pointing away from s (b > 0) - if (c > 0.0f && b > 0.0f) - { - return ISECT_RAY_SPHERE_NONE; - } - float discr = b * b - c; - // A negative discriminant corresponds to ray missing sphere - if (discr < 0.0f) - { - return ISECT_RAY_SPHERE_NONE; - } + /** + * Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin + * + * @param rayStart + * @param rayDirNormalized + * @param sphereCenter + * @param sphereRadius + * @param t + * @return int + */ + SphereIsectTypes IntersectRaySphere( + const Vector3& rayStart, const Vector3& rayDirNormalized, const Vector3& sphereCenter, const float sphereRadius, float& t); - // Ray now found to intersect sphere, compute smallest t value of intersection - t = -b - Sqrt(discr); - - // If t is negative, ray started inside sphere so clamp t to zero - if (t < 0.0f) - { - // t = 0.0f; - return ISECT_RAY_SPHERE_SA_INSIDE; // no hit if inside - } - //q = p + t * d; - return ISECT_RAY_SPHERE_ISECT; - } - - //! Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin - inline int IntersectRaySphere( - const Vector3& rayStart, const Vector3& rayDirNormalized, const Vector3& sphereCenter, const float sphereRadius, float& t) - { - return IntersectRaySphereOrigin(rayStart - sphereCenter, rayDirNormalized, sphereRadius, t); - } - - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param diskCenter Center point of the disk - //! @param diskRadius Radius of the disk - //! @param diskNormal A normal perpendicular to the disk - //! @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir that the hit occured at. - //! @return The number of intersecting points. + /** + * @param rayOrigin The origin of the ray to test. + * @param rayDir The direction of the ray to test. It has to be unit length. + * @param diskCenter Center point of the disk + * @param diskRadius Radius of the disk + * @param diskNormal A normal perpendicular to the disk + * @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir + * that the hit occured at. + * @return The number of intersecting points. + **/ int IntersectRayDisk( - const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& diskCenter, const float diskRadius, const AZ::Vector3& diskNormal, float& t); + const Vector3& rayOrigin, + const Vector3& rayDir, + const Vector3& diskCenter, + const float diskRadius, + const AZ::Vector3& diskNormal, + float& t); - //! If there is only one intersecting point, the coefficient is stored in \ref t1. - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param cylinderEnd1 The center of the circle on one end of the cylinder. - //! @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit length. - //! @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. - //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t1 * rayDir". - //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t2 * rayDir". - //! @return The number of intersecting points. + /** + * If there is only one intersecting point, the coefficient is stored in \ref t1. + * @param rayOrigin The origin of the ray to test. + * @param rayDir The direction of the ray to test. It has to be unit length. + * @param cylinderEnd1 The center of the circle on one end of the cylinder. + * @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit + * length. + * @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. + * @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + * as "rayOrigin + t1 * rayDir". + * @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + * as "rayOrigin + t2 * rayDir". + * @return The number of intersecting points. + **/ int IntersectRayCappedCylinder( - const Vector3& rayOrigin, const Vector3& rayDir, - const Vector3& cylinderEnd1, const Vector3& cylinderDir, float cylinderHeight, float cylinderRadius, - float& t1, float& t2); + const Vector3& rayOrigin, + const Vector3& rayDir, + const Vector3& cylinderEnd1, + const Vector3& cylinderDir, + float cylinderHeight, + float cylinderRadius, + float& t1, + float& t2); - //! If there is only one intersecting point, the coefficient is stored in \ref t1. - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param coneApex The apex of the cone. - //! @param coneDir The unit-length direction from the apex to the base. - //! @param coneHeight The height of the cone, from the apex to the base. - //! @param coneBaseRadius The radius of the cone base circle. - //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t1 * rayDir". - //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t2 * rayDir". - //! @return The number of intersecting points. + /** + * If there is only one intersecting point, the coefficient is stored in \ref t1. + * @param rayOrigin The origin of the ray to test. + * @param rayDir The direction of the ray to test. It has to be unit length. + * @param coneApex The apex of the cone. + * @param coneDir The unit-length direction from the apex to the base. + * @param coneHeight The height of the cone, from the apex to the base. + * @param coneBaseRadius The radius of the cone base circle. + * @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + * as "rayOrigin + t1 * rayDir". + * @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + * as "rayOrigin + t2 * rayDir". + * @return The number of intersecting points. + **/ int IntersectRayCone( - const Vector3& rayOrigin, const Vector3& rayDir, - const Vector3& coneApex, const Vector3& coneDir, float coneHeight, float coneBaseRadius, - float& t1, float& t2); + const Vector3& rayOrigin, + const Vector3& rayDir, + const Vector3& coneApex, + const Vector3& coneDir, + float coneHeight, + float coneBaseRadius, + float& t1, + float& t2); - //! Test intersection between a ray and a plane in 3D. - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param planePos A point on the plane to test intersection with. - //! @param planeNormal The normal of the plane to test intersection with. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return The number of intersection point. + /** + * Test intersection between a ray and a plane in 3D. + * @param rayOrigin The origin of the ray to test intersection with. + * @param rayDir The direction of the ray to test intersection with. + * @param planePos A point on the plane to test intersection with. + * @param planeNormal The normal of the plane to test intersection with. + * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + *+ t * rayDirection". + * @return The number of intersection point. + **/ int IntersectRayPlane( - const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& planePos, - const Vector3& planeNormal, float& t); + const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& planePos, const Vector3& planeNormal, float& t); //! Test intersection between a ray and a two-sided quadrilateral defined by four points in 3D. - //! The four points that define the quadrilateral could be passed in with either counter clock-wise + //! The four points that define the quadrilateral could be passed in with either counter clock-wise //! winding or clock-wise winding. //! @param rayOrigin The origin of the ray to test intersection with. //! @param rayDir The direction of the ray to test intersection with. @@ -263,105 +268,180 @@ namespace AZ //! @param vertexB One of the four points that define the quadrilateral. //! @param vertexC One of the four points that define the quadrilateral. //! @param vertexD One of the four points that define the quadrilateral. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + + //! t * rayDirection". //! @return The number of intersection point. int IntersectRayQuad( - const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& vertexA, - const Vector3& vertexB, const Vector3& vertexC, const Vector3& vertexD, float& t); - - //! Test intersection between a ray and an oriented box in 3D. - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param boxCenter The position of the center of the box. - //! @param boxAxis1 An axis along one dimension of the oriented box. - //! @param boxAxis2 An axis along one dimension of the oriented box. - //! @param boxAxis3 An axis along one dimension of the oriented box. - //! @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. - //! @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. - //! @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return 1 if there is an intersection, 0 otherwise. - int IntersectRayBox( - const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& boxCenter, const Vector3& boxAxis1, - const Vector3& boxAxis2, const Vector3& boxAxis3, float boxHalfExtent1, float boxHalfExtent2, float boxHalfExtent3, + const Vector3& rayOrigin, + const Vector3& rayDir, + const Vector3& vertexA, + const Vector3& vertexB, + const Vector3& vertexC, + const Vector3& vertexD, float& t); - //! Test intersection between a ray and an OBB. - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param obb The OBB to test for intersection with the ray. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return 1 if there is an intersection, 0 otherwise. + /** Test intersection between a ray and an oriented box in 3D. + * @param rayOrigin The origin of the ray to test intersection with. + * @param rayDir The direction of the ray to test intersection with. + * @param boxCenter The position of the center of the box. + * @param boxAxis1 An axis along one dimension of the oriented box. + * @param boxAxis2 An axis along one dimension of the oriented box. + * @param boxAxis3 An axis along one dimension of the oriented box. + * @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. + * @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. + * @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. + * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + + * t * rayDirection". + * @return 1 if there is an intersection, 0 otherwise. + **/ + int IntersectRayBox( + const Vector3& rayOrigin, + const Vector3& rayDir, + const Vector3& boxCenter, + const Vector3& boxAxis1, + const Vector3& boxAxis2, + const Vector3& boxAxis3, + float boxHalfExtent1, + float boxHalfExtent2, + float boxHalfExtent3, + float& t); + + /** + * Test intersection between a ray and an OBB. + * @param rayOrigin The origin of the ray to test intersection with. + * @param rayDir The direction of the ray to test intersection with. + * @param obb The OBB to test for intersection with the ray. + * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * + * rayDirection". + * @return 1 if there is an intersection, 0 otherwise. + */ int IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t); //! Ray cylinder intersection types. - enum CylinderIsectTypes + enum CylinderIsectTypes : AZ::s32 { RR_ISECT_RAY_CYL_SA_INSIDE = -1, // the ray starts inside the cylinder - RR_ISECT_RAY_CYL_NONE, // no intersection - RR_ISECT_RAY_CYL_PQ, // along the PQ segment - RR_ISECT_RAY_CYL_P_SIDE, // on the P side - RR_ISECT_RAY_CYL_Q_SIDE, // on the Q side + RR_ISECT_RAY_CYL_NONE, // no intersection + RR_ISECT_RAY_CYL_PQ, // along the PQ segment + RR_ISECT_RAY_CYL_P_SIDE, // on the P side + RR_ISECT_RAY_CYL_Q_SIDE, // on the Q side }; - //! Intersect segment S(t)=sa+t(dir), 0<=t<=1 against cylinder specified by p, q and r. - int IntersectSegmentCylinder( - const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, - const float r, float& t); + /** + * Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder + * Intersect segment S(t)=sa+t(dir), 0<=t<=1 against cylinder specified by p, q and r. + * + * @param sa point + * @param dir magnitude along sa + * @param p center point of side 1 cylinder + * @param q center point of side 2 cylinder + * @param r radius of cylinder + * @param t[out] proporition along line semgnet + * @return CylinderIsectTypes + */ + CylinderIsectTypes IntersectSegmentCylinder( + const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); //! Capsule ray intersect types. enum CapsuleIsectTypes { ISECT_RAY_CAPSULE_SA_INSIDE = -1, // the ray starts inside the cylinder ISECT_RAY_CAPSULE_NONE, // no intersection - ISECT_RAY_CAPSULE_PQ, // along the PQ segment - ISECT_RAY_CAPSULE_P_SIDE, // on the P side - ISECT_RAY_CAPSULE_Q_SIDE, // on the Q side + ISECT_RAY_CAPSULE_PQ, // along the PQ segment + ISECT_RAY_CAPSULE_P_SIDE, // on the P side + ISECT_RAY_CAPSULE_Q_SIDE, // on the Q side }; - //! This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder - //! segment sphere intersection. We can optimize it a lot once we fix the ray - //! cylinder intersection. - int IntersectSegmentCapsule( - const Vector3& sa, const Vector3& dir, const Vector3& p, - const Vector3& q, const float r, float& t); + /** + * This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder + * segment sphere intersection. We can optimize it a lot once we fix the ray + * cylinder intersection. + */ + CapsuleIsectTypes IntersectSegmentCapsule( + const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); - //! Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified - //! by the n halfspaces defined by the planes p[]. On exit tfirst and tlast - //! define the intersection, if any. - int IntersectSegmentPolyhedron( - const Vector3& sa, const Vector3& sBA, const Plane p[], int numPlanes, - float& tfirst, float& tlast, int& iFirstPlane, int& iLastPlane); + /** + * Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified + * by the n halfspaces defined by the planes p[]. On exit tfirst and tlast + * define the intersection, if any. + */ + bool IntersectSegmentPolyhedron( + const Vector3& sa, + const Vector3& sBA, + const Plane p[], + int numPlanes, + float& tfirst, + float& tlast, + int& iFirstPlane, + int& iLastPlane); - //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between - //! two segments segment1Start<->segment1End and segment2Start<->segment2End. Also calculate the values of segment1Proportion and segment2Proportion where - //! closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) - //! closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) - //! If segments are parallel returns a solution. + /** + * Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between + * two segments segment1Start<->segment1End and segment2Start<->segment2End. Also calculate the values of segment1Proportion and + * segment2Proportion where closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) + * closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) + * If segments are parallel returns a solution. + * @param segment1Start start of segment 1. + * @param segment1End end of segment 1. + * @param segment2Start start of segment 2. + * @param segment2End end of segment 2. + * @param segment1Proportion[out] the proporition along segment 1 [0..1] + * @param segment2Proportion[out] the proporition along segment 2 [0..1] + * @param closestPointSegment1[out] closest point on segment 1. + * @param closestPointSegment2[out] closest point on segment 2. + * @param epsilon the minimum square distance where a line segment can be treated as a single point. + */ void ClosestSegmentSegment( - const Vector3& segment1Start, const Vector3& segment1End, - const Vector3& segment2Start, const Vector3& segment2End, - float& segment1Proportion, float& segment2Proportion, - Vector3& closestPointSegment1, Vector3& closestPointSegment2, + const Vector3& segment1Start, + const Vector3& segment1End, + const Vector3& segment2Start, + const Vector3& segment2End, + float& segment1Proportion, + float& segment2Proportion, + Vector3& closestPointSegment1, + Vector3& closestPointSegment2, float epsilon = 1e-4f); - //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between - //! two segments segment1Start<->segment1End and segment2Start<->segment2End. - //! If segments are parallel returns a solution. + /** + * Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between + * two segments segment1Start<->segment1End and segment2Start<->segment2End. + * If segments are parallel returns a solution. + * + * @param segment1Start start of segment 1. + * @param segment1End end of segment 1. + * @param segment2Start start of segment 2. + * @param segment2End end of segment 2. + * @param closestPointSegment1[out] closest point on segment 1. + * @param closestPointSegment2[out] closest point on segment 2. + * @param epsilon the minimum square distance where a line segment can be treated as a single point. + */ void ClosestSegmentSegment( - const Vector3& segment1Start, const Vector3& segment1End, - const Vector3& segment2Start, const Vector3& segment2End, - Vector3& closestPointSegment1, Vector3& closestPointSegment2, + const Vector3& segment1Start, + const Vector3& segment1End, + const Vector3& segment2Start, + const Vector3& segment2End, + Vector3& closestPointSegment1, + Vector3& closestPointSegment2, float epsilon = 1e-4f); - //! Calculate the point (closestPointOnSegment) that is the closest point on - //! segment segmentStart/segmentEnd to point. Also calculate the value of proportion where - //! closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) + /** + * Calculate the point (closestPointOnSegment) that is the closest point on + * segment segmentStart/segmentEnd to point. Also calculate the value of proportion where + * closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) + * + * @param point the point to test + * @param segmentStart the start of the segment + * @param segmentEnd the end of the segment + * @param proportion[out] the proportion of the segment L(t) = (end - start) * t + * @param closestPointOnSegment[out] the point along the line segment + */ void ClosestPointSegment( - const Vector3& point, const Vector3& segmentStart, const Vector3& segmentEnd, - float& proportion, Vector3& closestPointOnSegment); - } -} + const Vector3& point, + const Vector3& segmentStart, + const Vector3& segmentEnd, + float& proportion, + Vector3& closestPointOnSegment); + } // namespace Intersect +} // namespace AZ -#endif // AZCORE_MATH_SEGMENT_INTERSECTION_H -#pragma once +#include diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl new file mode 100644 index 0000000000..b9f5139923 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl @@ -0,0 +1,102 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +namespace AZ +{ + namespace Intersect + { + AZ_MATH_INLINE bool ClipRayWithAabb(const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd) + { + Vector3 startNormal; + float tStart, tEnd; + Vector3 dirLen = rayEnd - rayStart; + if (IntersectRayAABB(rayStart, dirLen, dirLen.GetReciprocal(), aabb, tStart, tEnd, startNormal) != ISECT_RAY_AABB_NONE) + { + // clip the ray with the box + if (tStart > 0.0f) + { + rayStart = rayStart + tStart * dirLen; + tClipStart = tStart; + } + if (tEnd < 1.0f) + { + rayEnd = rayStart + tEnd * dirLen; + tClipEnd = tEnd; + } + + return true; + } + + return false; + } + + AZ_MATH_INLINE SphereIsectTypes + IntersectRaySphereOrigin(const Vector3& rayStart, const Vector3& rayDirNormalized, const float sphereRadius, float& t) + { + Vector3 m = rayStart; + float b = m.Dot(rayDirNormalized); + float c = m.Dot(m) - sphereRadius * sphereRadius; + + // Exit if r's origin outside s (c > 0)and r pointing away from s (b > 0) + if (c > 0.0f && b > 0.0f) + { + return ISECT_RAY_SPHERE_NONE; + } + float discr = b * b - c; + // A negative discriminant corresponds to ray missing sphere + if (discr < 0.0f) + { + return ISECT_RAY_SPHERE_NONE; + } + + // Ray now found to intersect sphere, compute smallest t value of intersection + t = -b - Sqrt(discr); + + // If t is negative, ray started inside sphere so clamp t to zero + if (t < 0.0f) + { + // t = 0.0f; + return ISECT_RAY_SPHERE_SA_INSIDE; // no hit if inside + } + // q = p + t * d; + return ISECT_RAY_SPHERE_ISECT; + } + + AZ_MATH_INLINE SphereIsectTypes IntersectRaySphere(const Vector3& rayStart, const Vector3& rayDirNormalized, const Vector3& sphereCenter, const float sphereRadius, float& t) + { + return IntersectRaySphereOrigin(rayStart - sphereCenter, rayDirNormalized, sphereRadius, t); + } + + AZ_MATH_INLINE Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u) + { + const Vector3 s21 = s2 - s1; + // we assume seg1 and seg2 are NOT coincident + AZ_MATH_ASSERT(!s21.IsClose(Vector3(0.0f), 1e-4f), "OK we agreed that we will pass valid segments! (s1 != s2)"); + + u = LineToPointDistanceTime(s1, s21, p); + + return s1 + u * s21; + } + + AZ_MATH_INLINE float LineToPointDistanceTime(const Vector3& s1, const Vector3& s21, const Vector3& p) + { + // so u = (p.x - s1.x)*(s2.x - s1.x) + (p.y - s1.y)*(s2.y - s1.y) + (p.z-s1.z)*(s2.z-s1.z) / |s2-s1|^2 + return s21.Dot(p - s1) / s21.Dot(s21); + } + + AZ_MATH_INLINE bool TestSegmentAABB(const Vector3& p0, const Vector3& p1, const Aabb& aabb) + { + Vector3 e = aabb.GetExtents(); + Vector3 d = p1 - p0; + Vector3 m = p0 + p1 - aabb.GetMin() - aabb.GetMax(); + + return TestSegmentAABBOrigin(m, d, e); + } + } // namespace Intersect +} // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index 6675958247..4d95ddf098 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -282,6 +282,7 @@ set(FILES Math/Internal/VertexContainer.inl Math/InterpolationSample.h Math/IntersectPoint.h + Math/IntersectSegment.inl Math/IntersectSegment.cpp Math/IntersectSegment.h Math/MathIntrinsics.h From 78f4e0d0de41687ff05bb0db33715edf1b316523 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sat, 9 Oct 2021 23:57:04 -0500 Subject: [PATCH 12/52] Combined common thumbnail classes Signed-off-by: Guthrie Adams --- .../EditorCommonFeaturesSystemComponent.cpp | 30 +---- .../Code/Source/Previewer/CommonPreviewer.cpp | 10 +- .../Code/Source/Previewer/CommonPreviewer.h | 14 +-- .../Previewer/CommonPreviewerFactory.cpp | 25 +--- .../Source/Previewer/CommonPreviewerFactory.h | 4 +- .../Code/Source/Previewer/CommonThumbnail.cpp | 113 +++++++++++++++++ .../{ModelThumbnail.h => CommonThumbnail.h} | 15 +-- .../Previewer/CommonThumbnailRenderer.cpp | 10 +- ...nailUtils.cpp => CommonThumbnailUtils.cpp} | 37 +++++- ...humbnailUtils.h => CommonThumbnailUtils.h} | 7 +- .../Previewer/LightingPresetThumbnail.cpp | 115 ------------------ .../Previewer/LightingPresetThumbnail.h | 67 ---------- .../Source/Previewer/MaterialThumbnail.cpp | 106 ---------------- .../Code/Source/Previewer/MaterialThumbnail.h | 67 ---------- .../Code/Source/Previewer/ModelThumbnail.cpp | 106 ---------------- ...egration_commonfeatures_editor_files.cmake | 12 +- 16 files changed, 192 insertions(+), 546 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/{ModelThumbnail.h => CommonThumbnail.h} (80%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/{ThumbnailUtils.cpp => CommonThumbnailUtils.cpp} (64%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/{ThumbnailUtils.h => CommonThumbnailUtils.h} (83%) delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h delete mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 34cd9f59d0..47dd5ce571 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -6,9 +6,6 @@ * */ -#include -#include - #include #include #include @@ -17,10 +14,9 @@ #include #include #include - -#include -#include -#include +#include +#include +#include #include @@ -220,15 +216,7 @@ namespace AZ using namespace LyIntegration; ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::MaterialThumbnailCache), - ThumbnailContext::DefaultContext); - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::ModelThumbnailCache), - ThumbnailContext::DefaultContext); - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::LightingPresetThumbnailCache), + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::CommonThumbnailCache), ThumbnailContext::DefaultContext); m_renderer = AZStd::make_unique(); @@ -241,15 +229,7 @@ namespace AZ using namespace LyIntegration; ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::MaterialThumbnailCache::ProviderName, - ThumbnailContext::DefaultContext); - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::ModelThumbnailCache::ProviderName, - ThumbnailContext::DefaultContext); - - ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::LightingPresetThumbnailCache::ProviderName, + &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::CommonThumbnailCache::ProviderName, ThumbnailContext::DefaultContext); m_renderer.reset(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp index 2b5ea7843a..9ecc41e0f2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp @@ -13,15 +13,15 @@ #include #include #include -#include +#include // Disables warning messages triggered by the Qt library -// 4251: class needs to have dll-interface to be used by clients of class +// 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") #include -#include #include +#include AZ_POP_DISABLE_WARNING namespace AZ @@ -41,6 +41,10 @@ namespace AZ { } + void CommonPreviewer::Clear() const + { + } + void CommonPreviewer::Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) { using namespace AzToolsFramework::AssetBrowser; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h index 1dfa8788e0..6d2108d826 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h @@ -5,16 +5,17 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #pragma once #if !defined(Q_MOC_RUN) -#include #include +#include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include #include +#include AZ_POP_DISABLE_WARNING #endif @@ -30,8 +31,8 @@ namespace AzToolsFramework class ProductAssetBrowserEntry; class SourceAssetBrowserEntry; class AssetBrowserEntry; - } -} + } // namespace AssetBrowser +} // namespace AzToolsFramework class QResizeEvent; @@ -39,8 +40,7 @@ namespace AZ { namespace LyIntegration { - class CommonPreviewer final - : public AzToolsFramework::AssetBrowser::Previewer + class CommonPreviewer final : public AzToolsFramework::AssetBrowser::Previewer { Q_OBJECT public: @@ -50,7 +50,7 @@ namespace AZ ~CommonPreviewer(); // AzToolsFramework::AssetBrowser::Previewer overrides... - void Clear() const override {} + void Clear() const override; void Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) override; const QString& GetName() const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp index 3a6fd2a424..f947cfd8ba 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace AZ { @@ -26,28 +26,7 @@ namespace AZ bool CommonPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const { - AZ::Data::AssetId assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::ModelAsset::RTTI_Type()); - if (assetId.IsValid()) - { - return true; - } - - assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::MaterialAsset::RTTI_Type()); - if (assetId.IsValid()) - { - return true; - } - - assetId = Thumbnails::GetAssetId(entry->GetThumbnailKey(), RPI::AnyAsset::RTTI_Type()); - if (assetId.IsValid()) - { - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); - return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); - } - - return false; + return Thumbnails::IsSupportedThumbnail(entry->GetThumbnailKey()); } const QString& CommonPreviewerFactory::GetName() const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h index 1f9cc9d5df..cec4ccc21f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h @@ -5,6 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #pragma once #include @@ -18,8 +19,7 @@ namespace AZ { namespace LyIntegration { - class CommonPreviewerFactory final - : public AzToolsFramework::AssetBrowser::PreviewerFactory + class CommonPreviewerFactory final : public AzToolsFramework::AssetBrowser::PreviewerFactory { public: AZ_CLASS_ALLOCATOR(CommonPreviewerFactory, AZ::SystemAllocator, 0); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp new file mode 100644 index 0000000000..298d062b7d --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace LyIntegration + { + namespace Thumbnails + { + static constexpr const int CommonThumbnailSize = 256; + + ////////////////////////////////////////////////////////////////////////// + // CommonThumbnail + ////////////////////////////////////////////////////////////////////////// + CommonThumbnail::CommonThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + : Thumbnail(key) + { + for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) + { + const AZ::Data::AssetId& assetId = GetAssetId(key, typeId); + if (assetId.IsValid()) + { + m_assetId = assetId; + m_typeId = typeId; + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); + return; + } + } + + AZ_Error("CommonThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); + m_state = State::Failed; + } + + void CommonThumbnail::LoadThread() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( + m_typeId, &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, + CommonThumbnailSize); + // wait for response from thumbnail renderer + m_renderWait.acquire(); + } + + CommonThumbnail::~CommonThumbnail() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); + AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); + } + + void CommonThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) + { + m_pixmap = thumbnailImage; + m_renderWait.release(); + } + + void CommonThumbnail::ThumbnailFailedToRender() + { + m_state = State::Failed; + m_renderWait.release(); + } + + void CommonThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) + { + if (m_assetId == assetId && m_state == State::Ready) + { + m_state = State::Unloaded; + Load(); + } + } + + ////////////////////////////////////////////////////////////////////////// + // CommonThumbnailCache + ////////////////////////////////////////////////////////////////////////// + CommonThumbnailCache::CommonThumbnailCache() + : ThumbnailCache() + { + } + + CommonThumbnailCache::~CommonThumbnailCache() = default; + + int CommonThumbnailCache::GetPriority() const + { + // Thumbnails override default source thumbnails, so carry higher priority + return 1; + } + + const char* CommonThumbnailCache::GetProviderName() const + { + return ProviderName; + } + + bool CommonThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const + { + return Thumbnails::IsSupportedThumbnail(key); + } + } // namespace Thumbnails + } // namespace LyIntegration +} // namespace AZ + +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.h similarity index 80% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.h index 5d9449e988..195452ca21 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.h @@ -22,15 +22,15 @@ namespace AZ namespace Thumbnails { //! Custom thumbnail that detects when an asset changes and updates the thumbnail - class ModelThumbnail + class CommonThumbnail : public AzToolsFramework::Thumbnailer::Thumbnail , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler , private AzFramework::AssetCatalogEventBus::Handler { Q_OBJECT public: - ModelThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - ~ModelThumbnail() override; + CommonThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + ~CommonThumbnail() override; //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... void ThumbnailRendered(const QPixmap& thumbnailImage) override; @@ -45,19 +45,20 @@ namespace AZ AZStd::binary_semaphore m_renderWait; Data::AssetId m_assetId; + AZ::Uuid m_typeId; }; //! Cache configuration for large thumbnails - class ModelThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache + class CommonThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache { public: - ModelThumbnailCache(); - ~ModelThumbnailCache() override; + CommonThumbnailCache(); + ~CommonThumbnailCache() override; int GetPriority() const override; const char* GetProviderName() const override; - static constexpr const char* ProviderName = "Model Thumbnails"; + static constexpr const char* ProviderName = "Common Thumbnails"; protected: bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp index f29762b563..0eb6a9b4a3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include namespace AZ { @@ -27,10 +27,10 @@ namespace AZ m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); - // CommonThumbnailRenderer supports both models and materials - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::MaterialAsset::RTTI_Type()); - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::ModelAsset::RTTI_Type()); - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(RPI::AnyAsset::RTTI_Type()); + for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(typeId); + } SystemTickBus::Handler::BusConnect(); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.cpp similarity index 64% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.cpp index 6d3d07faef..013bc4261b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.cpp @@ -9,9 +9,10 @@ #include #include #include +#include #include #include -#include +#include namespace AZ { @@ -30,12 +31,15 @@ namespace AZ { bool foundIt = false; AZStd::vector productsAssetInfo; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(foundIt, &AzToolsFramework::AssetSystemRequestBus::Events::GetAssetsProducedBySourceUUID, sourceKey->GetSourceUuid(), productsAssetInfo); + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + foundIt, &AzToolsFramework::AssetSystemRequestBus::Events::GetAssetsProducedBySourceUUID, + sourceKey->GetSourceUuid(), productsAssetInfo); if (!foundIt) { return defaultAssetId; } - auto assetInfoIt = AZStd::find_if(productsAssetInfo.begin(), productsAssetInfo.end(), + auto assetInfoIt = AZStd::find_if( + productsAssetInfo.begin(), productsAssetInfo.end(), [&assetType](const Data::AssetInfo& assetInfo) { return assetInfo.m_assetType == assetType; @@ -57,7 +61,6 @@ namespace AZ return defaultAssetId; } - QString WordWrap(const QString& string, int maxLength) { QString result; @@ -82,6 +85,32 @@ namespace AZ } return result; } + + AZStd::unordered_set GetSupportedThumbnailAssetTypes() + { + return { RPI::AnyAsset::RTTI_Type(), RPI::MaterialAsset::RTTI_Type(), RPI::ModelAsset::RTTI_Type() }; + } + + bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + { + for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) + { + const AZ::Data::AssetId& assetId = GetAssetId(key, typeId); + if (assetId.IsValid()) + { + if (typeId == RPI::AnyAsset::RTTI_Type()) + { + AZ::Data::AssetInfo assetInfo; + AZ::Data::AssetCatalogRequestBus::BroadcastResult( + assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); + return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); + } + return true; + } + } + + return false; + } } // namespace Thumbnails } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.h similarity index 83% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.h index a88a25c2b7..be2432bc7b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ThumbnailUtils.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.h @@ -26,8 +26,13 @@ namespace AZ const Data::AssetType& assetType, const Data::AssetId& defaultAssetId = {}); - //! Word wrap function for previewer QLabel, since by default it does not break long words such as filenames, so manual word wrap needed + //! Word wrap function for previewer QLabel, since by default it does not break long words such as filenames, so manual word + //! wrap needed QString WordWrap(const QString& string, int maxLength); + + AZStd::unordered_set GetSupportedThumbnailAssetTypes(); + + bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); } // namespace Thumbnails } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp deleted file mode 100644 index 6a9c2ca2ca..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - static constexpr const int LightingPresetThumbnailSize = 512; // 512 is the default size in render to texture pass - - ////////////////////////////////////////////////////////////////////////// - // LightingPresetThumbnail - ////////////////////////////////////////////////////////////////////////// - LightingPresetThumbnail::LightingPresetThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) - : Thumbnail(key) - { - m_assetId = GetAssetId(key, RPI::AnyAsset::RTTI_Type()); - if (!m_assetId.IsValid()) - { - AZ_Error("LightingPresetThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); - m_state = State::Failed; - return; - } - - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - } - - void LightingPresetThumbnail::LoadThread() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - RPI::AnyAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, - LightingPresetThumbnailSize); - // wait for response from thumbnail renderer - m_renderWait.acquire(); - } - - LightingPresetThumbnail::~LightingPresetThumbnail() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - } - - void LightingPresetThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) - { - m_pixmap = thumbnailImage; - m_renderWait.release(); - } - - void LightingPresetThumbnail::ThumbnailFailedToRender() - { - m_state = State::Failed; - m_renderWait.release(); - } - - void LightingPresetThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) - { - if (m_assetId == assetId && m_state == State::Ready) - { - m_state = State::Unloaded; - Load(); - } - } - - ////////////////////////////////////////////////////////////////////////// - // LightingPresetThumbnailCache - ////////////////////////////////////////////////////////////////////////// - LightingPresetThumbnailCache::LightingPresetThumbnailCache() - : ThumbnailCache() - { - } - - LightingPresetThumbnailCache::~LightingPresetThumbnailCache() = default; - - int LightingPresetThumbnailCache::GetPriority() const - { - // Thumbnails override default source thumbnails, so carry higher priority - return 1; - } - - const char* LightingPresetThumbnailCache::GetProviderName() const - { - return ProviderName; - } - - bool LightingPresetThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const - { - const auto assetId = Thumbnails::GetAssetId(key, RPI::AnyAsset::RTTI_Type()); - if (assetId.IsValid()) - { - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId); - return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath.c_str(), "lightingpreset.azasset"); - } - - return false; - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - -#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h deleted file mode 100644 index 437a372c3c..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/LightingPresetThumbnail.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include -#endif - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! Custom thumbnail that detects when an asset changes and updates the thumbnail - class LightingPresetThumbnail - : public AzToolsFramework::Thumbnailer::Thumbnail - , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler - , private AzFramework::AssetCatalogEventBus::Handler - { - Q_OBJECT - public: - LightingPresetThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - ~LightingPresetThumbnail() override; - - //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(const QPixmap& thumbnailImage) override; - void ThumbnailFailedToRender() override; - - protected: - void LoadThread() override; - - private: - // AzFramework::AssetCatalogEventBus::Handler interface overrides... - void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; - - AZStd::binary_semaphore m_renderWait; - Data::AssetId m_assetId; - }; - - //! Cache configuration for large thumbnails - class LightingPresetThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache - { - public: - LightingPresetThumbnailCache(); - ~LightingPresetThumbnailCache() override; - - int GetPriority() const override; - const char* GetProviderName() const override; - - static constexpr const char* ProviderName = "LightingPreset Thumbnails"; - - protected: - bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp deleted file mode 100644 index b9a3412d0e..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - static constexpr const int MaterialThumbnailSize = 512; // 512 is the default size in render to texture pass - - ////////////////////////////////////////////////////////////////////////// - // MaterialThumbnail - ////////////////////////////////////////////////////////////////////////// - MaterialThumbnail::MaterialThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) - : Thumbnail(key) - { - m_assetId = GetAssetId(key, RPI::MaterialAsset::RTTI_Type()); - if (!m_assetId.IsValid()) - { - AZ_Error("MaterialThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); - m_state = State::Failed; - return; - } - - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - } - - void MaterialThumbnail::LoadThread() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - RPI::MaterialAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, - MaterialThumbnailSize); - // wait for response from thumbnail renderer - m_renderWait.acquire(); - } - - MaterialThumbnail::~MaterialThumbnail() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - } - - void MaterialThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) - { - m_pixmap = thumbnailImage; - m_renderWait.release(); - } - - void MaterialThumbnail::ThumbnailFailedToRender() - { - m_state = State::Failed; - m_renderWait.release(); - } - - void MaterialThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) - { - if (m_assetId == assetId && m_state == State::Ready) - { - m_state = State::Unloaded; - Load(); - } - } - - ////////////////////////////////////////////////////////////////////////// - // MaterialThumbnailCache - ////////////////////////////////////////////////////////////////////////// - MaterialThumbnailCache::MaterialThumbnailCache() - : ThumbnailCache() - { - } - - MaterialThumbnailCache::~MaterialThumbnailCache() = default; - - int MaterialThumbnailCache::GetPriority() const - { - // Thumbnails override default source thumbnails, so carry higher priority - return 1; - } - - const char* MaterialThumbnailCache::GetProviderName() const - { - return ProviderName; - } - - bool MaterialThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const - { - return GetAssetId(key, RPI::MaterialAsset::RTTI_Type()).IsValid(); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - -#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h deleted file mode 100644 index 1349336245..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/MaterialThumbnail.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include -#include -#endif - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - //! Custom thumbnail that detects when an asset changes and updates the thumbnail - class MaterialThumbnail - : public AzToolsFramework::Thumbnailer::Thumbnail - , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler - , private AzFramework::AssetCatalogEventBus::Handler - { - Q_OBJECT - public: - MaterialThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - ~MaterialThumbnail() override; - - //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(const QPixmap& thumbnailImage) override; - void ThumbnailFailedToRender() override; - - protected: - void LoadThread() override; - - private: - // AzFramework::AssetCatalogEventBus::Handler interface overrides... - void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; - - AZStd::binary_semaphore m_renderWait; - Data::AssetId m_assetId; - }; - - //! Cache configuration for large thumbnails - class MaterialThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache - { - public: - MaterialThumbnailCache(); - ~MaterialThumbnailCache() override; - - int GetPriority() const override; - const char* GetProviderName() const override; - - static constexpr const char* ProviderName = "Material Thumbnails"; - - protected: - bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; - }; - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp deleted file mode 100644 index e3eb7a3af6..0000000000 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/ModelThumbnail.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace LyIntegration - { - namespace Thumbnails - { - static constexpr const int ModelThumbnailSize = 512; // 512 is the default size in render to texture pass - - ////////////////////////////////////////////////////////////////////////// - // ModelThumbnail - ////////////////////////////////////////////////////////////////////////// - ModelThumbnail::ModelThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) - : Thumbnail(key) - { - m_assetId = GetAssetId(key, RPI::ModelAsset::RTTI_Type()); - if (!m_assetId.IsValid()) - { - AZ_Error("ModelThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); - m_state = State::Failed; - return; - } - - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - } - - void ModelThumbnail::LoadThread() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - RPI::ModelAsset::RTTI_Type(), &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, - ModelThumbnailSize); - // wait for response from thumbnail renderer - m_renderWait.acquire(); - } - - ModelThumbnail::~ModelThumbnail() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - } - - void ModelThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) - { - m_pixmap = thumbnailImage; - m_renderWait.release(); - } - - void ModelThumbnail::ThumbnailFailedToRender() - { - m_state = State::Failed; - m_renderWait.release(); - } - - void ModelThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) - { - if (m_assetId == assetId && m_state == State::Ready) - { - m_state = State::Unloaded; - Load(); - } - } - - ////////////////////////////////////////////////////////////////////////// - // ModelThumbnailCache - ////////////////////////////////////////////////////////////////////////// - ModelThumbnailCache::ModelThumbnailCache() - : ThumbnailCache() - { - } - - ModelThumbnailCache::~ModelThumbnailCache() = default; - - int ModelThumbnailCache::GetPriority() const - { - // Thumbnails override default source thumbnails, so carry higher priority - return 1; - } - - const char* ModelThumbnailCache::GetProviderName() const - { - return ProviderName; - } - - bool ModelThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const - { - return GetAssetId(key, RPI::ModelAsset::RTTI_Type()).IsValid(); - } - } // namespace Thumbnails - } // namespace LyIntegration -} // namespace AZ - -#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 7c7765d3af..00d3f09978 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -91,8 +91,6 @@ set(FILES Source/SkyBox/EditorHDRiSkyboxComponent.h Source/SkyBox/EditorPhysicalSkyComponent.cpp Source/SkyBox/EditorPhysicalSkyComponent.h - Source/Previewer/ThumbnailUtils.h - Source/Previewer/ThumbnailUtils.cpp Source/Previewer/CommonPreviewer.cpp Source/Previewer/CommonPreviewer.h Source/Previewer/CommonPreviewer.ui @@ -100,14 +98,12 @@ set(FILES Source/Previewer/CommonPreviewerFactory.h Source/Previewer/CommonPreviewContent.cpp Source/Previewer/CommonPreviewContent.h + Source/Previewer/CommonThumbnail.cpp + Source/Previewer/CommonThumbnail.h Source/Previewer/CommonThumbnailRenderer.cpp Source/Previewer/CommonThumbnailRenderer.h - Source/Previewer/MaterialThumbnail.cpp - Source/Previewer/MaterialThumbnail.h - Source/Previewer/ModelThumbnail.cpp - Source/Previewer/ModelThumbnail.h - Source/Previewer/LightingPresetThumbnail.cpp - Source/Previewer/LightingPresetThumbnail.h + Source/Previewer/CommonThumbnailUtils.cpp + Source/Previewer/CommonThumbnailUtils.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From 7f4aae70891b7e95734c681475b0cb3e5e7346e0 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sun, 10 Oct 2021 00:32:14 -0500 Subject: [PATCH 13/52] renaming Previewer folder to SharedPreview Signed-off-by: Guthrie Adams --- .../Source/{Previewer => SharedPreview}/CommonPreviewContent.cpp | 0 .../Source/{Previewer => SharedPreview}/CommonPreviewContent.h | 0 .../Code/Source/{Previewer => SharedPreview}/CommonPreviewer.cpp | 0 .../Code/Source/{Previewer => SharedPreview}/CommonPreviewer.h | 0 .../Code/Source/{Previewer => SharedPreview}/CommonPreviewer.ui | 0 .../{Previewer => SharedPreview}/CommonPreviewerFactory.cpp | 0 .../Source/{Previewer => SharedPreview}/CommonPreviewerFactory.h | 0 .../Code/Source/{Previewer => SharedPreview}/CommonThumbnail.cpp | 0 .../Code/Source/{Previewer => SharedPreview}/CommonThumbnail.h | 0 .../{Previewer => SharedPreview}/CommonThumbnailRenderer.cpp | 0 .../Source/{Previewer => SharedPreview}/CommonThumbnailRenderer.h | 0 .../Source/{Previewer => SharedPreview}/CommonThumbnailUtils.cpp | 0 .../Source/{Previewer => SharedPreview}/CommonThumbnailUtils.h | 0 13 files changed, 0 insertions(+), 0 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewContent.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewContent.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewer.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewer.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewer.ui (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewerFactory.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonPreviewerFactory.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnail.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnail.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnailRenderer.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnailRenderer.h (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnailUtils.cpp (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/{Previewer => SharedPreview}/CommonThumbnailUtils.h (100%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewContent.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.ui b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.ui similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewer.ui rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.ui diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonPreviewerFactory.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailRenderer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/Previewer/CommonThumbnailUtils.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.h From 3ee45d54bb06f553b03d0f87cc4258df352cd933 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sun, 10 Oct 2021 00:37:13 -0500 Subject: [PATCH 14/52] rename Common*.* Shared*.* Signed-off-by: Guthrie Adams --- .../{CommonPreviewContent.cpp => SharedPreviewContent.cpp} | 0 .../{CommonPreviewContent.h => SharedPreviewContent.h} | 0 .../SharedPreview/{CommonPreviewer.cpp => SharedPreviewer.cpp} | 0 .../Source/SharedPreview/{CommonPreviewer.h => SharedPreviewer.h} | 0 .../SharedPreview/{CommonPreviewer.ui => SharedPreviewer.ui} | 0 .../{CommonPreviewerFactory.cpp => SharedPreviewerFactory.cpp} | 0 .../{CommonPreviewerFactory.h => SharedPreviewerFactory.h} | 0 .../SharedPreview/{CommonThumbnail.cpp => SharedThumbnail.cpp} | 0 .../Source/SharedPreview/{CommonThumbnail.h => SharedThumbnail.h} | 0 .../{CommonThumbnailRenderer.cpp => SharedThumbnailRenderer.cpp} | 0 .../{CommonThumbnailRenderer.h => SharedThumbnailRenderer.h} | 0 .../{CommonThumbnailUtils.cpp => SharedThumbnailUtils.cpp} | 0 .../{CommonThumbnailUtils.h => SharedThumbnailUtils.h} | 0 13 files changed, 0 insertions(+), 0 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewContent.cpp => SharedPreviewContent.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewContent.h => SharedPreviewContent.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewer.cpp => SharedPreviewer.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewer.h => SharedPreviewer.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewer.ui => SharedPreviewer.ui} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewerFactory.cpp => SharedPreviewerFactory.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonPreviewerFactory.h => SharedPreviewerFactory.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnail.cpp => SharedThumbnail.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnail.h => SharedThumbnail.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnailRenderer.cpp => SharedThumbnailRenderer.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnailRenderer.h => SharedThumbnailRenderer.h} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnailUtils.cpp => SharedThumbnailUtils.cpp} (100%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{CommonThumbnailUtils.h => SharedThumbnailUtils.h} (100%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewContent.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.ui b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewer.ui rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonPreviewerFactory.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnail.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailRenderer.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h similarity index 100% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/CommonThumbnailUtils.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h From 9f92bd2d331a8f3e0223111e78d12c106b2c558d Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sun, 10 Oct 2021 01:45:13 -0500 Subject: [PATCH 15/52] Compile again after renaming and moving files Cleaned up namespaces Renamed a couple of functions and added comments Signed-off-by: Guthrie Adams --- .../PreviewRenderer/PreviewContent.h | 2 +- .../PreviewRenderer/PreviewRenderer.h | 12 +- .../PreviewRenderer/PreviewRenderer.cpp | 14 +- .../PreviewRendererCaptureState.cpp | 2 +- .../PreviewRendererIdleState.cpp | 2 +- .../PreviewRendererLoadState.cpp | 6 +- .../EditorCommonFeaturesSystemComponent.cpp | 10 +- .../EditorCommonFeaturesSystemComponent.h | 8 +- .../EditorMaterialSystemComponent.cpp | 4 +- .../SharedPreview/SharedPreviewContent.cpp | 28 ++-- .../SharedPreview/SharedPreviewContent.h | 12 +- .../Source/SharedPreview/SharedPreviewer.cpp | 26 +-- .../Source/SharedPreview/SharedPreviewer.h | 14 +- .../Source/SharedPreview/SharedPreviewer.ui | 4 +- .../SharedPreview/SharedPreviewerFactory.cpp | 16 +- .../SharedPreview/SharedPreviewerFactory.h | 10 +- .../Source/SharedPreview/SharedThumbnail.cpp | 156 +++++++++--------- .../Source/SharedPreview/SharedThumbnail.h | 69 ++++---- .../SharedPreview/SharedThumbnailRenderer.cpp | 101 ++++++------ .../SharedPreview/SharedThumbnailRenderer.h | 54 +++--- .../SharedPreview/SharedThumbnailUtils.cpp | 14 +- .../SharedPreview/SharedThumbnailUtils.h | 10 +- ...egration_commonfeatures_editor_files.cmake | 26 +-- 23 files changed, 295 insertions(+), 305 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h index 17445835ba..bdc7afe0b1 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h @@ -24,6 +24,6 @@ namespace AtomToolsFramework virtual bool IsReady() const = 0; virtual bool IsError() const = 0; virtual void ReportErrors() = 0; - virtual void UpdateScene() = 0; + virtual void Update() = 0; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h index acedc77751..d4fdd3ca1e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h @@ -24,7 +24,7 @@ class QPixmap; namespace AtomToolsFramework { - //! Provides custom rendering of preview images + //! Processes requests for setting up content that gets rendered to a texture and captured to an image class PreviewRenderer final : public PreviewerFeatureProcessorProviderBus::Handler { public: @@ -58,15 +58,15 @@ namespace AtomToolsFramework void SetState(State state); State GetState() const; - void SelectCaptureRequest(); + void ProcessCaptureRequests(); void CancelCaptureRequest(); void CompleteCaptureRequest(); - void LoadAssets(); - void UpdateLoadAssets(); - void CancelLoadAssets(); + void LoadContent(); + void UpdateLoadContent(); + void CancelLoadContent(); - void UpdateScene(); + void PoseContent(); bool StartCapture(); void EndCapture(); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index 06969abee4..69a8d357c9 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -142,7 +142,7 @@ namespace AtomToolsFramework return m_currentState; } - void PreviewRenderer::SelectCaptureRequest() + void PreviewRenderer::ProcessCaptureRequests() { if (!m_captureRequestQueue.empty()) { @@ -165,12 +165,12 @@ namespace AtomToolsFramework SetState(PreviewRenderer::State::IdleState); } - void PreviewRenderer::LoadAssets() + void PreviewRenderer::LoadContent() { m_currentCaptureRequest.m_content->Load(); } - void PreviewRenderer::UpdateLoadAssets() + void PreviewRenderer::UpdateLoadContent() { if (m_currentCaptureRequest.m_content->IsReady()) { @@ -180,20 +180,20 @@ namespace AtomToolsFramework if (m_currentCaptureRequest.m_content->IsError()) { - CancelLoadAssets(); + CancelLoadContent(); return; } } - void PreviewRenderer::CancelLoadAssets() + void PreviewRenderer::CancelLoadContent() { m_currentCaptureRequest.m_content->ReportErrors(); CancelCaptureRequest(); } - void PreviewRenderer::UpdateScene() + void PreviewRenderer::PoseContent() { - m_currentCaptureRequest.m_content->UpdateScene(); + m_currentCaptureRequest.m_content->Update(); } bool PreviewRenderer::StartCapture() diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp index f3414bc29f..9cf228b707 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp @@ -19,7 +19,7 @@ namespace AtomToolsFramework void PreviewRendererCaptureState::Start() { m_ticksToCapture = 1; - m_renderer->UpdateScene(); + m_renderer->PoseContent(); AZ::TickBus::Handler::BusConnect(); } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp index db91bedce1..800aa03113 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp @@ -28,6 +28,6 @@ namespace AtomToolsFramework void PreviewRendererIdleState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - m_renderer->SelectCaptureRequest(); + m_renderer->ProcessCaptureRequests(); } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp index b5d219636e..bb858989f7 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp @@ -18,7 +18,7 @@ namespace AtomToolsFramework void PreviewRendererLoadState::Start() { - m_renderer->LoadAssets(); + m_renderer->LoadContent(); m_timeRemainingS = TimeOutS; AZ::TickBus::Handler::BusConnect(); } @@ -33,11 +33,11 @@ namespace AtomToolsFramework m_timeRemainingS -= deltaTime; if (m_timeRemainingS > 0.0f) { - m_renderer->UpdateLoadAssets(); + m_renderer->UpdateLoadContent(); } else { - m_renderer->CancelLoadAssets(); + m_renderer->CancelLoadContent(); } } } // namespace AtomToolsFramework diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp index 47dd5ce571..1718dde5d4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include @@ -216,11 +216,11 @@ namespace AZ using namespace LyIntegration; ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(Thumbnails::CommonThumbnailCache), + &ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(SharedThumbnailCache), ThumbnailContext::DefaultContext); - m_renderer = AZStd::make_unique(); - m_previewerFactory = AZStd::make_unique(); + m_renderer = AZStd::make_unique(); + m_previewerFactory = AZStd::make_unique(); } void EditorCommonFeaturesSystemComponent::TeardownThumbnails() @@ -229,7 +229,7 @@ namespace AZ using namespace LyIntegration; ThumbnailerRequestsBus::Broadcast( - &ThumbnailerRequests::UnregisterThumbnailProvider, Thumbnails::CommonThumbnailCache::ProviderName, + &ThumbnailerRequests::UnregisterThumbnailProvider, SharedThumbnailCache::ProviderName, ThumbnailContext::DefaultContext); m_renderer.reset(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h index b9a4151955..8021770873 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/EditorCommonFeaturesSystemComponent.h @@ -13,8 +13,8 @@ #include #include #include -#include -#include +#include +#include namespace AZ { @@ -78,8 +78,8 @@ namespace AZ AZStd::string m_atomLevelDefaultAssetPath{ "LevelAssets/default.slice" }; float m_envProbeHeight{ 200.0f }; - AZStd::unique_ptr m_renderer; - AZStd::unique_ptr m_previewerFactory; + AZStd::unique_ptr m_renderer; + AZStd::unique_ptr m_previewerFactory; }; } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index e18cc0b907..96a8e3e8d4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class @@ -176,7 +176,7 @@ namespace AZ m_previewRenderer->AddCaptureRequest( { 128, - AZStd::make_shared( + AZStd::make_shared( m_previewRenderer->GetScene(), m_previewRenderer->GetView(), m_previewRenderer->GetEntityContextId(), AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath), materialAssetId, AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath), propertyOverrides), diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp index 966877317c..21020f64b1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp @@ -23,13 +23,13 @@ #include #include #include -#include +#include namespace AZ { namespace LyIntegration { - CommonPreviewContent::CommonPreviewContent( + SharedPreviewContent::SharedPreviewContent( RPI::ScenePtr scene, RPI::ViewPtr view, AZ::Uuid entityContextId, @@ -56,7 +56,7 @@ namespace AZ m_lightingPresetAsset.Create(lightingPresetAssetId); } - CommonPreviewContent::~CommonPreviewContent() + SharedPreviewContent::~SharedPreviewContent() { if (m_modelEntity) { @@ -66,46 +66,46 @@ namespace AZ } } - void CommonPreviewContent::Load() + void SharedPreviewContent::Load() { m_modelAsset.QueueLoad(); m_materialAsset.QueueLoad(); m_lightingPresetAsset.QueueLoad(); } - bool CommonPreviewContent::IsReady() const + bool SharedPreviewContent::IsReady() const { return (!m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady()) && (!m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady()) && (!m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady()); } - bool CommonPreviewContent::IsError() const + bool SharedPreviewContent::IsError() const { return m_modelAsset.IsError() || m_materialAsset.IsError() || m_lightingPresetAsset.IsError(); } - void CommonPreviewContent::ReportErrors() + void SharedPreviewContent::ReportErrors() { AZ_Warning( - "CommonPreviewContent", !m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady(), "Asset failed to load in time: %s", + "SharedPreviewContent", !m_modelAsset.GetId().IsValid() || m_modelAsset.IsReady(), "Asset failed to load in time: %s", m_modelAsset.ToString().c_str()); AZ_Warning( - "CommonPreviewContent", !m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady(), "Asset failed to load in time: %s", + "SharedPreviewContent", !m_materialAsset.GetId().IsValid() || m_materialAsset.IsReady(), "Asset failed to load in time: %s", m_materialAsset.ToString().c_str()); AZ_Warning( - "CommonPreviewContent", !m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady(), + "SharedPreviewContent", !m_lightingPresetAsset.GetId().IsValid() || m_lightingPresetAsset.IsReady(), "Asset failed to load in time: %s", m_lightingPresetAsset.ToString().c_str()); } - void CommonPreviewContent::UpdateScene() + void SharedPreviewContent::Update() { UpdateModel(); UpdateLighting(); UpdateCamera(); } - void CommonPreviewContent::UpdateModel() + void SharedPreviewContent::UpdateModel() { Render::MeshComponentRequestBus::Event( m_modelEntity->GetId(), &Render::MeshComponentRequestBus::Events::SetModelAsset, m_modelAsset); @@ -119,7 +119,7 @@ namespace AZ Render::DefaultMaterialAssignmentId, m_materialPropertyOverrides); } - void CommonPreviewContent::UpdateLighting() + void SharedPreviewContent::UpdateLighting() { if (m_lightingPresetAsset.IsReady()) { @@ -152,7 +152,7 @@ namespace AZ } } - void CommonPreviewContent::UpdateCamera() + void SharedPreviewContent::UpdateCamera() { // Get bounding sphere of the model asset and estimate how far the camera needs to be see all of it Vector3 center = {}; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h index a6bb2f6c4e..7308aa19bc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.h @@ -19,13 +19,13 @@ namespace AZ { namespace LyIntegration { - //! Provides custom rendering of material and model previews - class CommonPreviewContent final : public AtomToolsFramework::PreviewContent + //! Creates a simple scene used for most previews and thumbnails + class SharedPreviewContent final : public AtomToolsFramework::PreviewContent { public: - AZ_CLASS_ALLOCATOR(CommonPreviewContent, AZ::SystemAllocator, 0); + AZ_CLASS_ALLOCATOR(SharedPreviewContent, AZ::SystemAllocator, 0); - CommonPreviewContent( + SharedPreviewContent( RPI::ScenePtr scene, RPI::ViewPtr view, AZ::Uuid entityContextId, @@ -34,13 +34,13 @@ namespace AZ const Data::AssetId& lightingPresetAssetId, const Render::MaterialPropertyOverrideMap& materialPropertyOverrides); - ~CommonPreviewContent() override; + ~SharedPreviewContent() override; void Load() override; bool IsReady() const override; bool IsError() const override; void ReportErrors() override; - void UpdateScene() override; + void Update() override; private: void UpdateModel(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp index 9ecc41e0f2..73080b5c05 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp @@ -12,14 +12,14 @@ #include #include #include -#include -#include +#include +#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include +#include #include #include AZ_POP_DISABLE_WARNING @@ -30,22 +30,22 @@ namespace AZ { static constexpr int CharWidth = 6; - CommonPreviewer::CommonPreviewer(QWidget* parent) + SharedPreviewer::SharedPreviewer(QWidget* parent) : Previewer(parent) - , m_ui(new Ui::CommonPreviewerClass()) + , m_ui(new Ui::SharedPreviewerClass()) { m_ui->setupUi(this); } - CommonPreviewer::~CommonPreviewer() + SharedPreviewer::~SharedPreviewer() { } - void CommonPreviewer::Clear() const + void SharedPreviewer::Clear() const { } - void CommonPreviewer::Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) + void SharedPreviewer::Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) { using namespace AzToolsFramework::AssetBrowser; using namespace AzToolsFramework::Thumbnailer; @@ -56,23 +56,23 @@ namespace AZ UpdateFileInfo(); } - const QString& CommonPreviewer::GetName() const + const QString& SharedPreviewer::GetName() const { return m_name; } - void CommonPreviewer::resizeEvent([[maybe_unused]] QResizeEvent* event) + void SharedPreviewer::resizeEvent([[maybe_unused]] QResizeEvent* event) { m_ui->m_previewWidget->setMaximumHeight(m_ui->m_previewWidget->width()); UpdateFileInfo(); } - void CommonPreviewer::UpdateFileInfo() const + void SharedPreviewer::UpdateFileInfo() const { - m_ui->m_fileInfoLabel->setText(Thumbnails::WordWrap(m_fileInfo, m_ui->m_fileInfoLabel->width() / CharWidth)); + m_ui->m_fileInfoLabel->setText(SharedPreviewUtils::WordWrap(m_fileInfo, m_ui->m_fileInfoLabel->width() / CharWidth)); } } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h index 6d2108d826..ab6f793982 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.h @@ -21,7 +21,7 @@ AZ_POP_DISABLE_WARNING namespace Ui { - class CommonPreviewerClass; + class SharedPreviewerClass; } namespace AzToolsFramework @@ -40,14 +40,14 @@ namespace AZ { namespace LyIntegration { - class CommonPreviewer final : public AzToolsFramework::AssetBrowser::Previewer + class SharedPreviewer final : public AzToolsFramework::AssetBrowser::Previewer { Q_OBJECT public: - AZ_CLASS_ALLOCATOR(CommonPreviewer, AZ::SystemAllocator, 0); + AZ_CLASS_ALLOCATOR(SharedPreviewer, AZ::SystemAllocator, 0); - explicit CommonPreviewer(QWidget* parent = nullptr); - ~CommonPreviewer(); + explicit SharedPreviewer(QWidget* parent = nullptr); + ~SharedPreviewer(); // AzToolsFramework::AssetBrowser::Previewer overrides... void Clear() const override; @@ -60,9 +60,9 @@ namespace AZ private: void UpdateFileInfo() const; - QScopedPointer m_ui; + QScopedPointer m_ui; QString m_fileInfo; - QString m_name = "CommonPreviewer"; + QString m_name = "SharedPreviewer"; }; } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui index f97dde0a1f..139231d607 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.ui @@ -1,7 +1,7 @@ - CommonPreviewerClass - + SharedPreviewerClass + 0 diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp index f947cfd8ba..95593402f3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp @@ -11,25 +11,25 @@ #include #include #include -#include -#include -#include +#include +#include +#include namespace AZ { namespace LyIntegration { - AzToolsFramework::AssetBrowser::Previewer* CommonPreviewerFactory::CreatePreviewer(QWidget* parent) const + AzToolsFramework::AssetBrowser::Previewer* SharedPreviewerFactory::CreatePreviewer(QWidget* parent) const { - return new CommonPreviewer(parent); + return new SharedPreviewer(parent); } - bool CommonPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const + bool SharedPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const { - return Thumbnails::IsSupportedThumbnail(entry->GetThumbnailKey()); + return SharedPreviewUtils::IsSupportedAssetType(entry->GetThumbnailKey()); } - const QString& CommonPreviewerFactory::GetName() const + const QString& SharedPreviewerFactory::GetName() const { return m_name; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h index cec4ccc21f..e3021cb8ab 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.h @@ -19,13 +19,13 @@ namespace AZ { namespace LyIntegration { - class CommonPreviewerFactory final : public AzToolsFramework::AssetBrowser::PreviewerFactory + class SharedPreviewerFactory final : public AzToolsFramework::AssetBrowser::PreviewerFactory { public: - AZ_CLASS_ALLOCATOR(CommonPreviewerFactory, AZ::SystemAllocator, 0); + AZ_CLASS_ALLOCATOR(SharedPreviewerFactory, AZ::SystemAllocator, 0); - CommonPreviewerFactory() = default; - ~CommonPreviewerFactory() = default; + SharedPreviewerFactory() = default; + ~SharedPreviewerFactory() = default; // AzToolsFramework::AssetBrowser::PreviewerFactory overrides... AzToolsFramework::AssetBrowser::Previewer* CreatePreviewer(QWidget* parent = nullptr) const override; @@ -33,7 +33,7 @@ namespace AZ const QString& GetName() const override; private: - QString m_name = "CommonPreviewer"; + QString m_name = "SharedPreviewer"; }; } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp index 298d062b7d..dcc5244d8c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp @@ -10,104 +10,100 @@ #include #include #include -#include -#include +#include +#include #include namespace AZ { namespace LyIntegration { - namespace Thumbnails + static constexpr const int SharedThumbnailSize = 256; + + ////////////////////////////////////////////////////////////////////////// + // SharedThumbnail + ////////////////////////////////////////////////////////////////////////// + SharedThumbnail::SharedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + : Thumbnail(key) { - static constexpr const int CommonThumbnailSize = 256; - - ////////////////////////////////////////////////////////////////////////// - // CommonThumbnail - ////////////////////////////////////////////////////////////////////////// - CommonThumbnail::CommonThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) - : Thumbnail(key) + for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) { - for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) + const AZ::Data::AssetId& assetId = SharedPreviewUtils::GetAssetId(key, typeId); + if (assetId.IsValid()) { - const AZ::Data::AssetId& assetId = GetAssetId(key, typeId); - if (assetId.IsValid()) - { - m_assetId = assetId; - m_typeId = typeId; - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - return; - } - } - - AZ_Error("CommonThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); - m_state = State::Failed; - } - - void CommonThumbnail::LoadThread() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( - m_typeId, &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, - CommonThumbnailSize); - // wait for response from thumbnail renderer - m_renderWait.acquire(); - } - - CommonThumbnail::~CommonThumbnail() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - } - - void CommonThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) - { - m_pixmap = thumbnailImage; - m_renderWait.release(); - } - - void CommonThumbnail::ThumbnailFailedToRender() - { - m_state = State::Failed; - m_renderWait.release(); - } - - void CommonThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) - { - if (m_assetId == assetId && m_state == State::Ready) - { - m_state = State::Unloaded; - Load(); + m_assetId = assetId; + m_typeId = typeId; + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusConnect(key); + AzFramework::AssetCatalogEventBus::Handler::BusConnect(); + return; } } - ////////////////////////////////////////////////////////////////////////// - // CommonThumbnailCache - ////////////////////////////////////////////////////////////////////////// - CommonThumbnailCache::CommonThumbnailCache() - : ThumbnailCache() - { - } + AZ_Error("SharedThumbnail", false, "Failed to find matching assetId for the thumbnailKey."); + m_state = State::Failed; + } - CommonThumbnailCache::~CommonThumbnailCache() = default; + void SharedThumbnail::LoadThread() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::QueueEvent( + m_typeId, &AzToolsFramework::Thumbnailer::ThumbnailerRendererRequests::RenderThumbnail, m_key, SharedThumbnailSize); + // wait for response from thumbnail renderer + m_renderWait.acquire(); + } - int CommonThumbnailCache::GetPriority() const - { - // Thumbnails override default source thumbnails, so carry higher priority - return 1; - } + SharedThumbnail::~SharedThumbnail() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler::BusDisconnect(); + AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); + } - const char* CommonThumbnailCache::GetProviderName() const - { - return ProviderName; - } + void SharedThumbnail::ThumbnailRendered(const QPixmap& thumbnailImage) + { + m_pixmap = thumbnailImage; + m_renderWait.release(); + } - bool CommonThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const + void SharedThumbnail::ThumbnailFailedToRender() + { + m_state = State::Failed; + m_renderWait.release(); + } + + void SharedThumbnail::OnCatalogAssetChanged([[maybe_unused]] const AZ::Data::AssetId& assetId) + { + if (m_assetId == assetId && m_state == State::Ready) { - return Thumbnails::IsSupportedThumbnail(key); + m_state = State::Unloaded; + Load(); } - } // namespace Thumbnails + } + + ////////////////////////////////////////////////////////////////////////// + // SharedThumbnailCache + ////////////////////////////////////////////////////////////////////////// + SharedThumbnailCache::SharedThumbnailCache() + : ThumbnailCache() + { + } + + SharedThumbnailCache::~SharedThumbnailCache() = default; + + int SharedThumbnailCache::GetPriority() const + { + // Thumbnails override default source thumbnails, so carry higher priority + return 1; + } + + const char* SharedThumbnailCache::GetProviderName() const + { + return ProviderName; + } + + bool SharedThumbnailCache::IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const + { + return SharedPreviewUtils::IsSupportedAssetType(key); + } } // namespace LyIntegration } // namespace AZ -#include +#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h index 195452ca21..d65e94a7a3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.h @@ -19,50 +19,47 @@ namespace AZ { namespace LyIntegration { - namespace Thumbnails + //! Custom thumbnail that detects when an asset changes and updates the thumbnail + class SharedThumbnail final + : public AzToolsFramework::Thumbnailer::Thumbnail + , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler + , private AzFramework::AssetCatalogEventBus::Handler { - //! Custom thumbnail that detects when an asset changes and updates the thumbnail - class CommonThumbnail - : public AzToolsFramework::Thumbnailer::Thumbnail - , public AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Handler - , private AzFramework::AssetCatalogEventBus::Handler - { - Q_OBJECT - public: - CommonThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - ~CommonThumbnail() override; + Q_OBJECT + public: + SharedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + ~SharedThumbnail() override; - //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... - void ThumbnailRendered(const QPixmap& thumbnailImage) override; - void ThumbnailFailedToRender() override; + //! AzToolsFramework::ThumbnailerRendererNotificationBus::Handler overrides... + void ThumbnailRendered(const QPixmap& thumbnailImage) override; + void ThumbnailFailedToRender() override; - protected: - void LoadThread() override; + protected: + void LoadThread() override; - private: - // AzFramework::AssetCatalogEventBus::Handler interface overrides... - void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; + private: + // AzFramework::AssetCatalogEventBus::Handler interface overrides... + void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; - AZStd::binary_semaphore m_renderWait; - Data::AssetId m_assetId; - AZ::Uuid m_typeId; - }; + AZStd::binary_semaphore m_renderWait; + Data::AssetId m_assetId; + AZ::Uuid m_typeId; + }; - //! Cache configuration for large thumbnails - class CommonThumbnailCache : public AzToolsFramework::Thumbnailer::ThumbnailCache - { - public: - CommonThumbnailCache(); - ~CommonThumbnailCache() override; + //! Cache configuration for large thumbnails + class SharedThumbnailCache final : public AzToolsFramework::Thumbnailer::ThumbnailCache + { + public: + SharedThumbnailCache(); + ~SharedThumbnailCache() override; - int GetPriority() const override; - const char* GetProviderName() const override; + int GetPriority() const override; + const char* GetProviderName() const override; - static constexpr const char* ProviderName = "Common Thumbnails"; + static constexpr const char* ProviderName = "Common Feature Shared Thumbnail= Provider"; - protected: - bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; - }; - } // namespace Thumbnails + protected: + bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) const override; + }; } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp index 0eb6a9b4a3..28b2290d23 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp @@ -8,69 +8,66 @@ #include #include -#include -#include -#include +#include +#include +#include namespace AZ { namespace LyIntegration { - namespace Thumbnails + SharedThumbnailRenderer::SharedThumbnailRenderer() { - CommonThumbnailRenderer::CommonThumbnailRenderer() + m_previewRenderer.reset(aznew AtomToolsFramework::PreviewRenderer( + "SharedThumbnailRenderer Preview Scene", "SharedThumbnailRenderer Preview Pipeline")); + + m_defaultModelAsset.Create(DefaultModelAssetId, true); + m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); + m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); + + for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) { - m_previewRenderer.reset(aznew AtomToolsFramework::PreviewRenderer( - "CommonThumbnailRenderer Preview Scene", "CommonThumbnailRenderer Preview Pipeline")); - - m_defaultModelAsset.Create(DefaultModelAssetId, true); - m_defaultMaterialAsset.Create(DefaultMaterialAssetId, true); - m_defaultLightingPresetAsset.Create(DefaultLightingPresetAssetId, true); - - for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(typeId); - } - SystemTickBus::Handler::BusConnect(); + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusConnect(typeId); } + SystemTickBus::Handler::BusConnect(); + } - CommonThumbnailRenderer::~CommonThumbnailRenderer() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); - SystemTickBus::Handler::BusDisconnect(); - } + SharedThumbnailRenderer::~SharedThumbnailRenderer() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler::BusDisconnect(); + SystemTickBus::Handler::BusDisconnect(); + } - void CommonThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) - { - m_previewRenderer->AddCaptureRequest( - { thumbnailSize, - AZStd::make_shared( - m_previewRenderer->GetScene(), m_previewRenderer->GetView(), m_previewRenderer->GetEntityContextId(), - GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type(), DefaultModelAssetId), - GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type(), DefaultMaterialAssetId), - GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type(), DefaultLightingPresetAssetId), - Render::MaterialPropertyOverrideMap()), - [thumbnailKey]() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); - }, - [thumbnailKey](const QPixmap& pixmap) - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( - thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, pixmap); - } }); - } + void SharedThumbnailRenderer::RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) + { + m_previewRenderer->AddCaptureRequest( + { thumbnailSize, + AZStd::make_shared( + m_previewRenderer->GetScene(), m_previewRenderer->GetView(), m_previewRenderer->GetEntityContextId(), + SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::ModelAsset::RTTI_Type(), DefaultModelAssetId), + SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::MaterialAsset::RTTI_Type(), DefaultMaterialAssetId), + SharedPreviewUtils::GetAssetId(thumbnailKey, RPI::AnyAsset::RTTI_Type(), DefaultLightingPresetAssetId), + Render::MaterialPropertyOverrideMap()), + [thumbnailKey]() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailFailedToRender); + }, + [thumbnailKey](const QPixmap& pixmap) + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererNotificationBus::Event( + thumbnailKey, &AzToolsFramework::Thumbnailer::ThumbnailerRendererNotifications::ThumbnailRendered, pixmap); + } }); + } - bool CommonThumbnailRenderer::Installed() const - { - return true; - } + bool SharedThumbnailRenderer::Installed() const + { + return true; + } - void CommonThumbnailRenderer::OnSystemTick() - { - AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); - } - } // namespace Thumbnails + void SharedThumbnailRenderer::OnSystemTick() + { + AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::ExecuteQueuedEvents(); + } } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h index a57c3dae8e..bcefbd6f4e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.h @@ -22,41 +22,39 @@ namespace AZ { namespace LyIntegration { - namespace Thumbnails + //! Provides custom rendering thumbnails of supported asset types + class SharedThumbnailRenderer final + : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler + , public SystemTickBus::Handler { - //! Provides custom rendering of material and model thumbnails - class CommonThumbnailRenderer - : public AzToolsFramework::Thumbnailer::ThumbnailerRendererRequestBus::MultiHandler - , public SystemTickBus::Handler - { - public: - AZ_CLASS_ALLOCATOR(CommonThumbnailRenderer, AZ::SystemAllocator, 0); + public: + AZ_CLASS_ALLOCATOR(SharedThumbnailRenderer, AZ::SystemAllocator, 0); - CommonThumbnailRenderer(); - ~CommonThumbnailRenderer(); + SharedThumbnailRenderer(); + ~SharedThumbnailRenderer(); - private: - //! ThumbnailerRendererRequestsBus::Handler interface overrides... - void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; - bool Installed() const override; + private: + //! ThumbnailerRendererRequestsBus::Handler interface overrides... + void RenderThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey thumbnailKey, int thumbnailSize) override; + bool Installed() const override; - //! SystemTickBus::Handler interface overrides... - void OnSystemTick() override; + //! SystemTickBus::Handler interface overrides... + void OnSystemTick() override; - static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; - const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); - Data::Asset m_defaultLightingPresetAsset; + // Default assets to be kept loaded and used for rendering if not overridden + static constexpr const char* DefaultLightingPresetPath = "lightingpresets/thumbnail.lightingpreset.azasset"; + const Data::AssetId DefaultLightingPresetAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultLightingPresetPath); + Data::Asset m_defaultLightingPresetAsset; - static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; - const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); - Data::Asset m_defaultModelAsset; + static constexpr const char* DefaultModelPath = "models/sphere.azmodel"; + const Data::AssetId DefaultModelAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultModelPath); + Data::Asset m_defaultModelAsset; - static constexpr const char* DefaultMaterialPath = ""; - const Data::AssetId DefaultMaterialAssetId; - Data::Asset m_defaultMaterialAsset; + static constexpr const char* DefaultMaterialPath = ""; + const Data::AssetId DefaultMaterialAssetId; + Data::Asset m_defaultMaterialAsset; - AZStd::unique_ptr m_previewRenderer; - }; - } // namespace Thumbnails + AZStd::unique_ptr m_previewRenderer; + }; } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp index 013bc4261b..398e50e10a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp @@ -9,16 +9,16 @@ #include #include #include -#include #include #include #include +#include namespace AZ { namespace LyIntegration { - namespace Thumbnails + namespace SharedPreviewUtils { Data::AssetId GetAssetId( AzToolsFramework::Thumbnailer::SharedThumbnailKey key, @@ -86,16 +86,16 @@ namespace AZ return result; } - AZStd::unordered_set GetSupportedThumbnailAssetTypes() + AZStd::unordered_set GetSupportedAssetTypes() { return { RPI::AnyAsset::RTTI_Type(), RPI::MaterialAsset::RTTI_Type(), RPI::ModelAsset::RTTI_Type() }; } - bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) + bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key) { - for (const AZ::Uuid& typeId : GetSupportedThumbnailAssetTypes()) + for (const AZ::Uuid& typeId : SharedPreviewUtils::GetSupportedAssetTypes()) { - const AZ::Data::AssetId& assetId = GetAssetId(key, typeId); + const AZ::Data::AssetId& assetId = SharedPreviewUtils::GetAssetId(key, typeId); if (assetId.IsValid()) { if (typeId == RPI::AnyAsset::RTTI_Type()) @@ -111,6 +111,6 @@ namespace AZ return false; } - } // namespace Thumbnails + } // namespace SharedPreviewUtils } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h index be2432bc7b..51b8981e41 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h @@ -18,7 +18,7 @@ namespace AZ { namespace LyIntegration { - namespace Thumbnails + namespace SharedPreviewUtils { //! Get assetId by assetType that belongs to either source or product thumbnail key Data::AssetId GetAssetId( @@ -30,9 +30,11 @@ namespace AZ //! wrap needed QString WordWrap(const QString& string, int maxLength); - AZStd::unordered_set GetSupportedThumbnailAssetTypes(); + //! Get the set of all asset types supported by the shared preview + AZStd::unordered_set GetSupportedAssetTypes(); - bool IsSupportedThumbnail(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); - } // namespace Thumbnails + //! Determine if a thumbnail key has an asset the shared preview + bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); + } // namespace SharedPreviewUtils } // namespace LyIntegration } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 00d3f09978..6babd43db7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -91,19 +91,19 @@ set(FILES Source/SkyBox/EditorHDRiSkyboxComponent.h Source/SkyBox/EditorPhysicalSkyComponent.cpp Source/SkyBox/EditorPhysicalSkyComponent.h - Source/Previewer/CommonPreviewer.cpp - Source/Previewer/CommonPreviewer.h - Source/Previewer/CommonPreviewer.ui - Source/Previewer/CommonPreviewerFactory.cpp - Source/Previewer/CommonPreviewerFactory.h - Source/Previewer/CommonPreviewContent.cpp - Source/Previewer/CommonPreviewContent.h - Source/Previewer/CommonThumbnail.cpp - Source/Previewer/CommonThumbnail.h - Source/Previewer/CommonThumbnailRenderer.cpp - Source/Previewer/CommonThumbnailRenderer.h - Source/Previewer/CommonThumbnailUtils.cpp - Source/Previewer/CommonThumbnailUtils.h + Source/SharedPreview/SharedPreviewer.cpp + Source/SharedPreview/SharedPreviewer.h + Source/SharedPreview/SharedPreviewer.ui + Source/SharedPreview/SharedPreviewerFactory.cpp + Source/SharedPreview/SharedPreviewerFactory.h + Source/SharedPreview/SharedPreviewContent.cpp + Source/SharedPreview/SharedPreviewContent.h + Source/SharedPreview/SharedThumbnail.cpp + Source/SharedPreview/SharedThumbnail.h + Source/SharedPreview/SharedThumbnailRenderer.cpp + Source/SharedPreview/SharedThumbnailRenderer.h + Source/SharedPreview/SharedThumbnailUtils.cpp + Source/SharedPreview/SharedThumbnailUtils.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From 8aea92af29bf06ad455ab7a96715e848df4c3b5c Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Sun, 10 Oct 2021 02:10:15 -0500 Subject: [PATCH 16/52] renamed SharedThumbnailUtils to SharedPreviewUtils Signed-off-by: Guthrie Adams --- .../{SharedThumbnailUtils.cpp => SharedPreviewUtils.cpp} | 2 +- .../{SharedThumbnailUtils.h => SharedPreviewUtils.h} | 2 +- .../Code/Source/SharedPreview/SharedPreviewer.cpp | 4 ++-- .../Code/Source/SharedPreview/SharedPreviewerFactory.cpp | 6 +----- .../Code/Source/SharedPreview/SharedThumbnail.cpp | 7 ++----- .../Code/Source/SharedPreview/SharedThumbnailRenderer.cpp | 2 +- .../atomlyintegration_commonfeatures_editor_files.cmake | 4 ++-- 7 files changed, 10 insertions(+), 17 deletions(-) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{SharedThumbnailUtils.cpp => SharedPreviewUtils.cpp} (98%) rename Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/{SharedThumbnailUtils.h => SharedPreviewUtils.h} (93%) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp similarity index 98% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp index 398e50e10a..c2988cf53d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h similarity index 93% rename from Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h rename to Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h index 51b8981e41..6c5d83d22a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailUtils.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewUtils.h @@ -33,7 +33,7 @@ namespace AZ //! Get the set of all asset types supported by the shared preview AZStd::unordered_set GetSupportedAssetTypes(); - //! Determine if a thumbnail key has an asset the shared preview + //! Determine if a thumbnail key has an asset supported by the shared preview bool IsSupportedAssetType(AzToolsFramework::Thumbnailer::SharedThumbnailKey key); } // namespace SharedPreviewUtils } // namespace LyIntegration diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp index 73080b5c05..942af55721 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewer.cpp @@ -12,16 +12,16 @@ #include #include #include +#include #include -#include // Disables warning messages triggered by the Qt library // 4251: class needs to have dll-interface to be used by clients of class // 4800: forcing value to bool 'true' or 'false' (performance warning) AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") -#include #include #include +#include AZ_POP_DISABLE_WARNING namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp index 95593402f3..14d6e5b5f0 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewerFactory.cpp @@ -6,14 +6,10 @@ * */ -#include -#include -#include -#include #include +#include #include #include -#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp index dcc5244d8c..ebfad39229 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnail.cpp @@ -6,13 +6,10 @@ * */ -#include -#include -#include #include -#include -#include #include +#include +#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp index 28b2290d23..c20cef548f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedThumbnailRenderer.cpp @@ -9,8 +9,8 @@ #include #include #include +#include #include -#include namespace AZ { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index 6babd43db7..2714b65a56 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -98,12 +98,12 @@ set(FILES Source/SharedPreview/SharedPreviewerFactory.h Source/SharedPreview/SharedPreviewContent.cpp Source/SharedPreview/SharedPreviewContent.h + Source/SharedPreview/SharedPreviewUtils.cpp + Source/SharedPreview/SharedPreviewUtils.h Source/SharedPreview/SharedThumbnail.cpp Source/SharedPreview/SharedThumbnail.h Source/SharedPreview/SharedThumbnailRenderer.cpp Source/SharedPreview/SharedThumbnailRenderer.h - Source/SharedPreview/SharedThumbnailUtils.cpp - Source/SharedPreview/SharedThumbnailUtils.h Source/Scripting/EditorEntityReferenceComponent.cpp Source/Scripting/EditorEntityReferenceComponent.h Source/SurfaceData/EditorSurfaceDataMeshComponent.cpp From 1c3b293cd36da71dd5c34fc71521d9a81446b885 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Mon, 11 Oct 2021 07:28:34 -0700 Subject: [PATCH 17/52] fix comments replace /** with //! Signed-off-by: Michael Pollind --- .../AzCore/AzCore/Math/IntersectSegment.h | 454 ++++++++---------- .../AzCore/AzCore/Math/IntersectSegment.inl | 1 - 2 files changed, 204 insertions(+), 251 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h index 7be35c5ae6..ecb0d7acc9 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h @@ -16,56 +16,47 @@ namespace AZ { namespace Intersect { - /** - * LineToPointDistanceTime computes the time of the shortest distance from point 'p' to segment (s1,s2). - * To calculate the point of intersection: - * P = s1 + u (s2 - s1) - * @param s1 segment start point - * @param s2 segment end point - * @param p point to find the closest time to. - * @return time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] - */ + //! LineToPointDistanceTime computes the time of the shortest distance from point 'p' to segment (s1,s2). + //! To calculate the point of intersection: + //! P = s1 + u (s2 - s1) + //! @param s1 segment start point + //! @param s2 segment end point + //! @param p point to find the closest time to. + //! @return time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] float LineToPointDistanceTime(const Vector3& s1, const Vector3& s21, const Vector3& p); - /** - * LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). - * @param s1 segment start point - * @param s2 segment end point - * @param p point to find the closest time to. - * @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] - * @return the closest point - */ + //! LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). + //! @param s1 segment start point + //! @param s2 segment end point + //! @param p point to find the closest time to. + //! @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + //! @return the closest point Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u); - /** - * Given segment pq and triangle abc (CCW), returns whether segment intersects - * triangle and if so, also returns the barycentric coordinates (u,v,w) - * of the intersection point. - * - * @param p segment start point - * @param q segment end point - * @param a triangle point 1 - * @param b triangle point 2 - * @param c triangle point 3 - * @param normal at the intersection point. - * @param t time of intersection along the segment [0.0 (p), 1.0 (q)] - * @return true if the segments intersects the triangle otherwise false - */ + //! Given segment pq and triangle abc (CCW), returns whether segment intersects + //! triangle and if so, also returns the barycentric coordinates (u,v,w) + //! of the intersection point. + //! + //! @param p segment start point + //! @param q segment end point + //! @param a triangle point 1 + //! @param b triangle point 2 + //! @param c triangle point 3 + //! @param normal at the intersection point. + //! @param t time of intersection along the segment [0.0 (p), 1.0 (q)] + //! @return true if the segments intersects the triangle otherwise false int IntersectSegmentTriangleCCW( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); - /** - * Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). - * - * @param p segment start point - * @param q segment end point - * @param a triangle point 1 - * @param b triangle point 2 - * @param c triangle point 3 - * @param normal at the intersection point; - * @param t time of intersection along the segment [0.0 (p), 1.0 (q)] - * @return true if the segments intersects the triangle otherwise false - */ + //! Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). + //! //! @param p segment start point + //! @param q segment end point + //! @param a triangle point 1 + //! @param b triangle point 2 + //! @param c triangle point 3 + //! @param normal at the intersection point; + //! @param t time of intersection along the segment [0.0 (p), 1.0 (q)] + //! @return true if the segments intersects the triangle otherwise false int IntersectSegmentTriangle( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); @@ -77,19 +68,17 @@ namespace AZ ISECT_RAY_AABB_ISECT, ///< intersects along the PQ segment }; - /** - * Intersect ray R(t) = rayStart + t*d against AABB a. When intersecting, - * return intersection distance tmin and point q of intersection. - * @param rayStart ray starting point - * @param dir ray direction and length (dir = rayEnd - rayStart) - * @param dirRCP 1/dir (reciprocal direction - we cache this result very often so we don't need to compute it multiple times, - * otherwise just use dir.GetReciprocal()) - * @param aabb Axis aligned bounding box to intersect against - * @param tStart time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value - * @param tEnd time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) - * @param startNormal normal at the start point. - * @return \ref RayAABBIsectTypes - */ + //! Intersect ray R(t) = rayStart + t*d against AABB a. When intersecting, + //! return intersection distance tmin and point q of intersection. + //! @param rayStart ray starting point + //! @param dir ray direction and length (dir = rayEnd - rayStart) + //! @param dirRCP 1/dir (reciprocal direction - we cache this result very often so we don't need to compute it multiple times, + //! otherwise just use dir.GetReciprocal()) + //! @param aabb Axis aligned bounding box to intersect against + //! @param tStart time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value + //! @param tEnd time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) + //! @param startNormal normal at the start point. + //! @return \ref RayAABBIsectTypes RayAABBIsectTypes IntersectRayAABB( const Vector3& rayStart, const Vector3& dir, @@ -99,51 +88,43 @@ namespace AZ float& tEnd, Vector3& startNormal /*, Vector3& inter*/); - /** - * Intersect ray against AABB. - * - * @param rayStart ray starting point. - * @param dir ray reciprocal direction. - * @param aabb Axis aligned bounding box to intersect against. - * @param start length on ray of the first intersection. - * @param end length of the of the second intersection. - * @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and ISECT_RAY_AABB_ISECT. You can check yourself for that case. - */ + //! Intersect ray against AABB. + //! + //! @param rayStart ray starting point. + //! @param dir ray reciprocal direction. + //! @param aabb Axis aligned bounding box to intersect against. + //! @param start length on ray of the first intersection. + //! @param end length of the of the second intersection. + //! @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and ISECT_RAY_AABB_ISECT. You can check yourself for that case. RayAABBIsectTypes IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, float& start, float& end); - /** - * Clip a ray to an aabb. return true if ray was clipped. The ray - * can be inside so don't use the result if the ray intersect the box. - * - * @param aabb bounds - * @param rayStart the start of the ray - * @param rayEnd the end of the ray - * @param tClipStart[out] The proportion where the ray enterts the aabb - * @param tClipEnd[out] The proportion where the ray exits the aabb - * @return true ray was clipped else false - */ + //! Clip a ray to an aabb. return true if ray was clipped. The ray + //! can be inside so don't use the result if the ray intersect the box. + //! + //! @param aabb bounds + //! @param rayStart the start of the ray + //! @param rayEnd the end of the ray + //! @param tClipStart[out] The proportion where the ray enterts the aabb + //! @param tClipEnd[out] The proportion where the ray exits the aabb + //! @return true ray was clipped else false bool ClipRayWithAabb(const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd); - /** - * Test segment and aabb where the segment is defined by midpoint - * midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. - * the aabb is at the origin and defined by half extents only. - * - * @param midPoint midpoint of a line segment - * @param halfVector half vector of an aabb - * @param aabbExtends the extends of a bounded box - * @return 1 if the intersect, otherwise 0. - */ + //! Test segment and aabb where the segment is defined by midpoint + //! midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. + //! the aabb is at the origin and defined by half extents only. + //! + //! @param midPoint midpoint of a line segment + //! @param halfVector half vector of an aabb + //! @param aabbExtends the extends of a bounded box + //! @return 1 if the intersect, otherwise 0. bool TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends); - /** - * Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin - * - * @param p0 point 1 - * @param p1 point 2 - * @param aabb bounded box - * @return true if the segment and AABB intersect, otherwise false. - */ + //! Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin + //! + //! @param p0 point 1 + //! @param p1 point 2 + //! @param aabb bounded box + //! @return true if the segment and AABB intersect, otherwise false. bool TestSegmentAABB(const Vector3& p0, const Vector3& p1, const Aabb& aabb); //! Ray sphere intersection result types. @@ -154,42 +135,36 @@ namespace AZ ISECT_RAY_SPHERE_ISECT, // along the PQ segment }; - /** - * IntersectRaySphereOrigin - * return time t>=0 but not limited, so if you check a segment make sure - * t <= segmentLen - * @param rayStart ray start point - * @param rayDirNormalized ray direction normalized. - * @param shereRadius sphere radius - * @param time of closest intersection [0,+INF] in relation to the normalized direction. - * @return \ref SphereIsectTypes - **/ + //! IntersectRaySphereOrigin + //! return time t>=0 but not limited, so if you check a segment make sure + //! t <= segmentLen + //! @param rayStart ray start point + //! @param rayDirNormalized ray direction normalized. + //! @param shereRadius sphere radius + //! @param time of closest intersection [0,+INF] in relation to the normalized direction. + //! @return \ref SphereIsectTypes SphereIsectTypes IntersectRaySphereOrigin( const Vector3& rayStart, const Vector3& rayDirNormalized, const float sphereRadius, float& t); - /** - * Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin - * - * @param rayStart - * @param rayDirNormalized - * @param sphereCenter - * @param sphereRadius - * @param t - * @return int - */ + //! Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin + //! + //! @param rayStart + //! @param rayDirNormalized + //! @param sphereCenter + //! @param sphereRadius + //! @param t + //! @return SphereIsectTypes SphereIsectTypes IntersectRaySphere( const Vector3& rayStart, const Vector3& rayDirNormalized, const Vector3& sphereCenter, const float sphereRadius, float& t); - /** - * @param rayOrigin The origin of the ray to test. - * @param rayDir The direction of the ray to test. It has to be unit length. - * @param diskCenter Center point of the disk - * @param diskRadius Radius of the disk - * @param diskNormal A normal perpendicular to the disk - * @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir - * that the hit occured at. - * @return The number of intersecting points. - **/ + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param diskCenter Center point of the disk + //! @param diskRadius Radius of the disk + //! @param diskNormal A normal perpendicular to the disk + //! @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir + //! that the hit occured at. + //! @return The number of intersecting points. int IntersectRayDisk( const Vector3& rayOrigin, const Vector3& rayDir, @@ -198,20 +173,18 @@ namespace AZ const AZ::Vector3& diskNormal, float& t); - /** - * If there is only one intersecting point, the coefficient is stored in \ref t1. - * @param rayOrigin The origin of the ray to test. - * @param rayDir The direction of the ray to test. It has to be unit length. - * @param cylinderEnd1 The center of the circle on one end of the cylinder. - * @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit - * length. - * @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. - * @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - * as "rayOrigin + t1 * rayDir". - * @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - * as "rayOrigin + t2 * rayDir". - * @return The number of intersecting points. - **/ + //! If there is only one intersecting point, the coefficient is stored in \ref t1. + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param cylinderEnd1 The center of the circle on one end of the cylinder. + //! @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit + //! length. + //! @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. + //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + //! as "rayOrigin + t1 * rayDir". + //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + //! as "rayOrigin + t2 * rayDir". + //! @return The number of intersecting points. int IntersectRayCappedCylinder( const Vector3& rayOrigin, const Vector3& rayDir, @@ -222,20 +195,18 @@ namespace AZ float& t1, float& t2); - /** - * If there is only one intersecting point, the coefficient is stored in \ref t1. - * @param rayOrigin The origin of the ray to test. - * @param rayDir The direction of the ray to test. It has to be unit length. - * @param coneApex The apex of the cone. - * @param coneDir The unit-length direction from the apex to the base. - * @param coneHeight The height of the cone, from the apex to the base. - * @param coneBaseRadius The radius of the cone base circle. - * @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - * as "rayOrigin + t1 * rayDir". - * @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - * as "rayOrigin + t2 * rayDir". - * @return The number of intersecting points. - **/ + //! If there is only one intersecting point, the coefficient is stored in \ref t1. + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param coneApex The apex of the cone. + //! @param coneDir The unit-length direction from the apex to the base. + //! @param coneHeight The height of the cone, from the apex to the base. + //! @param coneBaseRadius The radius of the cone base circle. + //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + //! as "rayOrigin + t1 * rayDir". + //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated + //! as "rayOrigin + t2 * rayDir". + //! @return The number of intersecting points. int IntersectRayCone( const Vector3& rayOrigin, const Vector3& rayDir, @@ -246,16 +217,13 @@ namespace AZ float& t1, float& t2); - /** - * Test intersection between a ray and a plane in 3D. - * @param rayOrigin The origin of the ray to test intersection with. - * @param rayDir The direction of the ray to test intersection with. - * @param planePos A point on the plane to test intersection with. - * @param planeNormal The normal of the plane to test intersection with. - * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin - *+ t * rayDirection". - * @return The number of intersection point. - **/ + //! Test intersection between a ray and a plane in 3D. + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param planePos A point on the plane to test intersection with. + //! @param planeNormal The normal of the plane to test intersection with. + //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @return The number of intersection point. int IntersectRayPlane( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& planePos, const Vector3& planeNormal, float& t); @@ -268,8 +236,7 @@ namespace AZ //! @param vertexB One of the four points that define the quadrilateral. //! @param vertexC One of the four points that define the quadrilateral. //! @param vertexD One of the four points that define the quadrilateral. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + - //! t * rayDirection". + //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". //! @return The number of intersection point. int IntersectRayQuad( const Vector3& rayOrigin, @@ -280,20 +247,19 @@ namespace AZ const Vector3& vertexD, float& t); - /** Test intersection between a ray and an oriented box in 3D. - * @param rayOrigin The origin of the ray to test intersection with. - * @param rayDir The direction of the ray to test intersection with. - * @param boxCenter The position of the center of the box. - * @param boxAxis1 An axis along one dimension of the oriented box. - * @param boxAxis2 An axis along one dimension of the oriented box. - * @param boxAxis3 An axis along one dimension of the oriented box. - * @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. - * @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. - * @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. - * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + - * t * rayDirection". - * @return 1 if there is an intersection, 0 otherwise. - **/ + //! Test intersection between a ray and an oriented box in 3D. + //! + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param boxCenter The position of the center of the box. + //! @param boxAxis1 An axis along one dimension of the oriented box. + //! @param boxAxis2 An axis along one dimension of the oriented box. + //! @param boxAxis3 An axis along one dimension of the oriented box. + //! @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. + //! @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. + //! @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. + //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @return 1 if there is an intersection, 0 otherwise. int IntersectRayBox( const Vector3& rayOrigin, const Vector3& rayDir, @@ -306,15 +272,14 @@ namespace AZ float boxHalfExtent3, float& t); - /** - * Test intersection between a ray and an OBB. - * @param rayOrigin The origin of the ray to test intersection with. - * @param rayDir The direction of the ray to test intersection with. - * @param obb The OBB to test for intersection with the ray. - * @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * - * rayDirection". - * @return 1 if there is an intersection, 0 otherwise. - */ + //! Test intersection between a ray and an OBB. + //! + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param obb The OBB to test for intersection with the ray. + //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * + //! rayDirection". + //! @return 1 if there is an intersection, 0 otherwise. int IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t); //! Ray cylinder intersection types. @@ -327,18 +292,16 @@ namespace AZ RR_ISECT_RAY_CYL_Q_SIDE, // on the Q side }; - /** - * Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder - * Intersect segment S(t)=sa+t(dir), 0<=t<=1 against cylinder specified by p, q and r. - * - * @param sa point - * @param dir magnitude along sa - * @param p center point of side 1 cylinder - * @param q center point of side 2 cylinder - * @param r radius of cylinder - * @param t[out] proporition along line semgnet - * @return CylinderIsectTypes - */ + //! Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder + //! Intersect segment S(t)=sa+t(dir), 0<=t<=1 against cylinder specified by p, q and r. + //! + //! @param sa point + //! @param dir magnitude along sa + //! @param p center point of side 1 cylinder + //! @param q center point of side 2 cylinder + //! @param r radius of cylinder + //! @param t[out] proporition along line semgnet + //! @return CylinderIsectTypes CylinderIsectTypes IntersectSegmentCylinder( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); @@ -352,19 +315,16 @@ namespace AZ ISECT_RAY_CAPSULE_Q_SIDE, // on the Q side }; - /** - * This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder - * segment sphere intersection. We can optimize it a lot once we fix the ray - * cylinder intersection. - */ + //! This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder + //! segment sphere intersection. We can optimize it a lot once we fix the ray + //! cylinder intersection. + //! CapsuleIsectTypes IntersectSegmentCapsule( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); - /** - * Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified - * by the n halfspaces defined by the planes p[]. On exit tfirst and tlast - * define the intersection, if any. - */ + //! Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified + //! by the n halfspaces defined by the planes p[]. On exit tfirst and tlast + //! define the intersection, if any. bool IntersectSegmentPolyhedron( const Vector3& sa, const Vector3& sBA, @@ -375,22 +335,20 @@ namespace AZ int& iFirstPlane, int& iLastPlane); - /** - * Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between - * two segments segment1Start<->segment1End and segment2Start<->segment2End. Also calculate the values of segment1Proportion and - * segment2Proportion where closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) - * closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) - * If segments are parallel returns a solution. - * @param segment1Start start of segment 1. - * @param segment1End end of segment 1. - * @param segment2Start start of segment 2. - * @param segment2End end of segment 2. - * @param segment1Proportion[out] the proporition along segment 1 [0..1] - * @param segment2Proportion[out] the proporition along segment 2 [0..1] - * @param closestPointSegment1[out] closest point on segment 1. - * @param closestPointSegment2[out] closest point on segment 2. - * @param epsilon the minimum square distance where a line segment can be treated as a single point. - */ + //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between + //! two segments segment1Start<->segment1End and segment2Start<->segment2End. Also calculate the values of segment1Proportion and + //! segment2Proportion where closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) + //! closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) + //! If segments are parallel returns a solution. + //! @param segment1Start start of segment 1. + //! @param segment1End end of segment 1. + //! @param segment2Start start of segment 2. + //! @param segment2End end of segment 2. + //! @param segment1Proportion[out] the proporition along segment 1 [0..1] + //! @param segment2Proportion[out] the proporition along segment 2 [0..1] + //! @param closestPointSegment1[out] closest point on segment 1. + //! @param closestPointSegment2[out] closest point on segment 2. + //! @param epsilon the minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, const Vector3& segment1End, @@ -402,19 +360,17 @@ namespace AZ Vector3& closestPointSegment2, float epsilon = 1e-4f); - /** - * Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between - * two segments segment1Start<->segment1End and segment2Start<->segment2End. - * If segments are parallel returns a solution. - * - * @param segment1Start start of segment 1. - * @param segment1End end of segment 1. - * @param segment2Start start of segment 2. - * @param segment2End end of segment 2. - * @param closestPointSegment1[out] closest point on segment 1. - * @param closestPointSegment2[out] closest point on segment 2. - * @param epsilon the minimum square distance where a line segment can be treated as a single point. - */ + //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between + //! two segments segment1Start<->segment1End and segment2Start<->segment2End. + //! If segments are parallel returns a solution. + //! + //! @param segment1Start start of segment 1. + //! @param segment1End end of segment 1. + //! @param segment2Start start of segment 2. + //! @param segment2End end of segment 2. + //! @param closestPointSegment1[out] closest point on segment 1. + //! @param closestPointSegment2[out] closest point on segment 2. + //! @param epsilon the minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, const Vector3& segment1End, @@ -424,17 +380,15 @@ namespace AZ Vector3& closestPointSegment2, float epsilon = 1e-4f); - /** - * Calculate the point (closestPointOnSegment) that is the closest point on - * segment segmentStart/segmentEnd to point. Also calculate the value of proportion where - * closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) - * - * @param point the point to test - * @param segmentStart the start of the segment - * @param segmentEnd the end of the segment - * @param proportion[out] the proportion of the segment L(t) = (end - start) * t - * @param closestPointOnSegment[out] the point along the line segment - */ + //! Calculate the point (closestPointOnSegment) that is the closest point on + //! segment segmentStart/segmentEnd to point. Also calculate the value of proportion where + //! closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) + //! + //! @param point the point to test + //! @param segmentStart the start of the segment + //! @param segmentEnd the end of the segment + //! @param proportion[out] the proportion of the segment L(t) = (end - start) * t + //! @param closestPointOnSegment[out] the point along the line segment void ClosestPointSegment( const Vector3& point, const Vector3& segmentStart, diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl index b9f5139923..b570b6a182 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.inl @@ -5,7 +5,6 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#pragma once namespace AZ { From 7af448c9b72aed8402e92822e403be57ddca4b0a Mon Sep 17 00:00:00 2001 From: Mikhail Naumov Date: Mon, 11 Oct 2021 20:15:56 -0500 Subject: [PATCH 18/52] PR feedback Signed-off-by: Mikhail Naumov --- .../AzFramework/Spawnable/SpawnableSystemComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp index af41fdd6ba..957786c6df 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableSystemComponent.cpp @@ -166,6 +166,8 @@ namespace AzFramework void SpawnableSystemComponent::Deactivate() { + ProcessSpawnableQueue(); + m_registryChangeHandler.Disconnect(); AZ::TickBus::Handler::BusDisconnect(); From 02d8596d875614316a720820e12db38e02661cfe Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Mon, 11 Oct 2021 20:24:41 -0700 Subject: [PATCH 19/52] chore: improject documentation for IntersectSegment - change return of IntersectRayDisk to bool - change return of IntersectRayBox to bool - move [out] after @param Signed-off-by: Michael Pollind --- .../AzCore/AzCore/Math/IntersectSegment.cpp | 31 ++- .../AzCore/AzCore/Math/IntersectSegment.h | 217 +++++++++--------- 2 files changed, 124 insertions(+), 124 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp index 2a00412689..1bf1e41cb7 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp @@ -352,9 +352,6 @@ AZ::Intersect::IntersectRayAABB( return ISECT_RAY_AABB_ISECT; } - - - //========================================================================= // IntersectRayAABB2 // [2/18/2011] @@ -411,7 +408,7 @@ AZ::Intersect::IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, return ISECT_RAY_AABB_ISECT; } -int AZ::Intersect::IntersectRayDisk( +bool AZ::Intersect::IntersectRayDisk( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& diskCenter, const float diskRadius, const Vector3& diskNormal, float& t) { // First intersect with the plane of the disk @@ -424,10 +421,10 @@ int AZ::Intersect::IntersectRayDisk( if (pointOnPlane.GetDistance(diskCenter) < diskRadius) { t = planeIntersectionDistance; - return 1; + return true; } } - return 0; + return false; } // Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder, and the book's errata. @@ -1015,7 +1012,7 @@ int AZ::Intersect::IntersectRayQuad( } // reference: Real-Time Collision Detection, 5.3.3 Intersecting Ray or Segment Against Box -int AZ::Intersect::IntersectRayBox( +bool AZ::Intersect::IntersectRayBox( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& boxCenter, const Vector3& boxAxis1, const Vector3& boxAxis2, const Vector3& boxAxis3, float boxHalfExtent1, float boxHalfExtent2, float boxHalfExtent3, float& t) { @@ -1047,7 +1044,7 @@ int AZ::Intersect::IntersectRayBox( // If the ray is parallel to the slab and the ray origin is outside, return no intersection. if (tp < 0.0f || tn < 0.0f) { - return 0; + return false; } } else @@ -1068,7 +1065,7 @@ int AZ::Intersect::IntersectRayBox( tmax = AZ::GetMin(tmax, t2); if (tmin > tmax) { - return 0; + return false; } } @@ -1088,7 +1085,7 @@ int AZ::Intersect::IntersectRayBox( // If the ray is parallel to the slab and the ray origin is outside, return no intersection. if (tp < 0.0f || tn < 0.0f) { - return 0; + return false; } } else @@ -1109,7 +1106,7 @@ int AZ::Intersect::IntersectRayBox( tmax = AZ::GetMin(tmax, t2); if (tmin > tmax) { - return 0; + return false; } } @@ -1129,7 +1126,7 @@ int AZ::Intersect::IntersectRayBox( // If the ray is parallel to the slab and the ray origin is outside, return no intersection. if (tp < 0.0f || tn < 0.0f) { - return 0; + return false; } } else @@ -1150,15 +1147,15 @@ int AZ::Intersect::IntersectRayBox( tmax = AZ::GetMin(tmax, t2); if (tmin > tmax) { - return 0; + return false; } } t = (isRayOriginInsideBox ? tmax : tmin); - return 1; + return true; } -int AZ::Intersect::IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t) +bool AZ::Intersect::IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t) { return AZ::Intersect::IntersectRayBox(rayOrigin, rayDir, obb.GetPosition(), obb.GetAxisX(), obb.GetAxisY(), obb.GetAxisZ(), @@ -1366,11 +1363,11 @@ AZ::Intersect::IntersectSegmentCapsule(const Vector3& sa, const Vector3& dir, co //========================================================================= bool AZ::Intersect::IntersectSegmentPolyhedron( - const Vector3& sa, const Vector3& sBA, const Plane p[], int numPlanes, + const Vector3& sa, const Vector3& dir, const Plane p[], int numPlanes, float& tfirst, float& tlast, int& iFirstPlane, int& iLastPlane) { // Compute direction vector for the segment - Vector3 d = /*b - a*/ sBA; + Vector3 d = /*b - a*/ dir; // Set initial interval to being the whole segment. For a ray, tlast should be // set to +RR_FLT_MAX. For a line, additionally tfirst should be set to -RR_FLT_MAX tfirst = 0.0f; diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h index ecb0d7acc9..71c39fb53d 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h @@ -28,15 +28,14 @@ namespace AZ //! LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). //! @param s1 segment start point //! @param s2 segment end point - //! @param p point to find the closest time to. - //! @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + //! @param p point to find the closest time to. + //! @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] //! @return the closest point Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u); //! Given segment pq and triangle abc (CCW), returns whether segment intersects //! triangle and if so, also returns the barycentric coordinates (u,v,w) //! of the intersection point. - //! //! @param p segment start point //! @param q segment end point //! @param a triangle point 1 @@ -49,7 +48,7 @@ namespace AZ const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); //! Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). - //! //! @param p segment start point + //! @param p segment start point //! @param q segment end point //! @param a triangle point 1 //! @param b triangle point 2 @@ -86,41 +85,38 @@ namespace AZ const Aabb& aabb, float& tStart, float& tEnd, - Vector3& startNormal /*, Vector3& inter*/); + Vector3& startNormal); //! Intersect ray against AABB. - //! //! @param rayStart ray starting point. //! @param dir ray reciprocal direction. //! @param aabb Axis aligned bounding box to intersect against. //! @param start length on ray of the first intersection. //! @param end length of the of the second intersection. - //! @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and ISECT_RAY_AABB_ISECT. You can check yourself for that case. + //! @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and + //! ISECT_RAY_AABB_ISECT. You can check yourself for that case. RayAABBIsectTypes IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, float& start, float& end); //! Clip a ray to an aabb. return true if ray was clipped. The ray //! can be inside so don't use the result if the ray intersect the box. - //! //! @param aabb bounds //! @param rayStart the start of the ray //! @param rayEnd the end of the ray - //! @param tClipStart[out] The proportion where the ray enterts the aabb - //! @param tClipEnd[out] The proportion where the ray exits the aabb + //! @param[out] tClipStart The proportion where the ray enterts the aabb + //! @param[out] tClipEnd The proportion where the ray exits the aabb //! @return true ray was clipped else false bool ClipRayWithAabb(const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd); //! Test segment and aabb where the segment is defined by midpoint //! midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. //! the aabb is at the origin and defined by half extents only. - //! //! @param midPoint midpoint of a line segment //! @param halfVector half vector of an aabb //! @param aabbExtends the extends of a bounded box - //! @return 1 if the intersect, otherwise 0. + //! @return true if the intersect, otherwise false. bool TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends); //! Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin - //! //! @param p0 point 1 //! @param p1 point 2 //! @param aabb bounded box @@ -130,9 +126,9 @@ namespace AZ //! Ray sphere intersection result types. enum SphereIsectTypes : AZ::s32 { - ISECT_RAY_SPHERE_SA_INSIDE = -1, // the ray starts inside the cylinder - ISECT_RAY_SPHERE_NONE, // no intersection - ISECT_RAY_SPHERE_ISECT, // along the PQ segment + ISECT_RAY_SPHERE_SA_INSIDE = -1, //!< the ray starts inside the cylinder + ISECT_RAY_SPHERE_NONE, //!< no intersection + ISECT_RAY_SPHERE_ISECT, //!< along the PQ segment }; //! IntersectRaySphereOrigin @@ -147,25 +143,26 @@ namespace AZ const Vector3& rayStart, const Vector3& rayDirNormalized, const float sphereRadius, float& t); //! Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin - //! - //! @param rayStart - //! @param rayDirNormalized - //! @param sphereCenter - //! @param sphereRadius - //! @param t - //! @return SphereIsectTypes + //! @param rayStart the start of the ray + //! @param rayDirNormalized the direction of the ray normalized + //! @param sphereCenter the center of the sphere + //! @param sphereRadius radius of the sphere + //! @param[out] t coefficient in the ray's explicit equation from which an + //! intersecting point is calculated as "rayOrigin + t1 * rayDir". + //! @return SphereIsectTypes SphereIsectTypes IntersectRaySphere( const Vector3& rayStart, const Vector3& rayDirNormalized, const Vector3& sphereCenter, const float sphereRadius, float& t); - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param diskCenter Center point of the disk - //! @param diskRadius Radius of the disk - //! @param diskNormal A normal perpendicular to the disk - //! @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir + //! Intersect ray (rayStarty, rayDirNormalized) and disk (center, radius, normal) + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param diskCenter Center point of the disk + //! @param diskRadius Radius of the disk + //! @param diskNormal A normal perpendicular to the disk + //! @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir //! that the hit occured at. - //! @return The number of intersecting points. - int IntersectRayDisk( + //! @return false if not interesecting and true if intersecting + bool IntersectRayDisk( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& diskCenter, @@ -174,17 +171,14 @@ namespace AZ float& t); //! If there is only one intersecting point, the coefficient is stored in \ref t1. - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param cylinderEnd1 The center of the circle on one end of the cylinder. - //! @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit - //! length. - //! @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. - //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - //! as "rayOrigin + t1 * rayDir". - //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - //! as "rayOrigin + t2 * rayDir". - //! @return The number of intersecting points. + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param cylinderEnd1 The center of the circle on one end of the cylinder. + //! @param cylinderDir The direction pointing from \ref cylinderEnd1 to the other end of the cylinder. It has to be unit length. + //! @param cylinderHeight The distance between two centers of the circles on two ends of the cylinder respectively. + //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t1 * rayDir". + //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t2 * rayDir". + //! @return The number of intersecting points. int IntersectRayCappedCylinder( const Vector3& rayOrigin, const Vector3& rayDir, @@ -196,17 +190,15 @@ namespace AZ float& t2); //! If there is only one intersecting point, the coefficient is stored in \ref t1. - //! @param rayOrigin The origin of the ray to test. - //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param coneApex The apex of the cone. - //! @param coneDir The unit-length direction from the apex to the base. - //! @param coneHeight The height of the cone, from the apex to the base. - //! @param coneBaseRadius The radius of the cone base circle. - //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - //! as "rayOrigin + t1 * rayDir". - //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated - //! as "rayOrigin + t2 * rayDir". - //! @return The number of intersecting points. + //! @param rayOrigin The origin of the ray to test. + //! @param rayDir The direction of the ray to test. It has to be unit length. + //! @param coneApex The apex of the cone. + //! @param coneDir The unit-length direction from the apex to the base. + //! @param coneHeight The height of the cone, from the apex to the base. + //! @param coneBaseRadius The radius of the cone base circle. + //! @param[out] t1 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t1 * rayDir". + //! @param[out] t2 A possible coefficient in the ray's explicit equation from which an intersecting point is calculated as "rayOrigin + t2 * rayDir". + //! @return The number of intersecting points. int IntersectRayCone( const Vector3& rayOrigin, const Vector3& rayDir, @@ -218,11 +210,11 @@ namespace AZ float& t2); //! Test intersection between a ray and a plane in 3D. - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param planePos A point on the plane to test intersection with. - //! @param planeNormal The normal of the plane to test intersection with. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param planePos A point on the plane to test intersection with. + //! @param planeNormal The normal of the plane to test intersection with. + //! @param[out] t The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". //! @return The number of intersection point. int IntersectRayPlane( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& planePos, const Vector3& planeNormal, float& t); @@ -230,13 +222,14 @@ namespace AZ //! Test intersection between a ray and a two-sided quadrilateral defined by four points in 3D. //! The four points that define the quadrilateral could be passed in with either counter clock-wise //! winding or clock-wise winding. - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param vertexA One of the four points that define the quadrilateral. - //! @param vertexB One of the four points that define the quadrilateral. - //! @param vertexC One of the four points that define the quadrilateral. - //! @param vertexD One of the four points that define the quadrilateral. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param vertexA One of the four points that define the quadrilateral. + //! @param vertexB One of the four points that define the quadrilateral. + //! @param vertexC One of the four points that define the quadrilateral. + //! @param vertexD One of the four points that define the quadrilateral. + //! @param[out] t The coefficient in the ray's explicit equation from which the + //! intersecting point is calculated as "rayOrigin + t * rayDirection". //! @return The number of intersection point. int IntersectRayQuad( const Vector3& rayOrigin, @@ -248,19 +241,18 @@ namespace AZ float& t); //! Test intersection between a ray and an oriented box in 3D. - //! - //! @param rayOrigin The origin of the ray to test intersection with. - //! @param rayDir The direction of the ray to test intersection with. - //! @param boxCenter The position of the center of the box. - //! @param boxAxis1 An axis along one dimension of the oriented box. - //! @param boxAxis2 An axis along one dimension of the oriented box. - //! @param boxAxis3 An axis along one dimension of the oriented box. - //! @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. - //! @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. - //! @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return 1 if there is an intersection, 0 otherwise. - int IntersectRayBox( + //! @param rayOrigin The origin of the ray to test intersection with. + //! @param rayDir The direction of the ray to test intersection with. + //! @param boxCenter The position of the center of the box. + //! @param boxAxis1 An axis along one dimension of the oriented box. + //! @param boxAxis2 An axis along one dimension of the oriented box. + //! @param boxAxis3 An axis along one dimension of the oriented box. + //! @param boxHalfExtent1 The half extent of the box on the dimension of \ref boxAxis1. + //! @param boxHalfExtent2 The half extent of the box on the dimension of \ref boxAxis2. + //! @param boxHalfExtent3 The half extent of the box on the dimension of \ref boxAxis3. + //! @param[out] t The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @return true if there is an intersection, false otherwise. + bool IntersectRayBox( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& boxCenter, @@ -273,23 +265,21 @@ namespace AZ float& t); //! Test intersection between a ray and an OBB. - //! //! @param rayOrigin The origin of the ray to test intersection with. //! @param rayDir The direction of the ray to test intersection with. //! @param obb The OBB to test for intersection with the ray. - //! @param t[out] The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * - //! rayDirection". - //! @return 1 if there is an intersection, 0 otherwise. - int IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t); + //! @param[out] t The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". + //! @return true if there is an intersection, false otherwise. + bool IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t); //! Ray cylinder intersection types. enum CylinderIsectTypes : AZ::s32 { - RR_ISECT_RAY_CYL_SA_INSIDE = -1, // the ray starts inside the cylinder - RR_ISECT_RAY_CYL_NONE, // no intersection - RR_ISECT_RAY_CYL_PQ, // along the PQ segment - RR_ISECT_RAY_CYL_P_SIDE, // on the P side - RR_ISECT_RAY_CYL_Q_SIDE, // on the Q side + RR_ISECT_RAY_CYL_SA_INSIDE = -1, //!< the ray starts inside the cylinder + RR_ISECT_RAY_CYL_NONE, //!< no intersection + RR_ISECT_RAY_CYL_PQ, //!< along the PQ segment + RR_ISECT_RAY_CYL_P_SIDE, //!< on the P side + RR_ISECT_RAY_CYL_Q_SIDE, //!< on the Q side }; //! Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder @@ -300,7 +290,7 @@ namespace AZ //! @param p center point of side 1 cylinder //! @param q center point of side 2 cylinder //! @param r radius of cylinder - //! @param t[out] proporition along line semgnet + //! @param[out] t proporition along line segment //! @return CylinderIsectTypes CylinderIsectTypes IntersectSegmentCylinder( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); @@ -308,26 +298,41 @@ namespace AZ //! Capsule ray intersect types. enum CapsuleIsectTypes { - ISECT_RAY_CAPSULE_SA_INSIDE = -1, // the ray starts inside the cylinder - ISECT_RAY_CAPSULE_NONE, // no intersection - ISECT_RAY_CAPSULE_PQ, // along the PQ segment - ISECT_RAY_CAPSULE_P_SIDE, // on the P side - ISECT_RAY_CAPSULE_Q_SIDE, // on the Q side + ISECT_RAY_CAPSULE_SA_INSIDE = -1, //!< the ray starts inside the cylinder + ISECT_RAY_CAPSULE_NONE, //!< no intersection + ISECT_RAY_CAPSULE_PQ, //!< along the PQ segment + ISECT_RAY_CAPSULE_P_SIDE, //!< on the P side + ISECT_RAY_CAPSULE_Q_SIDE, //!< on the Q side }; //! This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder //! segment sphere intersection. We can optimize it a lot once we fix the ray //! cylinder intersection. - //! + //! @param sa the beginning of the line segment + //! @param dir the direction and length of the segment + //! @param p center point of side 1 capsule + //! @param q center point of side 1 capsule + //! @param r the radius of the capsule + //! @param[out] t proporition along line segment + //! @return CapsuleIsectTypes CapsuleIsectTypes IntersectSegmentCapsule( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); //! Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified //! by the n halfspaces defined by the planes p[]. On exit tfirst and tlast //! define the intersection, if any. + //! @param sa the beggining of the line segment + //! @param dir the direction and length of the segment + //! @param p planes that compose a convex ponvex polyhedron + //! @param numPlanes number of planes + //! @param[out] tfirst proportion along the line segment where the line enters + //! @param[out] tlast proportion along the line segment where the line exits + //! @param[out] iFirstPlane the plane where the line enters + //! @param[out] iLastPlane the plane where the line exits + //! @return true if intersects else false bool IntersectSegmentPolyhedron( const Vector3& sa, - const Vector3& sBA, + const Vector3& dir, const Plane p[], int numPlanes, float& tfirst, @@ -335,7 +340,7 @@ namespace AZ int& iFirstPlane, int& iLastPlane); - //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between + //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between //! two segments segment1Start<->segment1End and segment2Start<->segment2End. Also calculate the values of segment1Proportion and //! segment2Proportion where closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) //! closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) @@ -344,10 +349,10 @@ namespace AZ //! @param segment1End end of segment 1. //! @param segment2Start start of segment 2. //! @param segment2End end of segment 2. - //! @param segment1Proportion[out] the proporition along segment 1 [0..1] - //! @param segment2Proportion[out] the proporition along segment 2 [0..1] - //! @param closestPointSegment1[out] closest point on segment 1. - //! @param closestPointSegment2[out] closest point on segment 2. + //! @param[out] segment1Proportion the proporition along segment 1 [0..1] + //! @param[out] segment2Proportion the proporition along segment 2 [0..1] + //! @param[out] closestPointSegment1 closest point on segment 1. + //! @param[out] closestPointSegment2 closest point on segment 2. //! @param epsilon the minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, @@ -363,13 +368,12 @@ namespace AZ //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between //! two segments segment1Start<->segment1End and segment2Start<->segment2End. //! If segments are parallel returns a solution. - //! //! @param segment1Start start of segment 1. //! @param segment1End end of segment 1. //! @param segment2Start start of segment 2. //! @param segment2End end of segment 2. - //! @param closestPointSegment1[out] closest point on segment 1. - //! @param closestPointSegment2[out] closest point on segment 2. + //! @param[out] closestPointSegment1 closest point on segment 1. + //! @param[out] closestPointSegment2 closest point on segment 2. //! @param epsilon the minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, @@ -383,12 +387,11 @@ namespace AZ //! Calculate the point (closestPointOnSegment) that is the closest point on //! segment segmentStart/segmentEnd to point. Also calculate the value of proportion where //! closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) - //! //! @param point the point to test //! @param segmentStart the start of the segment //! @param segmentEnd the end of the segment - //! @param proportion[out] the proportion of the segment L(t) = (end - start) * t - //! @param closestPointOnSegment[out] the point along the line segment + //! @param[out] proportion the proportion of the segment L(t) = (end - start) * t + //! @param[out] closestPointOnSegment the point along the line segment void ClosestPointSegment( const Vector3& point, const Vector3& segmentStart, From 36e201a1be032b5777b4b9a5d0ef148d76672753 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Tue, 12 Oct 2021 11:22:53 -0500 Subject: [PATCH 20/52] Update PropertyAssetCtrl and ThumbnailPropertyCtrl to support custom images Signed-off-by: Guthrie Adams --- .../UI/PropertyEditor/PropertyAssetCtrl.cpp | 57 +++++++- .../UI/PropertyEditor/PropertyAssetCtrl.hxx | 5 + .../PropertyEditor/ThumbnailPropertyCtrl.cpp | 131 +++++++++++------- .../UI/PropertyEditor/ThumbnailPropertyCtrl.h | 25 +++- 4 files changed, 161 insertions(+), 57 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index ba84e662c1..7f3b9e61fd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -28,6 +28,9 @@ AZ_PUSH_DISABLE_WARNING(4244 4251, "-Wunknown-warning-option") #include #include #include +#include +#include +#include AZ_POP_DISABLE_WARNING #include @@ -1230,6 +1233,16 @@ namespace AzToolsFramework return m_showThumbnailDropDownButton; } + void PropertyAssetCtrl::SetCustomThumbnailEnabled(bool enabled) + { + m_thumbnail->SetCustomThumbnailEnabled(enabled); + } + + void PropertyAssetCtrl::SetCustomThumbnailPixmap(const QPixmap& pixmap) + { + m_thumbnail->SetCustomThumbnailPixmap(pixmap); + } + void PropertyAssetCtrl::SetThumbnailCallback(EditCallbackType* editNotifyCallback) { m_thumbnailCallback = editNotifyCallback; @@ -1356,15 +1369,27 @@ namespace AzToolsFramework GUI->SetClearNotifyCallback(nullptr); } } - else if (attrib == AZ_CRC("BrowseIcon", 0x507d7a4f)) + else if (attrib == AZ_CRC_CE("BrowseIcon")) { AZStd::string iconPath; - attrValue->Read(iconPath); - - if (!iconPath.empty()) + if (attrValue->Read(iconPath) && !iconPath.empty()) { GUI->SetBrowseButtonIcon(QIcon(iconPath.c_str())); } + else + { + // A QPixmap object can't be assigned directly via an attribute. + // This allows dynamic icon data to be supplied as a buffer containing a serialized QPixmap. + AZStd::vector pixmapBuffer; + if (attrValue->Read>(pixmapBuffer) && !pixmapBuffer.empty()) + { + QByteArray pixmapBytes(pixmapBuffer.data(), aznumeric_cast(pixmapBuffer.size())); + QDataStream stream(&pixmapBytes, QIODevice::ReadOnly); + QPixmap pixmap; + stream >> pixmap; + GUI->SetBrowseButtonIcon(pixmap); + } + } } else if (attrib == AZ_CRC_CE("BrowseButtonEnabled")) { @@ -1390,6 +1415,30 @@ namespace AzToolsFramework GUI->SetShowThumbnail(showThumbnail); } } + else if (attrib == AZ_CRC_CE("ThumbnailIcon")) + { + AZStd::string iconPath; + if (attrValue->Read(iconPath) && !iconPath.empty()) + { + GUI->SetCustomThumbnailEnabled(true); + GUI->SetCustomThumbnailPixmap(QPixmap::fromImage(QImage(iconPath.c_str()))); + } + else + { + // A QPixmap object can't be assigned directly via an attribute. + // This allows dynamic icon data to be supplied as a buffer containing a serialized QPixmap. + AZStd::vector pixmapBuffer; + if (attrValue->Read>(pixmapBuffer) && !pixmapBuffer.empty()) + { + QByteArray pixmapBytes(pixmapBuffer.data(), aznumeric_cast(pixmapBuffer.size())); + QDataStream stream(&pixmapBytes, QIODevice::ReadOnly); + QPixmap pixmap; + stream >> pixmap; + GUI->SetCustomThumbnailEnabled(true); + GUI->SetCustomThumbnailPixmap(pixmap); + } + } + } else if (attrib == AZ_CRC_CE("ThumbnailCallback")) { PropertyAssetCtrl::EditCallbackType* func = azdynamic_cast(attrValue->GetAttribute()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx index cc4aff5649..0b98278bc5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx @@ -217,12 +217,17 @@ namespace AzToolsFramework void SetHideProductFilesInAssetPicker(bool hide); bool GetHideProductFilesInAssetPicker() const; + // Enable and configure a thumbnail widget that displays an asset preview and dropdown arrow for a dropdown menu void SetShowThumbnail(bool enable); bool GetShowThumbnail() const; void SetShowThumbnailDropDownButton(bool enable); bool GetShowThumbnailDropDownButton() const; void SetThumbnailCallback(EditCallbackType* editNotifyCallback); + // If enabled, replaces the thumbnail widget content with a custom pixmap + void SetCustomThumbnailEnabled(bool enabled); + void SetCustomThumbnailPixmap(const QPixmap& pixmap); + void SetSelectedAssetID(const AZ::Data::AssetId& newID); void SetCurrentAssetType(const AZ::Data::AssetType& newType); void SetSelectedAssetID(const AZ::Data::AssetId& newID, const AZ::Data::AssetType& newType); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.cpp index c458f7c47e..d8ddee6b76 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.cpp @@ -7,75 +7,117 @@ */ #include -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // 4251: 'QRawFont::d': class 'QExplicitlySharedDataPointer' needs to have dll-interface to be used by clients of class 'QRawFont' - // 4800: 'QTextEngine *const ': forcing value to bool 'true' or 'false' (performance warning) -#include -#include -#include -#include -#include -#include + +// 4251: 'QRawFont::d': class 'QExplicitlySharedDataPointer' needs to have dll-interface to be used by clients of class +// 'QRawFont' 4800: 'QTextEngine *const ': forcing value to bool 'true' or 'false' (performance warning) +AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") #include +#include +#include +#include +#include +#include +#include AZ_POP_DISABLE_WARNING #include "ThumbnailPropertyCtrl.h" namespace AzToolsFramework { - ThumbnailPropertyCtrl::ThumbnailPropertyCtrl(QWidget* parent) : QWidget(parent) { - QHBoxLayout* pLayout = new QHBoxLayout(); - pLayout->setContentsMargins(0, 0, 0, 0); - pLayout->setSpacing(0); - m_thumbnail = new Thumbnailer::ThumbnailWidget(this); m_thumbnail->setFixedSize(QSize(24, 24)); + m_thumbnailEnlarged = new Thumbnailer::ThumbnailWidget(this); + m_thumbnailEnlarged->setFixedSize(QSize(180, 180)); + m_thumbnailEnlarged->setWindowFlags(Qt::Window | Qt::FramelessWindowHint); + + m_customThumbnail = new QLabel(this); + m_customThumbnail->setFixedSize(QSize(24, 24)); + m_customThumbnail->setScaledContents(true); + + m_customThumbnailEnlarged = new QLabel(this); + m_customThumbnailEnlarged->setFixedSize(QSize(180, 180)); + m_customThumbnailEnlarged->setWindowFlags(Qt::Window | Qt::FramelessWindowHint); + m_customThumbnailEnlarged->setScaledContents(true); + m_dropDownArrow = new AspectRatioAwarePixmapWidget(this); m_dropDownArrow->setPixmap(QPixmap(":/stylesheet/img/triangle0.png")); m_dropDownArrow->setFixedSize(QSize(8, 24)); - ShowDropDownArrow(false); m_emptyThumbnail = new QLabel(this); m_emptyThumbnail->setPixmap(QPixmap(":/stylesheet/img/line.png")); m_emptyThumbnail->setFixedSize(QSize(24, 24)); - pLayout->addWidget(m_emptyThumbnail); + QHBoxLayout* pLayout = new QHBoxLayout(); + pLayout->setContentsMargins(0, 0, 0, 0); + pLayout->setSpacing(0); pLayout->addWidget(m_thumbnail); + pLayout->addWidget(m_customThumbnail); + pLayout->addWidget(m_emptyThumbnail); pLayout->addSpacing(4); pLayout->addWidget(m_dropDownArrow); pLayout->addSpacing(4); - setLayout(pLayout); + + ShowDropDownArrow(false); + UpdateVisibility(); } void ThumbnailPropertyCtrl::SetThumbnailKey(Thumbnailer::SharedThumbnailKey key, const char* contextName) { - m_key = key; - m_emptyThumbnail->setVisible(false); - m_thumbnail->SetThumbnailKey(key, contextName); + if (m_customThumbnailEnabled) + { + ClearThumbnail(); + } + else + { + m_key = key; + m_thumbnail->SetThumbnailKey(m_key, contextName); + m_thumbnailEnlarged->SetThumbnailKey(m_key, contextName); + } + UpdateVisibility(); } void ThumbnailPropertyCtrl::ClearThumbnail() { - m_emptyThumbnail->setVisible(true); + m_key.clear(); m_thumbnail->ClearThumbnail(); + m_thumbnailEnlarged->ClearThumbnail(); + UpdateVisibility(); } void ThumbnailPropertyCtrl::ShowDropDownArrow(bool visible) { - if (visible) - { - setFixedSize(QSize(40, 24)); - } - else - { - setFixedSize(QSize(24, 24)); - } + setFixedSize(QSize(visible ? 40 : 24, 24)); m_dropDownArrow->setVisible(visible); } + void ThumbnailPropertyCtrl::SetCustomThumbnailEnabled(bool enabled) + { + m_customThumbnailEnabled = enabled; + UpdateVisibility(); + } + + void ThumbnailPropertyCtrl::SetCustomThumbnailPixmap(const QPixmap& pixmap) + { + m_customThumbnail->setPixmap(pixmap); + m_customThumbnailEnlarged->setPixmap(pixmap); + UpdateVisibility(); + } + + void ThumbnailPropertyCtrl::UpdateVisibility() + { + m_thumbnail->setVisible(m_key && !m_customThumbnailEnabled); + m_thumbnailEnlarged->setVisible(false); + + m_customThumbnail->setVisible(m_customThumbnailEnabled); + m_customThumbnailEnlarged->setVisible(false); + + m_emptyThumbnail->setVisible(!m_key && !m_customThumbnailEnabled); + } + bool ThumbnailPropertyCtrl::event(QEvent* e) { if (isEnabled()) @@ -83,7 +125,7 @@ namespace AzToolsFramework if (e->type() == QEvent::MouseButtonPress) { emit clicked(); - return true; //ignore + return true; // ignore } } @@ -94,37 +136,32 @@ namespace AzToolsFramework { QPainter p(this); QRect targetRect(QPoint(), QSize(40, 24)); - p.fillRect(targetRect, QColor(17, 17, 17)); // #111111 + p.fillRect(targetRect, QColor("#111111")); QWidget::paintEvent(e); } void ThumbnailPropertyCtrl::enterEvent(QEvent* e) { m_dropDownArrow->setPixmap(QPixmap(":/stylesheet/img/triangle0_highlighted.png")); - if (!m_thumbnailEnlarged && m_key) - { - QPoint position = mapToGlobal(pos() - QPoint(185, 0)); - QSize size(180, 180); - m_thumbnailEnlarged.reset(new Thumbnailer::ThumbnailWidget()); - m_thumbnailEnlarged->setFixedSize(size); - m_thumbnailEnlarged->move(position); - m_thumbnailEnlarged->setWindowFlags(Qt::Window | Qt::FramelessWindowHint); - m_thumbnailEnlarged->SetThumbnailKey(m_key); - m_thumbnailEnlarged->raise(); - m_thumbnailEnlarged->show(); - } + const QPoint offset(-m_thumbnailEnlarged->width() - 5, -m_thumbnailEnlarged->height() / 2 + m_thumbnail->height() / 2); + + m_thumbnailEnlarged->move(mapToGlobal(pos()) + offset); + m_thumbnailEnlarged->raise(); + m_thumbnailEnlarged->setVisible(m_key && !m_customThumbnailEnabled); + + m_customThumbnailEnlarged->move(mapToGlobal(pos()) + offset); + m_customThumbnailEnlarged->raise(); + m_customThumbnailEnlarged->setVisible(m_customThumbnailEnabled); QWidget::enterEvent(e); } void ThumbnailPropertyCtrl::leaveEvent(QEvent* e) { m_dropDownArrow->setPixmap(QPixmap(":/stylesheet/img/triangle0.png")); - if (m_thumbnailEnlarged) - { - m_thumbnailEnlarged.reset(); - } + m_thumbnailEnlarged->setVisible(false); + m_customThumbnailEnlarged->setVisible(false); QWidget::leaveEvent(e); } -} +} // namespace AzToolsFramework #include "UI/PropertyEditor/moc_ThumbnailPropertyCtrl.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h index 93f703c4c5..b1ce78b601 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h @@ -1,5 +1,3 @@ -#pragma once - /* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. @@ -8,6 +6,8 @@ * */ +#pragma once + #if !defined(Q_MOC_RUN) #include #include @@ -35,25 +35,38 @@ namespace AzToolsFramework //! Call this to set what thumbnail widget will display void SetThumbnailKey(Thumbnailer::SharedThumbnailKey key, const char* contextName = "Default"); + //! Remove current thumbnail void ClearThumbnail(); + //! Display a clickble dropdown arrow next to the thumbnail void ShowDropDownArrow(bool visible); - bool event(QEvent* e) override; + //! Override the thumbnail widget with a custom image + void SetCustomThumbnailEnabled(bool enabled); + + //! Assign a custom image to dispsy in place of thumbnail + void SetCustomThumbnailPixmap(const QPixmap& pixmap); Q_SIGNALS: void clicked(); - protected: + private: + void UpdateVisibility(); + + bool event(QEvent* e) override; void paintEvent(QPaintEvent* e) override; void enterEvent(QEvent* e) override; void leaveEvent(QEvent* e) override; - private: Thumbnailer::SharedThumbnailKey m_key; Thumbnailer::ThumbnailWidget* m_thumbnail = nullptr; - QScopedPointer m_thumbnailEnlarged; + Thumbnailer::ThumbnailWidget* m_thumbnailEnlarged = nullptr; + + QLabel* m_customThumbnail = nullptr; + QLabel* m_customThumbnailEnlarged = nullptr; + bool m_customThumbnailEnabled = false; + QLabel* m_emptyThumbnail = nullptr; AspectRatioAwarePixmapWidget* m_dropDownArrow = nullptr; }; From 26aa7495a228670e31ef85201625b7633318fa39 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Tue, 12 Oct 2021 11:26:14 -0500 Subject: [PATCH 21/52] Changed preview renderer states to use construction and destruction instead of start and stop functions to make sure everything is shut down cleanly Signed-off-by: Guthrie Adams --- .../PreviewRenderer/PreviewRenderer.h | 14 +------ .../PreviewRenderer/PreviewRendererState.h | 6 --- .../PreviewRenderer/PreviewRenderer.cpp | 42 +++++-------------- .../PreviewRendererCaptureState.cpp | 21 +++------- .../PreviewRendererCaptureState.h | 6 +-- .../PreviewRendererIdleState.cpp | 6 +-- .../PreviewRendererIdleState.h | 4 +- .../PreviewRendererLoadState.cpp | 17 +++----- .../PreviewRendererLoadState.h | 6 +-- 9 files changed, 29 insertions(+), 93 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h index d4fdd3ca1e..dc03ed6715 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRenderer.h @@ -47,17 +47,6 @@ namespace AtomToolsFramework AZ::RPI::ViewPtr GetView() const; AZ::Uuid GetEntityContextId() const; - enum class State : AZ::s8 - { - None, - IdleState, - LoadState, - CaptureState - }; - - void SetState(State state); - State GetState() const; - void ProcessCaptureRequests(); void CancelCaptureRequest(); void CompleteCaptureRequest(); @@ -91,7 +80,6 @@ namespace AtomToolsFramework AZStd::queue m_captureRequestQueue; CaptureRequest m_currentCaptureRequest; - AZStd::unordered_map> m_states; - State m_currentState = PreviewRenderer::State::None; + AZStd::unique_ptr m_state; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h index 264c37a122..bf68795974 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewRendererState.h @@ -23,12 +23,6 @@ namespace AtomToolsFramework virtual ~PreviewRendererState() = default; - //! Start is called when state begins execution - virtual void Start() = 0; - - //! Stop is called when state ends execution - virtual void Stop() = 0; - protected: PreviewRenderer* m_renderer = {}; }; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index 69a8d357c9..3e4fde4e08 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -79,17 +79,15 @@ namespace AtomToolsFramework m_view->SetViewToClipMatrix(viewToClipMatrix); m_renderPipeline->SetDefaultView(m_view); - m_states[PreviewRenderer::State::IdleState] = AZStd::make_shared(this); - m_states[PreviewRenderer::State::LoadState] = AZStd::make_shared(this); - m_states[PreviewRenderer::State::CaptureState] = AZStd::make_shared(this); - SetState(PreviewRenderer::State::IdleState); + m_state.reset(new PreviewRendererIdleState(this)); } PreviewRenderer::~PreviewRenderer() { PreviewerFeatureProcessorProviderBus::Handler::BusDisconnect(); - SetState(PreviewRenderer::State::None); + m_state.reset(); + m_currentCaptureRequest = {}; m_captureRequestQueue = {}; @@ -120,28 +118,6 @@ namespace AtomToolsFramework return m_entityContext->GetContextId(); } - void PreviewRenderer::SetState(State state) - { - auto stepItr = m_states.find(m_currentState); - if (stepItr != m_states.end()) - { - stepItr->second->Stop(); - } - - m_currentState = state; - - stepItr = m_states.find(m_currentState); - if (stepItr != m_states.end()) - { - stepItr->second->Start(); - } - } - - PreviewRenderer::State PreviewRenderer::GetState() const - { - return m_currentState; - } - void PreviewRenderer::ProcessCaptureRequests() { if (!m_captureRequestQueue.empty()) @@ -150,19 +126,22 @@ namespace AtomToolsFramework m_currentCaptureRequest = m_captureRequestQueue.front(); m_captureRequestQueue.pop(); - SetState(PreviewRenderer::State::LoadState); + m_state.reset(); + m_state.reset(new PreviewRendererLoadState(this)); } } void PreviewRenderer::CancelCaptureRequest() { m_currentCaptureRequest.m_captureFailedCallback(); - SetState(PreviewRenderer::State::IdleState); + m_state.reset(); + m_state.reset(new PreviewRendererIdleState(this)); } void PreviewRenderer::CompleteCaptureRequest() { - SetState(PreviewRenderer::State::IdleState); + m_state.reset(); + m_state.reset(new PreviewRendererIdleState(this)); } void PreviewRenderer::LoadContent() @@ -174,7 +153,8 @@ namespace AtomToolsFramework { if (m_currentCaptureRequest.m_content->IsReady()) { - SetState(PreviewRenderer::State::CaptureState); + m_state.reset(); + m_state.reset(new PreviewRendererCaptureState(this)); return; } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp index 9cf228b707..9a807b7d00 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.cpp @@ -14,32 +14,23 @@ namespace AtomToolsFramework PreviewRendererCaptureState::PreviewRendererCaptureState(PreviewRenderer* renderer) : PreviewRendererState(renderer) { - } - - void PreviewRendererCaptureState::Start() - { - m_ticksToCapture = 1; m_renderer->PoseContent(); AZ::TickBus::Handler::BusConnect(); } - void PreviewRendererCaptureState::Stop() + PreviewRendererCaptureState::~PreviewRendererCaptureState() { - m_renderer->EndCapture(); - AZ::TickBus::Handler::BusDisconnect(); AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); + m_renderer->EndCapture(); } void PreviewRendererCaptureState::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - if (m_ticksToCapture-- <= 0) + if ((m_ticksToCapture-- <= 0) && m_renderer->StartCapture()) { - // Reset the capture flag if the capture request was successful. Otherwise try capture it again next tick. - if (m_renderer->StartCapture()) - { - AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(); - AZ::TickBus::Handler::BusDisconnect(); - } + AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(); + AZ::TickBus::Handler::BusDisconnect(); } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h index 190cb919df..e8c6357445 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererCaptureState.h @@ -22,9 +22,7 @@ namespace AtomToolsFramework { public: PreviewRendererCaptureState(PreviewRenderer* renderer); - - void Start() override; - void Stop() override; + ~PreviewRendererCaptureState(); private: //! AZ::TickBus::Handler interface overrides... @@ -34,6 +32,6 @@ namespace AtomToolsFramework void OnCaptureFinished(AZ::Render::FrameCaptureResult result, const AZStd::string& info) override; //! This is necessary to suspend capture to allow a frame for Material and Mesh components to assign materials - int m_ticksToCapture = 0; + int m_ticksToCapture = 1; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp index 800aa03113..c440bafb73 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.cpp @@ -13,15 +13,11 @@ namespace AtomToolsFramework { PreviewRendererIdleState::PreviewRendererIdleState(PreviewRenderer* renderer) : PreviewRendererState(renderer) - { - } - - void PreviewRendererIdleState::Start() { AZ::TickBus::Handler::BusConnect(); } - void PreviewRendererIdleState::Stop() + PreviewRendererIdleState::~PreviewRendererIdleState() { AZ::TickBus::Handler::BusDisconnect(); } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h index 9e5380e734..f024bd8e30 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererIdleState.h @@ -20,9 +20,7 @@ namespace AtomToolsFramework { public: PreviewRendererIdleState(PreviewRenderer* renderer); - - void Start() override; - void Stop() override; + ~PreviewRendererIdleState(); private: //! AZ::TickBus::Handler interface overrides... diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp index bb858989f7..7e34592095 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.cpp @@ -13,31 +13,24 @@ namespace AtomToolsFramework { PreviewRendererLoadState::PreviewRendererLoadState(PreviewRenderer* renderer) : PreviewRendererState(renderer) - { - } - - void PreviewRendererLoadState::Start() { m_renderer->LoadContent(); - m_timeRemainingS = TimeOutS; AZ::TickBus::Handler::BusConnect(); } - void PreviewRendererLoadState::Stop() + PreviewRendererLoadState::~PreviewRendererLoadState() { AZ::TickBus::Handler::BusDisconnect(); } void PreviewRendererLoadState::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - m_timeRemainingS -= deltaTime; - if (m_timeRemainingS > 0.0f) - { - m_renderer->UpdateLoadContent(); - } - else + if ((m_timeRemainingS += deltaTime) > TimeOutS) { m_renderer->CancelLoadContent(); + return; } + + m_renderer->UpdateLoadContent(); } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h index 623d6cbdfc..702a01e862 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRendererLoadState.h @@ -20,15 +20,13 @@ namespace AtomToolsFramework { public: PreviewRendererLoadState(PreviewRenderer* renderer); - - void Start() override; - void Stop() override; + ~PreviewRendererLoadState(); private: //! AZ::TickBus::Handler interface overrides... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; static constexpr float TimeOutS = 5.0f; - float m_timeRemainingS = TimeOutS; + float m_timeRemainingS = 0.0f; }; } // namespace AtomToolsFramework From e8142fa403a7e932e361ef03bfcce5652051fa43 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Tue, 12 Oct 2021 13:19:38 -0500 Subject: [PATCH 22/52] Updated editor material component slots to support dynamic previews rendered with property overrides applied Fixed scaling issues with labels used for images Reduced updating previews and material component inspector to only apply after a value is committed Storing cache of previously rendered material previews Signed-off-by: Guthrie Adams --- ...orMaterialSystemComponentNotificationBus.h | 5 +- .../EditorMaterialSystemComponentRequestBus.h | 7 ++- .../Material/EditorMaterialComponent.cpp | 14 +++++ .../Source/Material/EditorMaterialComponent.h | 10 ++- .../EditorMaterialComponentInspector.cpp | 14 +++-- .../EditorMaterialComponentInspector.h | 2 - .../Material/EditorMaterialComponentSlot.cpp | 61 +++++++++++++------ .../Material/EditorMaterialComponentSlot.h | 38 ++++++++---- .../EditorMaterialSystemComponent.cpp | 29 +++++++++ .../Material/EditorMaterialSystemComponent.h | 12 +++- 10 files changed, 148 insertions(+), 44 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h index 4e655c7835..30762a60ba 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentNotificationBus.h @@ -10,7 +10,6 @@ #include #include #include -#include class QPixmap; @@ -18,11 +17,11 @@ namespace AZ { namespace Render { - //! EditorMaterialSystemComponentNotifications provides an interface to communicate with EditorMaterialSystemComponent + //! EditorMaterialSystemComponentNotifications is an interface for handling notifications from EditorMaterialSystemComponent, like + //! being informed that material preview images are available class EditorMaterialSystemComponentNotifications : public AZ::EBusTraits { public: - // Only a single handler is allowed static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h index 059e6dec8e..0bf93fc56f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h @@ -17,7 +17,8 @@ namespace AZ { namespace Render { - //! EditorMaterialSystemComponentRequests provides an interface to communicate with MaterialEditor + //! EditorMaterialSystemComponentRequests provides an interface for interacting with EditorMaterialSystemComponent, performing + //! different operations like opening the material editor, the material instance inspector, and managing material preview images class EditorMaterialSystemComponentRequests : public AZ::EBusTraits { public: @@ -35,6 +36,10 @@ namespace AZ //! Generate a material preview image virtual void RenderMaterialPreview( const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) = 0; + + //! Get recently rendered material preview image + virtual QPixmap GetRenderedMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) const = 0; }; using EditorMaterialSystemComponentRequestBus = AZ::EBus; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp index 8e5e7e2345..a3ae61b14b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp @@ -148,11 +148,13 @@ namespace AZ BaseClass::Activate(); MaterialReceiverNotificationBus::Handler::BusConnect(GetEntityId()); MaterialComponentNotificationBus::Handler::BusConnect(GetEntityId()); + EditorMaterialSystemComponentNotificationBus::Handler::BusConnect(); UpdateMaterialSlots(); } void EditorMaterialComponent::Deactivate() { + EditorMaterialSystemComponentNotificationBus::Handler::BusDisconnect(); MaterialReceiverNotificationBus::Handler::BusDisconnect(); MaterialComponentNotificationBus::Handler::BusDisconnect(); BaseClass::Deactivate(); @@ -260,6 +262,18 @@ namespace AZ } } + void EditorMaterialComponent::OnRenderMaterialPreviewComplete( + [[maybe_unused]] const AZ::EntityId& entityId, + [[maybe_unused]] const AZ::Render::MaterialAssignmentId& materialAssignmentId, + [[maybe_unused]] const QPixmap& pixmap) + { + if (entityId == GetEntityId()) + { + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues); + } + } + AZ::u32 EditorMaterialComponent::OnConfigurationChanged() { return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h index f8895d994f..ce21ae82ac 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include @@ -21,8 +22,9 @@ namespace AZ //! In-editor material component for displaying and editing material assignments. class EditorMaterialComponent final : public EditorRenderComponentAdapter - , private MaterialReceiverNotificationBus::Handler - , private MaterialComponentNotificationBus::Handler + , public MaterialReceiverNotificationBus::Handler + , public MaterialComponentNotificationBus::Handler + , public EditorMaterialSystemComponentNotificationBus::Handler { public: using BaseClass = EditorRenderComponentAdapter; @@ -52,6 +54,10 @@ namespace AZ //! MaterialComponentNotificationBus::Handler overrides... void OnMaterialInstanceCreated(const MaterialAssignment& materialAssignment) override; + //! EditorMaterialSystemComponentNotificationBus::Handler overrides... + void OnRenderMaterialPreviewComplete( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId, const QPixmap& pixmap) override; + // Regenerates the editor component material slots based on the material and // LOD mapping from the model or other consumer of materials. // If any corresponding material assignments are found in the component diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 7562049031..9cf39483fe 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -170,6 +170,7 @@ namespace AZ m_overviewImage = new QLabel(this); m_overviewImage->setFixedSize(QSize(120, 120)); + m_overviewImage->setScaledContents(true); m_overviewImage->setVisible(false); m_overviewText = new QLabel(this); @@ -241,8 +242,14 @@ namespace AZ m_overviewText->setText(materialInfo); m_overviewText->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignTop); + + QPixmap pixmap; + EditorMaterialSystemComponentRequestBus::BroadcastResult( + pixmap, &EditorMaterialSystemComponentRequestBus::Events::GetRenderedMaterialPreview, m_entityId, + m_materialAssignmentId); + m_overviewImage->setPixmap(pixmap); m_overviewImage->setVisible(true); - m_updatePreview = true; + m_updatePreview |= pixmap.isNull(); } void MaterialPropertyInspector::AddUvNamesGroup() @@ -400,7 +407,8 @@ namespace AZ m_internalEditNotification = false; } - m_updatePreview = true; + // m_updatePreview should be set to true here for continuous preview updates as slider/color properties change but needs + // throttling } void MaterialPropertyInspector::RunEditorMaterialFunctors() @@ -779,5 +787,3 @@ namespace AZ } // namespace EditorMaterialComponentInspector } // namespace Render } // namespace AZ - -//#include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h index 6199fba179..82f46ebc90 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h @@ -32,8 +32,6 @@ namespace AZ { namespace EditorMaterialComponentInspector { - using PropertyChangedCallback = AZStd::function; - class MaterialPropertyInspector : public AtomToolsFramework::InspectorWidget , public AzToolsFramework::IPropertyEditorNotify diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index 21d045a072..d65fd0f2af 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -6,23 +6,25 @@ * */ -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include +#include +#include #include +#include +#include AZ_POP_DISABLE_WARNING namespace AZ @@ -100,6 +102,7 @@ namespace AZ ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &EditorMaterialComponentSlot::GetLabel) ->Attribute(AZ::Edit::Attributes::ShowProductAssetFileName, true) ->Attribute("ThumbnailCallback", &EditorMaterialComponentSlot::OpenPopupMenu) + ->Attribute("ThumbnailIcon", &EditorMaterialComponentSlot::GetPreviewPixmapData) ; } } @@ -118,6 +121,33 @@ namespace AZ } }; + AZStd::vector EditorMaterialComponentSlot::GetPreviewPixmapData() const + { + if (!GetActiveAssetId().IsValid()) + { + return {}; + } + + QPixmap pixmap; + EditorMaterialSystemComponentRequestBus::BroadcastResult( + pixmap, &EditorMaterialSystemComponentRequestBus::Events::GetRenderedMaterialPreview, m_entityId, m_id); + if (pixmap.isNull()) + { + if (m_updatePreview) + { + EditorMaterialSystemComponentRequestBus::Broadcast( + &EditorMaterialSystemComponentRequestBus::Events::RenderMaterialPreview, m_entityId, m_id); + m_updatePreview = false; + } + return {}; + } + + QByteArray pixmapBytes; + QDataStream stream(&pixmapBytes, QIODevice::WriteOnly); + stream << pixmap; + return AZStd::vector(pixmapBytes.begin(), pixmapBytes.end()); + } + AZ::Data::AssetId EditorMaterialComponentSlot::GetActiveAssetId() const { return m_materialAsset.GetId().IsValid() ? m_materialAsset.GetId() : GetDefaultAssetId(); @@ -169,14 +199,6 @@ namespace AZ ClearOverrides(); } - void EditorMaterialComponentSlot::ClearToDefaultAsset() - { - m_materialAsset = AZ::Data::Asset(GetDefaultAssetId(), AZ::AzTypeInfo::Uuid()); - MaterialComponentRequestBus::Event( - m_entityId, &MaterialComponentRequestBus::Events::SetMaterialOverride, m_id, m_materialAsset.GetId()); - ClearOverrides(); - } - void EditorMaterialComponentSlot::ClearOverrides() { MaterialComponentRequestBus::Event( @@ -317,6 +339,7 @@ namespace AZ EditorMaterialSystemComponentRequestBus::Broadcast( &EditorMaterialSystemComponentRequestBus::Events::RenderMaterialPreview, m_entityId, m_id); + m_updatePreview = false; MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h index 377fe9a18b..78fc7449de 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h @@ -8,37 +8,52 @@ #pragma once -#include -#include - -#include -#include #include +#include +#include +#include +#include +#include namespace AZ { namespace Render { - static const size_t DefaultMaterialSlotIndex = std::numeric_limits::max(); - //! Details for a single editable material assignment struct EditorMaterialComponentSlot final { AZ_RTTI(EditorMaterialComponentSlot, "{344066EB-7C3D-4E92-B53D-3C9EBD546488}"); AZ_CLASS_ALLOCATOR(EditorMaterialComponentSlot, SystemAllocator, 0); - static void Reflect(ReflectContext* context); static bool ConvertVersion(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); + static void Reflect(ReflectContext* context); + //! Get cached preview image as a buffer to use as an RPE attribute + //! If a cached image isn't avalible then a request will be made to render one + AZStd::vector GetPreviewPixmapData() const; + + //! Returns the overridden asset id if it's valid, otherwise gets the default asseet id AZ::Data::AssetId GetActiveAssetId() const; + + //! Returns the default asseet id of the material provded by the model AZ::Data::AssetId GetDefaultAssetId() const; + + //! Returns the display name of the material slot AZStd::string GetLabel() const; + + //! Returns true if the active material asset has a source material bool HasSourceData() const; + //! Assign a new material override asset void SetAsset(const Data::AssetId& assetId); + + //! Assign a new material override asset void SetAsset(const Data::Asset& asset); + + //! Remove material and prperty overrides void Clear(); - void ClearToDefaultAsset(); + + //! Remove prperty overrides void ClearOverrides(); void OpenMaterialExporter(); @@ -54,6 +69,7 @@ namespace AZ void OpenPopupMenu(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& assetType); void OnMaterialChanged() const; void OnDataChanged() const; + mutable bool m_updatePreview = true; }; // Vector of slots for assignable or overridable material data. @@ -62,8 +78,8 @@ namespace AZ // Table containing all editable material data that is displayed in the edit context and inspector // The vector represents all the LODs that can have material overrides. // The container will be populated with every potential material slot on an associated model, using its default values. - // Whenever changes are made to this container, the modified values are copied into the controller configuration material assignment map - // as overrides that will be applied to material instances + // Whenever changes are made to this container, the modified values are copied into the controller configuration material assignment + // map as overrides that will be applied to material instances using EditorMaterialComponentSlotsByLodContainer = AZStd::vector; } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index 96a8e3e8d4..0939c8548b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -88,6 +88,7 @@ namespace AZ void EditorMaterialSystemComponent::Activate() { + EditorMaterialSystemComponentNotificationBus::Handler::BusConnect(); EditorMaterialSystemComponentRequestBus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusConnect(); @@ -100,6 +101,7 @@ namespace AZ { AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); + EditorMaterialSystemComponentNotificationBus::Handler::BusDisconnect(); EditorMaterialSystemComponentRequestBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorMenuNotificationBus::Handler::BusDisconnect(); @@ -167,6 +169,10 @@ namespace AZ { MaterialComponentRequestBus::EventResult( materialAssetId, entityId, &MaterialComponentRequestBus::Events::GetDefaultMaterialAssetId, materialAssignmentId); + if (!materialAssetId.IsValid()) + { + return; + } } AZ::Render::MaterialPropertyOverrideMap propertyOverrides; @@ -193,6 +199,29 @@ namespace AZ } } + QPixmap EditorMaterialSystemComponent::GetRenderedMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) const + { + const auto& itr1 = m_materialPreviews.find(entityId); + if (itr1 != m_materialPreviews.end()) + { + const auto& itr2 = itr1->second.find(materialAssignmentId); + if (itr2 != itr1->second.end()) + { + return itr2->second; + } + } + return QPixmap(); + } + + void EditorMaterialSystemComponent::OnRenderMaterialPreviewComplete( + [[maybe_unused]] const AZ::EntityId& entityId, + [[maybe_unused]] const AZ::Render::MaterialAssignmentId& materialAssignmentId, + [[maybe_unused]] const QPixmap& pixmap) + { + m_materialPreviews[entityId][materialAssignmentId] = pixmap; + } + void EditorMaterialSystemComponent::OnPopulateToolMenuItems() { if (!m_openMaterialEditorAction) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h index f2ccbdc435..e62c9b64dc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h @@ -16,6 +16,7 @@ #include #include #include +#include namespace AZ { @@ -24,6 +25,7 @@ namespace AZ //! System component that manages launching and maintaining connections with the material editor. class EditorMaterialSystemComponent final : public AZ::Component + , public EditorMaterialSystemComponentNotificationBus::Handler , public EditorMaterialSystemComponentRequestBus::Handler , public AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler , public AzToolsFramework::EditorMenuNotificationBus::Handler @@ -50,8 +52,13 @@ namespace AZ //! EditorMaterialSystemComponentRequestBus::Handler overrides... void OpenMaterialEditor(const AZStd::string& sourcePath) override; void OpenMaterialInspector(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; - void RenderMaterialPreview( - const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; + void RenderMaterialPreview(const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) override; + QPixmap GetRenderedMaterialPreview( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId) const override; + + //! EditorMaterialSystemComponentNotificationBus::Handler overrides... + void OnRenderMaterialPreviewComplete( + const AZ::EntityId& entityId, const AZ::Render::MaterialAssignmentId& materialAssignmentId, const QPixmap& pixmap)override; //! AssetBrowserInteractionNotificationBus::Handler overrides... AzToolsFramework::AssetBrowser::SourceFileDetails GetSourceFileDetails(const char* fullSourceFileName) override; @@ -73,6 +80,7 @@ namespace AZ QAction* m_openMaterialEditorAction = nullptr; AZStd::unique_ptr m_materialBrowserInteractions; AZStd::unique_ptr m_previewRenderer; + AZStd::unordered_map> m_materialPreviews; }; } // namespace Render } // namespace AZ From 343a13a13469e2c3db46c642d1a93d0b9ed10672 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Tue, 12 Oct 2021 16:44:54 -0500 Subject: [PATCH 23/52] updating comments Signed-off-by: Guthrie Adams --- .../UI/PropertyEditor/ThumbnailPropertyCtrl.h | 4 ++-- .../PreviewRenderer/PreviewContent.h | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h index b1ce78b601..ffd8234190 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ThumbnailPropertyCtrl.h @@ -39,13 +39,13 @@ namespace AzToolsFramework //! Remove current thumbnail void ClearThumbnail(); - //! Display a clickble dropdown arrow next to the thumbnail + //! Display a clickable dropdown arrow next to the thumbnail void ShowDropDownArrow(bool visible); //! Override the thumbnail widget with a custom image void SetCustomThumbnailEnabled(bool enabled); - //! Assign a custom image to dispsy in place of thumbnail + //! Assign a custom image to display in place of thumbnail void SetCustomThumbnailPixmap(const QPixmap& pixmap); Q_SIGNALS: diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h index bdc7afe0b1..a96cec65b1 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/PreviewRenderer/PreviewContent.h @@ -12,7 +12,7 @@ namespace AtomToolsFramework { - //! Provides custom rendering of previefw images + //! Interface for describing scene content that will be rendered using the PreviewRenderer class PreviewContent { public: @@ -20,10 +20,20 @@ namespace AtomToolsFramework PreviewContent() = default; virtual ~PreviewContent() = default; + + //! Initiate loading of scene content, models, materials, etc virtual void Load() = 0; + + //! Return true if content is loaded and ready to render virtual bool IsReady() const = 0; + + //! Return true if content failed to load virtual bool IsError() const = 0; + + //! Report any issues encountered while loading virtual void ReportErrors() = 0; + + //! Prepare or pose content before rendering virtual void Update() = 0; }; } // namespace AtomToolsFramework From 8d97f75e427cd8f4fa63b6e7236c7fd1bea28a5f Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 12 Oct 2021 23:38:01 +0000 Subject: [PATCH 24/52] Fixes to allow cmake to find files inside the render doc linux tar Signed-off-by: rgba16f <82187279+rgba16f@users.noreply.github.com> --- Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake | 4 +++- Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake b/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake index f8f17392b3..4fc54b9733 100644 --- a/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake +++ b/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake @@ -10,6 +10,8 @@ ly_add_external_target( NAME renderdoc 3RDPARTY_ROOT_DIRECTORY "${LY_RENDERDOC_PATH}" VERSION - INCLUDE_DIRECTORIES . + INCLUDE_DIRECTORIES + . + include COMPILE_DEFINITIONS USE_RENDERDOC ) diff --git a/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake b/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake index a74d250901..6225cc292a 100644 --- a/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake +++ b/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake @@ -6,4 +6,4 @@ # # -set(RENDERDOC_RUNTIME_DEPENDENCIES "${BASE_PATH}/librenderdoc.so") +set(RENDERDOC_RUNTIME_DEPENDENCIES "${BASE_PATH}/lib/librenderdoc.so") From 63da5847c105092ebe23d73aefbbfd4b4d1ea086 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Tue, 12 Oct 2021 20:15:29 -0700 Subject: [PATCH 25/52] chore: correct documentation and correct method return. - change return for IntersectSegmentTriangleCCW to bool - change return for IntersectSegmentTriangle to bool Signed-off-by: Michael Pollind --- .../AzCore/AzCore/Math/IntersectSegment.cpp | 24 +- .../AzCore/AzCore/Math/IntersectSegment.h | 238 +++++++++--------- 2 files changed, 130 insertions(+), 132 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp index 1bf1e41cb7..5d13acc34c 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.cpp @@ -15,7 +15,7 @@ using namespace Intersect; // IntersectSegmentTriangleCCW // [10/21/2009] //========================================================================= -int Intersect::IntersectSegmentTriangleCCW( +bool Intersect::IntersectSegmentTriangleCCW( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, /*float &u, float &v, float &w,*/ Vector3& normal, float& t) { @@ -34,7 +34,7 @@ int Intersect::IntersectSegmentTriangleCCW( float d = qp.Dot(normal); if (d <= 0.0f) { - return 0; + return false; } // Compute intersection t value of pq with plane of triangle. A ray @@ -46,7 +46,7 @@ int Intersect::IntersectSegmentTriangleCCW( // range segment check t[0,1] (it this case [0,d]) if (t < 0.0f || t > d) { - return 0; + return false; } // Compute barycentric coordinate components and test if within bounds @@ -54,12 +54,12 @@ int Intersect::IntersectSegmentTriangleCCW( v = ac.Dot(e); if (v < 0.0f || v > d) { - return 0; + return false; } w = -ab.Dot(e); if (w < 0.0f || v + w > d) { - return 0; + return false; } // Segment/ray intersects triangle. Perform delayed division and @@ -72,14 +72,14 @@ int Intersect::IntersectSegmentTriangleCCW( normal.Normalize(); - return 1; + return true; } //========================================================================= // IntersectSegmentTriangle // [10/21/2009] //========================================================================= -int +bool Intersect::IntersectSegmentTriangle( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, /*float &u, float &v, float &w,*/ Vector3& normal, float& t) @@ -111,7 +111,7 @@ Intersect::IntersectSegmentTriangle( // so either have a parallel ray or our normal is flipped if (d >= -Constants::FloatEpsilon) { - return 0; // parallel + return false; // parallel } d = -d; e = ap.Cross(qp); @@ -125,19 +125,19 @@ Intersect::IntersectSegmentTriangle( // range segment check t[0,1] (it this case [0,d]) if (t < 0.0f || t > d) { - return 0; + return false; } // Compute barycentric coordinate components and test if within bounds v = ac.Dot(e); if (v < 0.0f || v > d) { - return 0; + return false; } w = -ab.Dot(e); if (w < 0.0f || v + w > d) { - return 0; + return false; } // Segment/ray intersects the triangle. Perform delayed division and @@ -150,7 +150,7 @@ Intersect::IntersectSegmentTriangle( normal.Normalize(); - return 1; + return true; } //========================================================================= diff --git a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h index 71c39fb53d..523069987f 100644 --- a/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h +++ b/Code/Framework/AzCore/AzCore/Math/IntersectSegment.h @@ -17,46 +17,45 @@ namespace AZ namespace Intersect { //! LineToPointDistanceTime computes the time of the shortest distance from point 'p' to segment (s1,s2). - //! To calculate the point of intersection: - //! P = s1 + u (s2 - s1) - //! @param s1 segment start point - //! @param s2 segment end point - //! @param p point to find the closest time to. - //! @return time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + //! To calculate the point of intersection: P = s1 + u (s2 - s1) + //! @param s1 Segment start point. + //! @param s2 Segment end point. + //! @param p Point to find the closest time to. + //! @return Time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] float LineToPointDistanceTime(const Vector3& s1, const Vector3& s21, const Vector3& p); //! LineToPointDistance computes the closest point to 'p' from a segment (s1,s2). - //! @param s1 segment start point - //! @param s2 segment end point - //! @param p point to find the closest time to. - //! @param u time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] - //! @return the closest point + //! @param s1 Segment start point + //! @param s2 Segment end point + //! @param p Point to find the closest time to. + //! @param u Time (on the segment) for the shortest distance from 'p' to (s1,s2) [0.0f (s1),1.0f (s2)] + //! @return The closest point Vector3 LineToPointDistance(const Vector3& s1, const Vector3& s2, const Vector3& p, float& u); //! Given segment pq and triangle abc (CCW), returns whether segment intersects //! triangle and if so, also returns the barycentric coordinates (u,v,w) //! of the intersection point. - //! @param p segment start point - //! @param q segment end point - //! @param a triangle point 1 - //! @param b triangle point 2 - //! @param c triangle point 3 - //! @param normal at the intersection point. - //! @param t time of intersection along the segment [0.0 (p), 1.0 (q)] - //! @return true if the segments intersects the triangle otherwise false - int IntersectSegmentTriangleCCW( + //! @param p Segment start point. + //! @param q Segment end point. + //! @param a Triangle point 1. + //! @param b Triangle point 2. + //! @param c Triangle point 3. + //! @param normal At the intersection point. + //! @param t Time of intersection along the segment [0.0 (p), 1.0 (q)]. + //! @return true if the segments intersects the triangle otherwise false. + bool IntersectSegmentTriangleCCW( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); //! Same as \ref IntersectSegmentTriangleCCW without respecting the triangle (a,b,c) vertex order (double sided). - //! @param p segment start point - //! @param q segment end point - //! @param a triangle point 1 - //! @param b triangle point 2 - //! @param c triangle point 3 - //! @param normal at the intersection point; - //! @param t time of intersection along the segment [0.0 (p), 1.0 (q)] - //! @return true if the segments intersects the triangle otherwise false - int IntersectSegmentTriangle( + //! @param p Segment start point. + //! @param q Segment end point. + //! @param a Triangle point 1. + //! @param b Triangle point 2. + //! @param c Triangle point 3. + //! @param normal At the intersection point. + //! @param t Time of intersection along the segment [0.0 (p), 1.0 (q)]. + //! @return True if the segments intersects the triangle otherwise false. + bool IntersectSegmentTriangle( const Vector3& p, const Vector3& q, const Vector3& a, const Vector3& b, const Vector3& c, Vector3& normal, float& t); //! Ray aabb intersection result types. @@ -69,14 +68,14 @@ namespace AZ //! Intersect ray R(t) = rayStart + t*d against AABB a. When intersecting, //! return intersection distance tmin and point q of intersection. - //! @param rayStart ray starting point - //! @param dir ray direction and length (dir = rayEnd - rayStart) + //! @param rayStart Ray starting point + //! @param dir Ray direction and length (dir = rayEnd - rayStart) //! @param dirRCP 1/dir (reciprocal direction - we cache this result very often so we don't need to compute it multiple times, //! otherwise just use dir.GetReciprocal()) //! @param aabb Axis aligned bounding box to intersect against - //! @param tStart time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value - //! @param tEnd time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) - //! @param startNormal normal at the start point. + //! @param tStart Time on ray of the first intersection [0,1] or 0 if the ray starts inside the aabb - check the return value + //! @param tEnd Time of the of the second intersection [0,1] (it can be > 1 if intersects after the rayEnd) + //! @param startNormal Normal at the start point. //! @return \ref RayAABBIsectTypes RayAABBIsectTypes IntersectRayAABB( const Vector3& rayStart, @@ -88,66 +87,66 @@ namespace AZ Vector3& startNormal); //! Intersect ray against AABB. - //! @param rayStart ray starting point. - //! @param dir ray reciprocal direction. + //! @param rayStart Ray starting point. + //! @param dir Ray reciprocal direction. //! @param aabb Axis aligned bounding box to intersect against. - //! @param start length on ray of the first intersection. - //! @param end length of the of the second intersection. + //! @param start Length on ray of the first intersection. + //! @param end Length of the of the second intersection. //! @return \ref RayAABBIsectTypes In this faster version than IntersectRayAABB we return only ISECT_RAY_AABB_NONE and //! ISECT_RAY_AABB_ISECT. You can check yourself for that case. RayAABBIsectTypes IntersectRayAABB2(const Vector3& rayStart, const Vector3& dirRCP, const Aabb& aabb, float& start, float& end); //! Clip a ray to an aabb. return true if ray was clipped. The ray //! can be inside so don't use the result if the ray intersect the box. - //! @param aabb bounds - //! @param rayStart the start of the ray - //! @param rayEnd the end of the ray - //! @param[out] tClipStart The proportion where the ray enterts the aabb - //! @param[out] tClipEnd The proportion where the ray exits the aabb - //! @return true ray was clipped else false + //! @param aabb Bounds to test against. + //! @param rayStart The start of the ray. + //! @param rayEnd The end of the ray. + //! @param[out] tClipStart The proportion where the ray enters the \ref Aabb. + //! @param[out] tClipEnd The proportion where the ray exits the \ref Aabb. + //! @return True if the ray was clipped, otherwise false. bool ClipRayWithAabb(const Aabb& aabb, Vector3& rayStart, Vector3& rayEnd, float& tClipStart, float& tClipEnd); //! Test segment and aabb where the segment is defined by midpoint //! midPoint = (p1-p0) * 0.5f and half vector halfVector = p1 - midPoint. //! the aabb is at the origin and defined by half extents only. - //! @param midPoint midpoint of a line segment - //! @param halfVector half vector of an aabb - //! @param aabbExtends the extends of a bounded box - //! @return true if the intersect, otherwise false. + //! @param midPoint Midpoint of a line segment. + //! @param halfVector Half vector of an aabb. + //! @param aabbExtends The extends of a bounded box. + //! @return True if the segment and AABB intersect, otherwise false bool TestSegmentAABBOrigin(const Vector3& midPoint, const Vector3& halfVector, const Vector3& aabbExtends); - //! Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin - //! @param p0 point 1 - //! @param p1 point 2 - //! @param aabb bounded box - //! @return true if the segment and AABB intersect, otherwise false. + //! Test if segment specified by points p0 and p1 intersects AABB. \ref TestSegmentAABBOrigin. + //! @param p0 Segment start point. + //! @param p1 Segment end point. + //! @param aabb Bounded box to test against. + //! @return True if the segment and AABB intersect, otherwise false. bool TestSegmentAABB(const Vector3& p0, const Vector3& p1, const Aabb& aabb); //! Ray sphere intersection result types. enum SphereIsectTypes : AZ::s32 { - ISECT_RAY_SPHERE_SA_INSIDE = -1, //!< the ray starts inside the cylinder - ISECT_RAY_SPHERE_NONE, //!< no intersection - ISECT_RAY_SPHERE_ISECT, //!< along the PQ segment + ISECT_RAY_SPHERE_SA_INSIDE = -1, //!< The ray starts inside the cylinder + ISECT_RAY_SPHERE_NONE, //!< No intersection + ISECT_RAY_SPHERE_ISECT, //!< Along the PQ segment }; //! IntersectRaySphereOrigin //! return time t>=0 but not limited, so if you check a segment make sure - //! t <= segmentLen - //! @param rayStart ray start point + //! t <= segmentLen. + //! @param rayStart ray start point. //! @param rayDirNormalized ray direction normalized. - //! @param shereRadius sphere radius + //! @param shereRadius Radius of sphere at origin. //! @param time of closest intersection [0,+INF] in relation to the normalized direction. - //! @return \ref SphereIsectTypes + //! @return \ref SphereIsectTypes. SphereIsectTypes IntersectRaySphereOrigin( const Vector3& rayStart, const Vector3& rayDirNormalized, const float sphereRadius, float& t); //! Intersect ray (rayStart,rayDirNormalized) and sphere (sphereCenter,sphereRadius) \ref IntersectRaySphereOrigin - //! @param rayStart the start of the ray - //! @param rayDirNormalized the direction of the ray normalized - //! @param sphereCenter the center of the sphere - //! @param sphereRadius radius of the sphere - //! @param[out] t coefficient in the ray's explicit equation from which an + //! @param rayStart The start of the ray. + //! @param rayDirNormalized The direction of the ray normalized. + //! @param sphereCenter The center of the sphere. + //! @param sphereRadius Radius of the sphere. + //! @param[out] t Coefficient in the ray's explicit equation from which an //! intersecting point is calculated as "rayOrigin + t1 * rayDir". //! @return SphereIsectTypes SphereIsectTypes IntersectRaySphere( @@ -156,12 +155,12 @@ namespace AZ //! Intersect ray (rayStarty, rayDirNormalized) and disk (center, radius, normal) //! @param rayOrigin The origin of the ray to test. //! @param rayDir The direction of the ray to test. It has to be unit length. - //! @param diskCenter Center point of the disk - //! @param diskRadius Radius of the disk - //! @param diskNormal A normal perpendicular to the disk + //! @param diskCenter Center point of the disk. + //! @param diskRadius Radius of the disk. + //! @param diskNormal A normal perpendicular to the disk. //! @param[out] t If returning 1 (indicating a hit), this contains distance from rayOrigin along the normalized rayDir //! that the hit occured at. - //! @return false if not interesecting and true if intersecting + //! @return False if not interesecting and true if intersecting bool IntersectRayDisk( const Vector3& rayOrigin, const Vector3& rayDir, @@ -215,7 +214,7 @@ namespace AZ //! @param planePos A point on the plane to test intersection with. //! @param planeNormal The normal of the plane to test intersection with. //! @param[out] t The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return The number of intersection point. + //! @return The number of intersection point. int IntersectRayPlane( const Vector3& rayOrigin, const Vector3& rayDir, const Vector3& planePos, const Vector3& planeNormal, float& t); @@ -230,7 +229,7 @@ namespace AZ //! @param vertexD One of the four points that define the quadrilateral. //! @param[out] t The coefficient in the ray's explicit equation from which the //! intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return The number of intersection point. + //! @return The number of intersection point. int IntersectRayQuad( const Vector3& rayOrigin, const Vector3& rayDir, @@ -269,7 +268,7 @@ namespace AZ //! @param rayDir The direction of the ray to test intersection with. //! @param obb The OBB to test for intersection with the ray. //! @param[out] t The coefficient in the ray's explicit equation from which the intersecting point is calculated as "rayOrigin + t * rayDirection". - //! @return true if there is an intersection, false otherwise. + //! @return True if there is an intersection, false otherwise. bool IntersectRayObb(const Vector3& rayOrigin, const Vector3& rayDir, const Obb& obb, float& t); //! Ray cylinder intersection types. @@ -284,13 +283,12 @@ namespace AZ //! Reference: Real-Time Collision Detection - 5.3.7 Intersecting Ray or Segment Against Cylinder //! Intersect segment S(t)=sa+t(dir), 0<=t<=1 against cylinder specified by p, q and r. - //! - //! @param sa point - //! @param dir magnitude along sa - //! @param p center point of side 1 cylinder - //! @param q center point of side 2 cylinder - //! @param r radius of cylinder - //! @param[out] t proporition along line segment + //! @param sa The initial point. + //! @param dir Magnitude and direction for sa. + //! @param p Center point of side 1 cylinder. + //! @param q Center point of side 2 cylinder. + //! @param r Radius of cylinder. + //! @param[out] t Proporition along line segment. //! @return CylinderIsectTypes CylinderIsectTypes IntersectSegmentCylinder( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); @@ -298,22 +296,22 @@ namespace AZ //! Capsule ray intersect types. enum CapsuleIsectTypes { - ISECT_RAY_CAPSULE_SA_INSIDE = -1, //!< the ray starts inside the cylinder - ISECT_RAY_CAPSULE_NONE, //!< no intersection - ISECT_RAY_CAPSULE_PQ, //!< along the PQ segment - ISECT_RAY_CAPSULE_P_SIDE, //!< on the P side - ISECT_RAY_CAPSULE_Q_SIDE, //!< on the Q side + ISECT_RAY_CAPSULE_SA_INSIDE = -1, //!< The ray starts inside the cylinder + ISECT_RAY_CAPSULE_NONE, //!< No intersection + ISECT_RAY_CAPSULE_PQ, //!< Along the PQ segment + ISECT_RAY_CAPSULE_P_SIDE, //!< On the P side + ISECT_RAY_CAPSULE_Q_SIDE, //!< On the Q side }; //! This is a quick implementation of segment capsule based on segment cylinder \ref IntersectSegmentCylinder //! segment sphere intersection. We can optimize it a lot once we fix the ray //! cylinder intersection. - //! @param sa the beginning of the line segment - //! @param dir the direction and length of the segment - //! @param p center point of side 1 capsule - //! @param q center point of side 1 capsule - //! @param r the radius of the capsule - //! @param[out] t proporition along line segment + //! @param sa The beginning of the line segment. + //! @param dir The direction and length of the segment. + //! @param p Center point of side 1 capsule. + //! @param q Center point of side 1 capsule. + //! @param r The radius of the capsule. + //! @param[out] t Proporition along line segment. //! @return CapsuleIsectTypes CapsuleIsectTypes IntersectSegmentCapsule( const Vector3& sa, const Vector3& dir, const Vector3& p, const Vector3& q, const float r, float& t); @@ -321,15 +319,15 @@ namespace AZ //! Intersect segment S(t)=A+t(B-A), 0<=t<=1 against convex polyhedron specified //! by the n halfspaces defined by the planes p[]. On exit tfirst and tlast //! define the intersection, if any. - //! @param sa the beggining of the line segment - //! @param dir the direction and length of the segment - //! @param p planes that compose a convex ponvex polyhedron - //! @param numPlanes number of planes - //! @param[out] tfirst proportion along the line segment where the line enters - //! @param[out] tlast proportion along the line segment where the line exits - //! @param[out] iFirstPlane the plane where the line enters - //! @param[out] iLastPlane the plane where the line exits - //! @return true if intersects else false + //! @param sa The beggining of the line segment. + //! @param dir The direction and length of the segment. + //! @param p Planes that compose a convex ponvex polyhedron. + //! @param numPlanes number of planes. + //! @param[out] tfirst Proportion along the line segment where the line enters. + //! @param[out] tlast Proportion along the line segment where the line exits. + //! @param[out] iFirstPlane The plane where the line enters. + //! @param[out] iLastPlane The plane where the line exits. + //! @return True if intersects else false. bool IntersectSegmentPolyhedron( const Vector3& sa, const Vector3& dir, @@ -345,15 +343,15 @@ namespace AZ //! segment2Proportion where closestPointSegment1 = segment1Start + (segment1Proportion * (segment1End - segment1Start)) //! closestPointSegment2 = segment2Start + (segment2Proportion * (segment2End - segment2Start)) //! If segments are parallel returns a solution. - //! @param segment1Start start of segment 1. - //! @param segment1End end of segment 1. - //! @param segment2Start start of segment 2. - //! @param segment2End end of segment 2. - //! @param[out] segment1Proportion the proporition along segment 1 [0..1] - //! @param[out] segment2Proportion the proporition along segment 2 [0..1] - //! @param[out] closestPointSegment1 closest point on segment 1. - //! @param[out] closestPointSegment2 closest point on segment 2. - //! @param epsilon the minimum square distance where a line segment can be treated as a single point. + //! @param segment1Start Start of segment 1. + //! @param segment1End End of segment 1. + //! @param segment2Start Start of segment 2. + //! @param segment2End End of segment 2. + //! @param[out] segment1Proportion The proporition along segment 1 [0..1] + //! @param[out] segment2Proportion The proporition along segment 2 [0..1] + //! @param[out] closestPointSegment1 Closest point on segment 1. + //! @param[out] closestPointSegment2 Closest point on segment 2. + //! @param epsilon The minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, const Vector3& segment1End, @@ -368,13 +366,13 @@ namespace AZ //! Calculate the line segment closestPointSegment1<->closestPointSegment2 that is the shortest route between //! two segments segment1Start<->segment1End and segment2Start<->segment2End. //! If segments are parallel returns a solution. - //! @param segment1Start start of segment 1. - //! @param segment1End end of segment 1. - //! @param segment2Start start of segment 2. - //! @param segment2End end of segment 2. - //! @param[out] closestPointSegment1 closest point on segment 1. - //! @param[out] closestPointSegment2 closest point on segment 2. - //! @param epsilon the minimum square distance where a line segment can be treated as a single point. + //! @param segment1Start Start of segment 1. + //! @param segment1End End of segment 1. + //! @param segment2Start Start of segment 2. + //! @param segment2End End of segment 2. + //! @param[out] closestPointSegment1 Closest point on segment 1. + //! @param[out] closestPointSegment2 Closest point on segment 2. + //! @param epsilon The minimum square distance where a line segment can be treated as a single point. void ClosestSegmentSegment( const Vector3& segment1Start, const Vector3& segment1End, @@ -387,11 +385,11 @@ namespace AZ //! Calculate the point (closestPointOnSegment) that is the closest point on //! segment segmentStart/segmentEnd to point. Also calculate the value of proportion where //! closestPointOnSegment = segmentStart + (proportion * (segmentEnd - segmentStart)) - //! @param point the point to test - //! @param segmentStart the start of the segment - //! @param segmentEnd the end of the segment - //! @param[out] proportion the proportion of the segment L(t) = (end - start) * t - //! @param[out] closestPointOnSegment the point along the line segment + //! @param point The point to test + //! @param segmentStart The start of the segment + //! @param segmentEnd The end of the segment + //! @param[out] proportion The proportion of the segment L(t) = (end - start) * t + //! @param[out] closestPointOnSegment The point along the line segment void ClosestPointSegment( const Vector3& point, const Vector3& segmentStart, From 4089edb33698f37d06c0bcfee9385401aab50604 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 13 Oct 2021 11:19:01 -0500 Subject: [PATCH 26/52] added missing include to fix build Signed-off-by: Guthrie Adams --- .../Material/EditorMaterialSystemComponentRequestBus.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h index 0bf93fc56f..191f444586 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace AZ { From 7415277eed731284e9664d550f6ceb644c4e6582 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 13 Oct 2021 13:35:46 -0500 Subject: [PATCH 27/52] fixing ME shutdown Signed-off-by: Guthrie Adams --- .../Code/Source/PreviewRenderer/PreviewRenderer.cpp | 1 + .../Code/Source/SharedPreview/SharedPreviewContent.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index 3e4fde4e08..2a6991dc46 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -96,6 +96,7 @@ namespace AtomToolsFramework AZ::RPI::RPISystemInterface::Get()->UnregisterScene(m_scene); m_frameworkScene->UnsetSubsystem(m_scene); m_frameworkScene->UnsetSubsystem(m_entityContext.get()); + m_entityContext->DestroyContext(); } void PreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp index 21020f64b1..91b6d2b02a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SharedPreview/SharedPreviewContent.cpp @@ -44,7 +44,7 @@ namespace AZ { // Create preview model AzFramework::EntityContextRequestBus::EventResult( - m_modelEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ThumbnailPreviewModel"); + m_modelEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "SharedPreviewContentModel"); m_modelEntity->CreateComponent(Render::MeshComponentTypeId); m_modelEntity->CreateComponent(Render::MaterialComponentTypeId); m_modelEntity->CreateComponent(azrtti_typeid()); @@ -60,6 +60,7 @@ namespace AZ { if (m_modelEntity) { + m_modelEntity->Deactivate(); AzFramework::EntityContextRequestBus::Event( m_entityContextId, &AzFramework::EntityContextRequestBus::Events::DestroyEntity, m_modelEntity); m_modelEntity = nullptr; From f83c8bcb5aa17754c42f85e9471c42f08ec9225e Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Wed, 13 Oct 2021 16:28:56 -0500 Subject: [PATCH 28/52] Added gem template for custom tool in C++. Signed-off-by: Chris Galvan --- Templates/CustomTool/Template/CMakeLists.txt | 22 + .../Code/${NameLower}_editor_files.cmake | 15 + .../${NameLower}_editor_shared_files.cmake | 11 + .../${NameLower}_editor_tests_files.cmake | 11 + .../Template/Code/${NameLower}_files.cmake | 14 + .../Code/${NameLower}_shared_files.cmake | 11 + .../Code/${NameLower}_tests_files.cmake | 11 + .../CustomTool/Template/Code/CMakeLists.txt | 168 ++++++++ .../Code/Include/${Name}/${Name}Bus.h | 40 ++ .../Android/${NameLower}_android_files.cmake | 15 + .../${NameLower}_shared_android_files.cmake | 15 + .../Code/Platform/Android/PAL_android.cmake | 11 + .../Linux/${NameLower}_linux_files.cmake | 15 + .../${NameLower}_shared_linux_files.cmake | 15 + .../Code/Platform/Linux/PAL_linux.cmake | 11 + .../Platform/Mac/${NameLower}_mac_files.cmake | 15 + .../Mac/${NameLower}_shared_mac_files.cmake | 15 + .../Template/Code/Platform/Mac/PAL_mac.cmake | 11 + .../${NameLower}_shared_windows_files.cmake | 15 + .../Windows/${NameLower}_windows_files.cmake | 15 + .../Code/Platform/Windows/PAL_windows.cmake | 11 + .../Platform/iOS/${NameLower}_ios_files.cmake | 15 + .../iOS/${NameLower}_shared_ios_files.cmake | 15 + .../Template/Code/Platform/iOS/PAL_ios.cmake | 11 + .../Template/Code/Source/${Name}.qrc | 5 + .../Code/Source/${Name}EditorModule.cpp | 55 +++ .../Source/${Name}EditorSystemComponent.cpp | 78 ++++ .../Source/${Name}EditorSystemComponent.h | 45 +++ .../Template/Code/Source/${Name}Module.cpp | 25 ++ .../Code/Source/${Name}ModuleInterface.h | 45 +++ .../Code/Source/${Name}SystemComponent.cpp | 92 +++++ .../Code/Source/${Name}SystemComponent.h | 56 +++ .../Template/Code/Source/${Name}Widget.cpp | 44 ++ .../Template/Code/Source/${Name}Widget.h | 28 ++ .../Template/Code/Source/toolbar_icon.svg | 1 + .../Template/Code/Tests/${Name}EditorTest.cpp | 13 + .../Template/Code/Tests/${Name}Test.cpp | 13 + .../Platform/Android/android_gem.cmake | 8 + .../Platform/Android/android_gem.json | 3 + .../Template/Platform/Linux/linux_gem.cmake | 8 + .../Template/Platform/Linux/linux_gem.json | 3 + .../Template/Platform/Mac/mac_gem.cmake | 8 + .../Template/Platform/Mac/mac_gem.json | 3 + .../Platform/Windows/windows_gem.cmake | 8 + .../Platform/Windows/windows_gem.json | 3 + .../Template/Platform/iOS/ios_gem.cmake | 8 + .../Template/Platform/iOS/ios_gem.json | 3 + Templates/CustomTool/Template/gem.json | 17 + Templates/CustomTool/Template/preview.png | 3 + Templates/CustomTool/template.json | 382 ++++++++++++++++++ engine.json | 1 + 51 files changed, 1466 insertions(+) create mode 100644 Templates/CustomTool/Template/CMakeLists.txt create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_editor_files.cmake create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_editor_shared_files.cmake create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_editor_tests_files.cmake create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_files.cmake create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_shared_files.cmake create mode 100644 Templates/CustomTool/Template/Code/${NameLower}_tests_files.cmake create mode 100644 Templates/CustomTool/Template/Code/CMakeLists.txt create mode 100644 Templates/CustomTool/Template/Code/Include/${Name}/${Name}Bus.h create mode 100644 Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_android_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_shared_android_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_shared_linux_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Linux/PAL_linux.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_shared_mac_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Mac/PAL_mac.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_shared_windows_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/Windows/PAL_windows.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_shared_ios_files.cmake create mode 100644 Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}.qrc create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}EditorModule.cpp create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.cpp create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.h create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}Module.cpp create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}ModuleInterface.h create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.cpp create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.h create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}Widget.cpp create mode 100644 Templates/CustomTool/Template/Code/Source/${Name}Widget.h create mode 100644 Templates/CustomTool/Template/Code/Source/toolbar_icon.svg create mode 100644 Templates/CustomTool/Template/Code/Tests/${Name}EditorTest.cpp create mode 100644 Templates/CustomTool/Template/Code/Tests/${Name}Test.cpp create mode 100644 Templates/CustomTool/Template/Platform/Android/android_gem.cmake create mode 100644 Templates/CustomTool/Template/Platform/Android/android_gem.json create mode 100644 Templates/CustomTool/Template/Platform/Linux/linux_gem.cmake create mode 100644 Templates/CustomTool/Template/Platform/Linux/linux_gem.json create mode 100644 Templates/CustomTool/Template/Platform/Mac/mac_gem.cmake create mode 100644 Templates/CustomTool/Template/Platform/Mac/mac_gem.json create mode 100644 Templates/CustomTool/Template/Platform/Windows/windows_gem.cmake create mode 100644 Templates/CustomTool/Template/Platform/Windows/windows_gem.json create mode 100644 Templates/CustomTool/Template/Platform/iOS/ios_gem.cmake create mode 100644 Templates/CustomTool/Template/Platform/iOS/ios_gem.json create mode 100644 Templates/CustomTool/Template/gem.json create mode 100644 Templates/CustomTool/Template/preview.png create mode 100644 Templates/CustomTool/template.json diff --git a/Templates/CustomTool/Template/CMakeLists.txt b/Templates/CustomTool/Template/CMakeLists.txt new file mode 100644 index 0000000000..b19ea2edce --- /dev/null +++ b/Templates/CustomTool/Template/CMakeLists.txt @@ -0,0 +1,22 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(o3de_gem_path ${CMAKE_CURRENT_LIST_DIR}) +set(o3de_gem_json ${o3de_gem_path}/gem.json) +o3de_read_json_key(o3de_gem_name ${o3de_gem_json} "gem_name") +o3de_restricted_path(${o3de_gem_json} o3de_gem_restricted_path) + +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} "${o3de_gem_restricted_path}" ${o3de_gem_path} ${o3de_gem_name}) + +# Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the +# project cmake for this platform. +include(${pal_dir}/${PAL_PLATFORM_NAME_LOWERCASE}_gem.cmake) + +ly_add_external_target_path(${CMAKE_CURRENT_LIST_DIR}/3rdParty) + +add_subdirectory(Code) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_editor_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_editor_files.cmake new file mode 100644 index 0000000000..d73efffa2e --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_editor_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Source/${Name}EditorSystemComponent.cpp + Source/${Name}EditorSystemComponent.h + Source/${Name}Widget.cpp + Source/${Name}Widget.h + Source/${Name}.qrc +) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_editor_shared_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_editor_shared_files.cmake new file mode 100644 index 0000000000..2d4ceae97d --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_editor_shared_files.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Source/${Name}EditorModule.cpp +) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_editor_tests_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_editor_tests_files.cmake new file mode 100644 index 0000000000..ff45c2fc1c --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_editor_tests_files.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Tests/${Name}EditorTest.cpp +) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_files.cmake new file mode 100644 index 0000000000..b7d6d37bdf --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_files.cmake @@ -0,0 +1,14 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Include/${Name}/${Name}Bus.h + Source/${Name}ModuleInterface.h + Source/${Name}SystemComponent.cpp + Source/${Name}SystemComponent.h +) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_shared_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_shared_files.cmake new file mode 100644 index 0000000000..b85916191c --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_shared_files.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Source/${Name}Module.cpp +) diff --git a/Templates/CustomTool/Template/Code/${NameLower}_tests_files.cmake b/Templates/CustomTool/Template/Code/${NameLower}_tests_files.cmake new file mode 100644 index 0000000000..adcfe2645f --- /dev/null +++ b/Templates/CustomTool/Template/Code/${NameLower}_tests_files.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(FILES + Tests/${Name}Test.cpp +) diff --git a/Templates/CustomTool/Template/Code/CMakeLists.txt b/Templates/CustomTool/Template/Code/CMakeLists.txt new file mode 100644 index 0000000000..f5cda477fc --- /dev/null +++ b/Templates/CustomTool/Template/Code/CMakeLists.txt @@ -0,0 +1,168 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Currently we are in the Code folder: ${CMAKE_CURRENT_LIST_DIR} +# Get the platform specific folder ${pal_dir} for the current folder: ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} +# Note: ly_get_list_relative_pal_filename will take care of the details for us, as this may be a restricted platform +# in which case it will see if that platform is present here or in the restricted folder. +# i.e. It could here in our gem : Gems/${Name}/Code/Platform/ or +# //Gems/${Name}/Code +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME} ${o3de_gem_restricted_path} ${o3de_gem_path} ${o3de_gem_name}) + +# Now that we have the platform abstraction layer (PAL) folder for this folder, thats where we will find the +# traits for this platform. Traits for a platform are defines for things like whether or not something in this gem +# is supported by this platform. +include(${pal_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) + +# Add the ${Name}.Static target +# Note: We include the common files and the platform specific files which are set in ${NameLower}_common_files.cmake +# and in ${pal_dir}/${NameLower}_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake +ly_add_target( + NAME ${Name}.Static STATIC + NAMESPACE Gem + FILES_CMAKE + ${NameLower}_files.cmake + ${pal_dir}/${NameLower}_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + INCLUDE_DIRECTORIES + PUBLIC + Include + PRIVATE + Source + BUILD_DEPENDENCIES + PUBLIC + AZ::AzCore + AZ::AzFramework +) + +# Here add ${Name} target, it depends on the ${Name}.Static +ly_add_target( + NAME ${Name} ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} + NAMESPACE Gem + FILES_CMAKE + ${NameLower}_shared_files.cmake + ${pal_dir}/${NameLower}_shared_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + INCLUDE_DIRECTORIES + PUBLIC + Include + PRIVATE + Source + BUILD_DEPENDENCIES + PRIVATE + Gem::${Name}.Static +) + +# By default, we will specify that the above target ${Name} would be used by +# Client and Server type targets when this gem is enabled. If you don't want it +# active in Clients or Servers by default, delete one of both of the following lines: +ly_create_alias(NAME ${Name}.Clients NAMESPACE Gem TARGETS Gem::${Name}) +ly_create_alias(NAME ${Name}.Servers NAMESPACE Gem TARGETS Gem::${Name}) + +# If we are on a host platform, we want to add the host tools targets like the ${Name}.Editor target which +# will also depend on ${Name}.Static +if(PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_target( + NAME ${Name}.Editor.Static STATIC + NAMESPACE Gem + AUTOMOC + AUTORCC + FILES_CMAKE + ${NameLower}_editor_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Source + PUBLIC + Include + BUILD_DEPENDENCIES + PUBLIC + AZ::AzToolsFramework + Gem::${Name}.Static + ) + + ly_add_target( + NAME ${Name}.Editor GEM_MODULE + NAMESPACE Gem + AUTOMOC + FILES_CMAKE + ${NameLower}_editor_shared_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Source + PUBLIC + Include + BUILD_DEPENDENCIES + PUBLIC + Gem::${Name}.Editor.Static + ) + + # By default, we will specify that the above target ${Name} would be used by + # Tool and Builder type targets when this gem is enabled. If you don't want it + # active in Tools or Builders by default, delete one of both of the following lines: + ly_create_alias(NAME ${Name}.Tools NAMESPACE Gem TARGETS Gem::${Name}.Editor) + ly_create_alias(NAME ${Name}.Builders NAMESPACE Gem TARGETS Gem::${Name}.Editor) + + +endif() + +################################################################################ +# Tests +################################################################################ +# See if globally, tests are supported +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + # We globally support tests, see if we support tests on this platform for ${Name}.Static + if(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED) + # We support ${Name}.Tests on this platform, add ${Name}.Tests target which depends on ${Name}.Static + ly_add_target( + NAME ${Name}.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + ${NameLower}_files.cmake + ${NameLower}_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + AZ::AzFramework + Gem::${Name}.Static + ) + + # Add ${Name}.Tests to googletest + ly_add_googletest( + NAME Gem::${Name}.Tests + ) + endif() + + # If we are a host platform we want to add tools test like editor tests here + if(PAL_TRAIT_BUILD_HOST_TOOLS) + # We are a host platform, see if Editor tests are supported on this platform + if(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED) + # We support ${Name}.Editor.Tests on this platform, add ${Name}.Editor.Tests target which depends on ${Name}.Editor + ly_add_target( + NAME ${Name}.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + ${NameLower}_editor_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + Gem::${Name}.Editor + ) + + # Add ${Name}.Editor.Tests to googletest + ly_add_googletest( + NAME Gem::${Name}.Editor.Tests + ) + endif() + endif() +endif() diff --git a/Templates/CustomTool/Template/Code/Include/${Name}/${Name}Bus.h b/Templates/CustomTool/Template/Code/Include/${Name}/${Name}Bus.h new file mode 100644 index 0000000000..d09bb2b009 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Include/${Name}/${Name}Bus.h @@ -0,0 +1,40 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#pragma once + +#include +#include + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}Requests + { + public: + AZ_RTTI(${SanitizedCppName}Requests, "{${Random_Uuid}}"); + virtual ~${SanitizedCppName}Requests() = default; + // Put your public methods here + }; + + class ${SanitizedCppName}BusTraits + : public AZ::EBusTraits + { + public: + ////////////////////////////////////////////////////////////////////////// + // EBusTraits overrides + static constexpr AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static constexpr AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + ////////////////////////////////////////////////////////////////////////// + }; + + using ${SanitizedCppName}RequestBus = AZ::EBus<${SanitizedCppName}Requests, ${SanitizedCppName}BusTraits>; + using ${SanitizedCppName}Interface = AZ::Interface<${SanitizedCppName}Requests>; + +} // namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_android_files.cmake b/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_android_files.cmake new file mode 100644 index 0000000000..5b6da14a20 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_android_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Android +# i.e. ../Source/Android/${Name}Android.cpp +# ../Source/Android/${Name}Android.h +# ../Include/Android/${Name}Android.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_shared_android_files.cmake b/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_shared_android_files.cmake new file mode 100644 index 0000000000..5b6da14a20 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Android/${NameLower}_shared_android_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Android +# i.e. ../Source/Android/${Name}Android.cpp +# ../Source/Android/${Name}Android.h +# ../Include/Android/${Name}Android.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake b/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake new file mode 100644 index 0000000000..49dfe71f53 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) diff --git a/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake b/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake new file mode 100644 index 0000000000..2f58a2e6f5 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_linux_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Linux +# i.e. ../Source/Linux/${Name}Linux.cpp +# ../Source/Linux/${Name}Linux.h +# ../Include/Linux/${Name}Linux.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_shared_linux_files.cmake b/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_shared_linux_files.cmake new file mode 100644 index 0000000000..2f58a2e6f5 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Linux/${NameLower}_shared_linux_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Linux +# i.e. ../Source/Linux/${Name}Linux.cpp +# ../Source/Linux/${Name}Linux.h +# ../Include/Linux/${Name}Linux.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Linux/PAL_linux.cmake b/Templates/CustomTool/Template/Code/Platform/Linux/PAL_linux.cmake new file mode 100644 index 0000000000..0abcd887e8 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Linux/PAL_linux.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) \ No newline at end of file diff --git a/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake b/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake new file mode 100644 index 0000000000..1cf737a2f1 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_mac_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Mac +# i.e. ../Source/Mac/${Name}Mac.cpp +# ../Source/Mac/${Name}Mac.h +# ../Include/Mac/${Name}Mac.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_shared_mac_files.cmake b/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_shared_mac_files.cmake new file mode 100644 index 0000000000..1cf737a2f1 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Mac/${NameLower}_shared_mac_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Mac +# i.e. ../Source/Mac/${Name}Mac.cpp +# ../Source/Mac/${Name}Mac.h +# ../Include/Mac/${Name}Mac.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Mac/PAL_mac.cmake b/Templates/CustomTool/Template/Code/Platform/Mac/PAL_mac.cmake new file mode 100644 index 0000000000..0abcd887e8 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Mac/PAL_mac.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) \ No newline at end of file diff --git a/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_shared_windows_files.cmake b/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_shared_windows_files.cmake new file mode 100644 index 0000000000..712aad1207 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_shared_windows_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Windows +# i.e. ../Source/Windows/${Name}Windows.cpp +# ../Source/Windows/${Name}Windows.h +# ../Include/Windows/${Name}Windows.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake b/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake new file mode 100644 index 0000000000..712aad1207 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Windows/${NameLower}_windows_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for Windows +# i.e. ../Source/Windows/${Name}Windows.cpp +# ../Source/Windows/${Name}Windows.h +# ../Include/Windows/${Name}Windows.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/Windows/PAL_windows.cmake b/Templates/CustomTool/Template/Code/Platform/Windows/PAL_windows.cmake new file mode 100644 index 0000000000..0abcd887e8 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/Windows/PAL_windows.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) \ No newline at end of file diff --git a/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake b/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake new file mode 100644 index 0000000000..61efde11c2 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_ios_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for iOS +# i.e. ../Source/iOS/${Name}iOS.cpp +# ../Source/iOS/${Name}iOS.h +# ../Include/iOS/${Name}iOS.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_shared_ios_files.cmake b/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_shared_ios_files.cmake new file mode 100644 index 0000000000..61efde11c2 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/iOS/${NameLower}_shared_ios_files.cmake @@ -0,0 +1,15 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +# Platform specific files for iOS +# i.e. ../Source/iOS/${Name}iOS.cpp +# ../Source/iOS/${Name}iOS.h +# ../Include/iOS/${Name}iOS.h + +set(FILES +) diff --git a/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake b/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake new file mode 100644 index 0000000000..0abcd887e8 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake @@ -0,0 +1,11 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + +set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) \ No newline at end of file diff --git a/Templates/CustomTool/Template/Code/Source/${Name}.qrc b/Templates/CustomTool/Template/Code/Source/${Name}.qrc new file mode 100644 index 0000000000..90d7695b88 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}.qrc @@ -0,0 +1,5 @@ + + + toolbar_icon.svg + + diff --git a/Templates/CustomTool/Template/Code/Source/${Name}EditorModule.cpp b/Templates/CustomTool/Template/Code/Source/${Name}EditorModule.cpp new file mode 100644 index 0000000000..0027af011a --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}EditorModule.cpp @@ -0,0 +1,55 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include <${Name}ModuleInterface.h> +#include <${Name}EditorSystemComponent.h> + +void Init${SanitizedCppName}Resources() +{ + // We must register our Qt resources (.qrc file) since this is being loaded from a separate module (gem) + Q_INIT_RESOURCE(${SanitizedCppName}); +} + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}EditorModule + : public ${SanitizedCppName}ModuleInterface + { + public: + AZ_RTTI(${SanitizedCppName}EditorModule, "${ModuleClassId}", ${SanitizedCppName}ModuleInterface); + AZ_CLASS_ALLOCATOR(${SanitizedCppName}EditorModule, AZ::SystemAllocator, 0); + + ${SanitizedCppName}EditorModule() + { + Init${SanitizedCppName}Resources(); + + // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. + // Add ALL components descriptors associated with this gem to m_descriptors. + // This will associate the AzTypeInfo information for the components with the the SerializeContext, BehaviorContext and EditContext. + // This happens through the [MyComponent]::Reflect() function. + m_descriptors.insert(m_descriptors.end(), { + ${SanitizedCppName}EditorSystemComponent::CreateDescriptor(), + }); + } + + /** + * Add required SystemComponents to the SystemEntity. + * Non-SystemComponents should not be added here + */ + AZ::ComponentTypeList GetRequiredSystemComponents() const override + { + return AZ::ComponentTypeList { + azrtti_typeid<${SanitizedCppName}EditorSystemComponent>(), + }; + } + }; +}// namespace ${SanitizedCppName} + +AZ_DECLARE_MODULE_CLASS(Gem_${SanitizedCppName}, ${SanitizedCppName}::${SanitizedCppName}EditorModule) diff --git a/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.cpp b/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.cpp new file mode 100644 index 0000000000..f12fa04929 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.cpp @@ -0,0 +1,78 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include + +#include + +#include <${Name}Widget.h> +#include <${Name}EditorSystemComponent.h> + +namespace ${SanitizedCppName} +{ + void ${SanitizedCppName}EditorSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class<${SanitizedCppName}EditorSystemComponent, ${SanitizedCppName}SystemComponent>() + ->Version(0); + } + } + + ${SanitizedCppName}EditorSystemComponent::${SanitizedCppName}EditorSystemComponent() = default; + + ${SanitizedCppName}EditorSystemComponent::~${SanitizedCppName}EditorSystemComponent() = default; + + void ${SanitizedCppName}EditorSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + BaseSystemComponent::GetProvidedServices(provided); + provided.push_back(AZ_CRC_CE("${SanitizedCppName}EditorService")); + } + + void ${SanitizedCppName}EditorSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + BaseSystemComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("${SanitizedCppName}EditorService")); + } + + void ${SanitizedCppName}EditorSystemComponent::GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required) + { + BaseSystemComponent::GetRequiredServices(required); + } + + void ${SanitizedCppName}EditorSystemComponent::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + BaseSystemComponent::GetDependentServices(dependent); + } + + void ${SanitizedCppName}EditorSystemComponent::Activate() + { + ${SanitizedCppName}SystemComponent::Activate(); + AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); + } + + void ${SanitizedCppName}EditorSystemComponent::Deactivate() + { + AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); + ${SanitizedCppName}SystemComponent::Deactivate(); + } + + void ${SanitizedCppName}EditorSystemComponent::NotifyRegisterViews() + { + AzToolsFramework::ViewPaneOptions options; + options.paneRect = QRect(100, 100, 500, 400); + options.showOnToolsToolbar = true; + options.toolbarIcon = ":/${Name}/toolbar_icon.svg"; + + // Register our custom widget as a dockable tool with the Editor + AzToolsFramework::RegisterViewPane<${SanitizedCppName}Widget>("${Name}", "Tools", options); + } + +} // namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.h b/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.h new file mode 100644 index 0000000000..bbeac97da3 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}EditorSystemComponent.h @@ -0,0 +1,45 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#pragma once + +#include <${Name}SystemComponent.h> + +#include + +namespace ${SanitizedCppName} +{ + /// System component for ${SanitizedCppName} editor + class ${SanitizedCppName}EditorSystemComponent + : public ${SanitizedCppName}SystemComponent + , private AzToolsFramework::EditorEvents::Bus::Handler + { + using BaseSystemComponent = ${SanitizedCppName}SystemComponent; + public: + AZ_COMPONENT(${SanitizedCppName}EditorSystemComponent, "${EditorSysCompClassId}", BaseSystemComponent); + static void Reflect(AZ::ReflectContext* context); + + ${SanitizedCppName}EditorSystemComponent(); + ~${SanitizedCppName}EditorSystemComponent(); + + private: + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + // AZ::Component + void Activate() override; + void Deactivate() override; + + // AzToolsFramework::EditorEventsBus overrides ... + void NotifyRegisterViews() override; + }; +} // namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Source/${Name}Module.cpp b/Templates/CustomTool/Template/Code/Source/${Name}Module.cpp new file mode 100644 index 0000000000..0a6e8bde3c --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}Module.cpp @@ -0,0 +1,25 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include <${Name}ModuleInterface.h> +#include <${Name}SystemComponent.h> + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}Module + : public ${SanitizedCppName}ModuleInterface + { + public: + AZ_RTTI(${SanitizedCppName}Module, "${ModuleClassId}", ${SanitizedCppName}ModuleInterface); + AZ_CLASS_ALLOCATOR(${SanitizedCppName}Module, AZ::SystemAllocator, 0); + }; +}// namespace ${SanitizedCppName} + +AZ_DECLARE_MODULE_CLASS(Gem_${SanitizedCppName}, ${SanitizedCppName}::${SanitizedCppName}Module) diff --git a/Templates/CustomTool/Template/Code/Source/${Name}ModuleInterface.h b/Templates/CustomTool/Template/Code/Source/${Name}ModuleInterface.h new file mode 100644 index 0000000000..925632491a --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}ModuleInterface.h @@ -0,0 +1,45 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include +#include +#include <${Name}SystemComponent.h> + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}ModuleInterface + : public AZ::Module + { + public: + AZ_RTTI(${SanitizedCppName}ModuleInterface, "{${Random_Uuid}}", AZ::Module); + AZ_CLASS_ALLOCATOR(${SanitizedCppName}ModuleInterface, AZ::SystemAllocator, 0); + + ${SanitizedCppName}ModuleInterface() + { + // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. + // Add ALL components descriptors associated with this gem to m_descriptors. + // This will associate the AzTypeInfo information for the components with the the SerializeContext, BehaviorContext and EditContext. + // This happens through the [MyComponent]::Reflect() function. + m_descriptors.insert(m_descriptors.end(), { + ${SanitizedCppName}SystemComponent::CreateDescriptor(), + }); + } + + /** + * Add required SystemComponents to the SystemEntity. + */ + AZ::ComponentTypeList GetRequiredSystemComponents() const override + { + return AZ::ComponentTypeList{ + azrtti_typeid<${SanitizedCppName}SystemComponent>(), + }; + } + }; +}// namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.cpp b/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.cpp new file mode 100644 index 0000000000..cb4d58418e --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.cpp @@ -0,0 +1,92 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include <${Name}SystemComponent.h> + +#include +#include +#include + +namespace ${SanitizedCppName} +{ + void ${SanitizedCppName}SystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class<${SanitizedCppName}SystemComponent, AZ::Component>() + ->Version(0) + ; + + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class<${SanitizedCppName}SystemComponent>("${SanitizedCppName}", "[Description of functionality provided by this System Component]") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System")) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + } + } + } + + void ${SanitizedCppName}SystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("${SanitizedCppName}Service")); + } + + void ${SanitizedCppName}SystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("${SanitizedCppName}Service")); + } + + void ${SanitizedCppName}SystemComponent::GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required) + { + } + + void ${SanitizedCppName}SystemComponent::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + } + + ${SanitizedCppName}SystemComponent::${SanitizedCppName}SystemComponent() + { + if (${SanitizedCppName}Interface::Get() == nullptr) + { + ${SanitizedCppName}Interface::Register(this); + } + } + + ${SanitizedCppName}SystemComponent::~${SanitizedCppName}SystemComponent() + { + if (${SanitizedCppName}Interface::Get() == this) + { + ${SanitizedCppName}Interface::Unregister(this); + } + } + + void ${SanitizedCppName}SystemComponent::Init() + { + } + + void ${SanitizedCppName}SystemComponent::Activate() + { + ${SanitizedCppName}RequestBus::Handler::BusConnect(); + AZ::TickBus::Handler::BusConnect(); + } + + void ${SanitizedCppName}SystemComponent::Deactivate() + { + AZ::TickBus::Handler::BusDisconnect(); + ${SanitizedCppName}RequestBus::Handler::BusDisconnect(); + } + + void ${SanitizedCppName}SystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + } + +} // namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.h b/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.h new file mode 100644 index 0000000000..5495d18e48 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}SystemComponent.h @@ -0,0 +1,56 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#pragma once + +#include +#include +#include <${Name}/${Name}Bus.h> + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}SystemComponent + : public AZ::Component + , protected ${SanitizedCppName}RequestBus::Handler + , public AZ::TickBus::Handler + { + public: + AZ_COMPONENT(${SanitizedCppName}SystemComponent, "${SysCompClassId}"); + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + ${SanitizedCppName}SystemComponent(); + ~${SanitizedCppName}SystemComponent(); + + protected: + //////////////////////////////////////////////////////////////////////// + // ${SanitizedCppName}RequestBus interface implementation + + //////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Init() override; + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // AZTickBus interface implementation + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + //////////////////////////////////////////////////////////////////////// + }; + +} // namespace ${SanitizedCppName} diff --git a/Templates/CustomTool/Template/Code/Source/${Name}Widget.cpp b/Templates/CustomTool/Template/Code/Source/${Name}Widget.cpp new file mode 100644 index 0000000000..bd6dd6c86a --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}Widget.cpp @@ -0,0 +1,44 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include + +#include +#include + +#include <${Name}Widget.h> + +namespace ${SanitizedCppName} +{ + ${SanitizedCppName}Widget::${SanitizedCppName}Widget(QWidget* parent) + : QWidget(parent) + { + setWindowTitle(QObject::tr("${Name}")); + + QVBoxLayout* mainLayout = new QVBoxLayout(this); + + QLabel* introLabel = new QLabel(QObject::tr("Put your cool stuff here!"), this); + mainLayout->addWidget(introLabel, 0, Qt::AlignCenter); + + QString helpText = QString( + "For help getting started, visit the UI Development documentation
or come ask a question in the sig-ui-ux channel on Discord"); + + QLabel* helpLabel = new QLabel(this); + helpLabel->setTextFormat(Qt::RichText); + helpLabel->setText(helpText); + helpLabel->setOpenExternalLinks(true); + + mainLayout->addWidget(helpLabel, 0, Qt::AlignCenter); + + setLayout(mainLayout); + } +} + +#include diff --git a/Templates/CustomTool/Template/Code/Source/${Name}Widget.h b/Templates/CustomTool/Template/Code/Source/${Name}Widget.h new file mode 100644 index 0000000000..4d0c86d043 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/${Name}Widget.h @@ -0,0 +1,28 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#pragma once + +#if !defined(Q_MOC_RUN) +#include + +#include +#endif + +namespace ${SanitizedCppName} +{ + class ${SanitizedCppName}Widget + : public QWidget + { + Q_OBJECT + public: + explicit ${SanitizedCppName}Widget(QWidget* parent = nullptr); + }; +} diff --git a/Templates/CustomTool/Template/Code/Source/toolbar_icon.svg b/Templates/CustomTool/Template/Code/Source/toolbar_icon.svg new file mode 100644 index 0000000000..59de66961c --- /dev/null +++ b/Templates/CustomTool/Template/Code/Source/toolbar_icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Templates/CustomTool/Template/Code/Tests/${Name}EditorTest.cpp b/Templates/CustomTool/Template/Code/Tests/${Name}EditorTest.cpp new file mode 100644 index 0000000000..9b84575fa0 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Tests/${Name}EditorTest.cpp @@ -0,0 +1,13 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Templates/CustomTool/Template/Code/Tests/${Name}Test.cpp b/Templates/CustomTool/Template/Code/Tests/${Name}Test.cpp new file mode 100644 index 0000000000..9b84575fa0 --- /dev/null +++ b/Templates/CustomTool/Template/Code/Tests/${Name}Test.cpp @@ -0,0 +1,13 @@ +// {BEGIN_LICENSE} +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +// {END_LICENSE} + +#include + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Templates/CustomTool/Template/Platform/Android/android_gem.cmake b/Templates/CustomTool/Template/Platform/Android/android_gem.cmake new file mode 100644 index 0000000000..063b3be9ac --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Android/android_gem.cmake @@ -0,0 +1,8 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + diff --git a/Templates/CustomTool/Template/Platform/Android/android_gem.json b/Templates/CustomTool/Template/Platform/Android/android_gem.json new file mode 100644 index 0000000000..23bbb28e66 --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Android/android_gem.json @@ -0,0 +1,3 @@ +{ + "Tags": ["Android"], +} \ No newline at end of file diff --git a/Templates/CustomTool/Template/Platform/Linux/linux_gem.cmake b/Templates/CustomTool/Template/Platform/Linux/linux_gem.cmake new file mode 100644 index 0000000000..063b3be9ac --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Linux/linux_gem.cmake @@ -0,0 +1,8 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + diff --git a/Templates/CustomTool/Template/Platform/Linux/linux_gem.json b/Templates/CustomTool/Template/Platform/Linux/linux_gem.json new file mode 100644 index 0000000000..d08fbf53ba --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Linux/linux_gem.json @@ -0,0 +1,3 @@ +{ + "Tags": ["Linux"] +} \ No newline at end of file diff --git a/Templates/CustomTool/Template/Platform/Mac/mac_gem.cmake b/Templates/CustomTool/Template/Platform/Mac/mac_gem.cmake new file mode 100644 index 0000000000..063b3be9ac --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Mac/mac_gem.cmake @@ -0,0 +1,8 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + diff --git a/Templates/CustomTool/Template/Platform/Mac/mac_gem.json b/Templates/CustomTool/Template/Platform/Mac/mac_gem.json new file mode 100644 index 0000000000..d42b6f8186 --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Mac/mac_gem.json @@ -0,0 +1,3 @@ +{ + "Tags": ["Mac"] +} \ No newline at end of file diff --git a/Templates/CustomTool/Template/Platform/Windows/windows_gem.cmake b/Templates/CustomTool/Template/Platform/Windows/windows_gem.cmake new file mode 100644 index 0000000000..063b3be9ac --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Windows/windows_gem.cmake @@ -0,0 +1,8 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + diff --git a/Templates/CustomTool/Template/Platform/Windows/windows_gem.json b/Templates/CustomTool/Template/Platform/Windows/windows_gem.json new file mode 100644 index 0000000000..a052f1e05a --- /dev/null +++ b/Templates/CustomTool/Template/Platform/Windows/windows_gem.json @@ -0,0 +1,3 @@ +{ + "Tags": ["Windows"] +} \ No newline at end of file diff --git a/Templates/CustomTool/Template/Platform/iOS/ios_gem.cmake b/Templates/CustomTool/Template/Platform/iOS/ios_gem.cmake new file mode 100644 index 0000000000..063b3be9ac --- /dev/null +++ b/Templates/CustomTool/Template/Platform/iOS/ios_gem.cmake @@ -0,0 +1,8 @@ +# {BEGIN_LICENSE} +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# {END_LICENSE} + diff --git a/Templates/CustomTool/Template/Platform/iOS/ios_gem.json b/Templates/CustomTool/Template/Platform/iOS/ios_gem.json new file mode 100644 index 0000000000..b2dab56d05 --- /dev/null +++ b/Templates/CustomTool/Template/Platform/iOS/ios_gem.json @@ -0,0 +1,3 @@ +{ + "Tags": ["iOS"] +} \ No newline at end of file diff --git a/Templates/CustomTool/Template/gem.json b/Templates/CustomTool/Template/gem.json new file mode 100644 index 0000000000..518d831e0f --- /dev/null +++ b/Templates/CustomTool/Template/gem.json @@ -0,0 +1,17 @@ +{ + "gem_name": "${Name}", + "display_name": "${Name}", + "license": "What license ${Name} uses goes here: i.e. https://opensource.org/licenses/MIT", + "origin": "The primary repo for ${Name} goes here: i.e. http://www.mydomain.com", + "type": "Code", + "summary": "A short description of ${Name}.", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "${Name}" + ], + "icon_path": "preview.png", + "requirements": "", + "restricted_name": "gems" +} diff --git a/Templates/CustomTool/Template/preview.png b/Templates/CustomTool/Template/preview.png new file mode 100644 index 0000000000..0f393ac886 --- /dev/null +++ b/Templates/CustomTool/Template/preview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ac9dd09bde78f389e3725ac49d61eff109857e004840bc0bc3881739df9618d +size 2217 diff --git a/Templates/CustomTool/template.json b/Templates/CustomTool/template.json new file mode 100644 index 0000000000..e3221db106 --- /dev/null +++ b/Templates/CustomTool/template.json @@ -0,0 +1,382 @@ +{ + "template_name": "CustomTool", + "origin": "The primary repo for CustomTool goes here: i.e. http://www.mydomain.com", + "license": "What license CustomTool uses goes here: i.e. https://opensource.org/licenses/MIT", + "display_name": "CustomTool", + "summary": "A gem template for a custom tool in C++ that gets registered with the Editor.", + "canonical_tags": [], + "user_tags": [ + "CustomTool" + ], + "icon_path": "preview.png", + "copyFiles": [ + { + "file": "CMakeLists.txt", + "origin": "CMakeLists.txt", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Code/${NameLower}_editor_files.cmake", + "origin": "Code/${NameLower}_editor_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/${NameLower}_editor_shared_files.cmake", + "origin": "Code/${NameLower}_editor_shared_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/${NameLower}_editor_tests_files.cmake", + "origin": "Code/${NameLower}_editor_tests_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/${NameLower}_files.cmake", + "origin": "Code/${NameLower}_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/${NameLower}_shared_files.cmake", + "origin": "Code/${NameLower}_shared_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/${NameLower}_tests_files.cmake", + "origin": "Code/${NameLower}_tests_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/CMakeLists.txt", + "origin": "Code/CMakeLists.txt", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Include/${Name}/${Name}Bus.h", + "origin": "Code/Include/${Name}/${Name}Bus.h", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Android/${NameLower}_android_files.cmake", + "origin": "Code/Platform/Android/${NameLower}_android_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Android/${NameLower}_shared_android_files.cmake", + "origin": "Code/Platform/Android/${NameLower}_shared_android_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Android/PAL_android.cmake", + "origin": "Code/Platform/Android/PAL_android.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Linux/${NameLower}_linux_files.cmake", + "origin": "Code/Platform/Linux/${NameLower}_linux_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Linux/${NameLower}_shared_linux_files.cmake", + "origin": "Code/Platform/Linux/${NameLower}_shared_linux_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Linux/PAL_linux.cmake", + "origin": "Code/Platform/Linux/PAL_linux.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Mac/${NameLower}_mac_files.cmake", + "origin": "Code/Platform/Mac/${NameLower}_mac_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Mac/${NameLower}_shared_mac_files.cmake", + "origin": "Code/Platform/Mac/${NameLower}_shared_mac_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Mac/PAL_mac.cmake", + "origin": "Code/Platform/Mac/PAL_mac.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Windows/${NameLower}_shared_windows_files.cmake", + "origin": "Code/Platform/Windows/${NameLower}_shared_windows_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Windows/${NameLower}_windows_files.cmake", + "origin": "Code/Platform/Windows/${NameLower}_windows_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/Windows/PAL_windows.cmake", + "origin": "Code/Platform/Windows/PAL_windows.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/iOS/${NameLower}_ios_files.cmake", + "origin": "Code/Platform/iOS/${NameLower}_ios_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/iOS/${NameLower}_shared_ios_files.cmake", + "origin": "Code/Platform/iOS/${NameLower}_shared_ios_files.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Platform/iOS/PAL_ios.cmake", + "origin": "Code/Platform/iOS/PAL_ios.cmake", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}.qrc", + "origin": "Code/Source/${Name}.qrc", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}EditorModule.cpp", + "origin": "Code/Source/${Name}EditorModule.cpp", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}EditorSystemComponent.cpp", + "origin": "Code/Source/${Name}EditorSystemComponent.cpp", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}EditorSystemComponent.h", + "origin": "Code/Source/${Name}EditorSystemComponent.h", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}Module.cpp", + "origin": "Code/Source/${Name}Module.cpp", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}ModuleInterface.h", + "origin": "Code/Source/${Name}ModuleInterface.h", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}SystemComponent.cpp", + "origin": "Code/Source/${Name}SystemComponent.cpp", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}SystemComponent.h", + "origin": "Code/Source/${Name}SystemComponent.h", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}Widget.cpp", + "origin": "Code/Source/${Name}Widget.cpp", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/${Name}Widget.h", + "origin": "Code/Source/${Name}Widget.h", + "isTemplated": true, + "isOptional": false + }, + { + "file": "Code/Source/toolbar_icon.svg", + "origin": "Code/Source/toolbar_icon.svg", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Code/Tests/${Name}EditorTest.cpp", + "origin": "Code/Tests/${Name}EditorTest.cpp", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Code/Tests/${Name}Test.cpp", + "origin": "Code/Tests/${Name}Test.cpp", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Android/android_gem.cmake", + "origin": "Platform/Android/android_gem.cmake", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Android/android_gem.json", + "origin": "Platform/Android/android_gem.json", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Linux/linux_gem.cmake", + "origin": "Platform/Linux/linux_gem.cmake", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Linux/linux_gem.json", + "origin": "Platform/Linux/linux_gem.json", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Mac/mac_gem.cmake", + "origin": "Platform/Mac/mac_gem.cmake", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Mac/mac_gem.json", + "origin": "Platform/Mac/mac_gem.json", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Windows/windows_gem.cmake", + "origin": "Platform/Windows/windows_gem.cmake", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/Windows/windows_gem.json", + "origin": "Platform/Windows/windows_gem.json", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/iOS/ios_gem.cmake", + "origin": "Platform/iOS/ios_gem.cmake", + "isTemplated": false, + "isOptional": false + }, + { + "file": "Platform/iOS/ios_gem.json", + "origin": "Platform/iOS/ios_gem.json", + "isTemplated": false, + "isOptional": false + }, + { + "file": "gem.json", + "origin": "gem.json", + "isTemplated": true, + "isOptional": false + }, + { + "file": "preview.png", + "origin": "preview.png", + "isTemplated": false, + "isOptional": false + } + ], + "createDirectories": [ + { + "dir": "Assets", + "origin": "Assets" + }, + { + "dir": "Code", + "origin": "Code" + }, + { + "dir": "Code/Include", + "origin": "Code/Include" + }, + { + "dir": "Code/Include/${Name}", + "origin": "Code/Include/${Name}" + }, + { + "dir": "Code/Platform", + "origin": "Code/Platform" + }, + { + "dir": "Code/Platform/Android", + "origin": "Code/Platform/Android" + }, + { + "dir": "Code/Platform/Linux", + "origin": "Code/Platform/Linux" + }, + { + "dir": "Code/Platform/Mac", + "origin": "Code/Platform/Mac" + }, + { + "dir": "Code/Platform/Windows", + "origin": "Code/Platform/Windows" + }, + { + "dir": "Code/Platform/iOS", + "origin": "Code/Platform/iOS" + }, + { + "dir": "Code/Source", + "origin": "Code/Source" + }, + { + "dir": "Code/Tests", + "origin": "Code/Tests" + }, + { + "dir": "Platform", + "origin": "Platform" + }, + { + "dir": "Platform/Android", + "origin": "Platform/Android" + }, + { + "dir": "Platform/Linux", + "origin": "Platform/Linux" + }, + { + "dir": "Platform/Mac", + "origin": "Platform/Mac" + }, + { + "dir": "Platform/Windows", + "origin": "Platform/Windows" + }, + { + "dir": "Platform/iOS", + "origin": "Platform/iOS" + } + ] +} diff --git a/engine.json b/engine.json index 2b56e255fc..3d522ce175 100644 --- a/engine.json +++ b/engine.json @@ -92,6 +92,7 @@ "templates": [ "Templates/AssetGem", "Templates/DefaultGem", + "Templates/CustomTool", "Templates/DefaultProject", "Templates/MinimalProject" ] From 66c25f3a029fd675002c695213a6056126e2cedd Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Wed, 13 Oct 2021 20:36:15 -0500 Subject: [PATCH 29/52] Making sure that all capture requests are cleaned up before the preview renderer gets destroyed A request was captured and held onto to by a lambda that was not getting cleared before the system was destroyed This caused an entity to be destroyed late, accessing the culling system that was already torn down Solution is to only store the success and failure callbacks inside of the attachment pass read back callback lambda so the rest of the content can be released Signed-off-by: Guthrie Adams --- .../PreviewRenderer/PreviewRenderer.cpp | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index 2a6991dc46..6e47360a84 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -96,7 +96,6 @@ namespace AtomToolsFramework AZ::RPI::RPISystemInterface::Get()->UnregisterScene(m_scene); m_frameworkScene->UnsetSubsystem(m_scene); m_frameworkScene->UnsetSubsystem(m_entityContext.get()); - m_entityContext->DestroyContext(); } void PreviewRenderer::AddCaptureRequest(const CaptureRequest& captureRequest) @@ -134,7 +133,10 @@ namespace AtomToolsFramework void PreviewRenderer::CancelCaptureRequest() { - m_currentCaptureRequest.m_captureFailedCallback(); + if (m_currentCaptureRequest.m_captureFailedCallback) + { + m_currentCaptureRequest.m_captureFailedCallback(); + } m_state.reset(); m_state.reset(new PreviewRendererIdleState(this)); } @@ -179,17 +181,25 @@ namespace AtomToolsFramework bool PreviewRenderer::StartCapture() { - auto captureCallback = [currentCaptureRequest = m_currentCaptureRequest](const AZ::RPI::AttachmentReadback::ReadbackResult& result) + auto captureCompleteCallback = m_currentCaptureRequest.m_captureCompleteCallback; + auto captureFailedCallback = m_currentCaptureRequest.m_captureFailedCallback; + auto captureCallback = [captureCompleteCallback, captureFailedCallback](const AZ::RPI::AttachmentReadback::ReadbackResult& result) { if (result.m_dataBuffer) { - currentCaptureRequest.m_captureCompleteCallback(QPixmap::fromImage(QImage( - result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, result.m_imageDescriptor.m_size.m_height, - QImage::Format_RGBA8888))); + if (captureCompleteCallback) + { + captureCompleteCallback(QPixmap::fromImage(QImage( + result.m_dataBuffer.get()->data(), result.m_imageDescriptor.m_size.m_width, + result.m_imageDescriptor.m_size.m_height, QImage::Format_RGBA8888))); + } } else { - currentCaptureRequest.m_captureFailedCallback(); + if (captureFailedCallback) + { + captureFailedCallback(); + } } }; @@ -209,6 +219,7 @@ namespace AtomToolsFramework void PreviewRenderer::EndCapture() { + m_currentCaptureRequest = {}; m_renderPipeline->RemoveFromRenderTick(); } From 5a204dc80b65c322be7fb038cd9c5783cadf4533 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Wed, 13 Oct 2021 21:26:03 -0700 Subject: [PATCH 30/52] chore: remove equality from boolean expression Signed-off-by: Michael Pollind --- .../AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp | 2 +- Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp | 2 +- Gems/LmbrCentral/Code/Source/Shape/DiskShape.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp index 3a7fffb3be..4c7afa2275 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Picking/Manipulators/ManipulatorBounds.cpp @@ -116,7 +116,7 @@ namespace AzToolsFramework { return AZ::Intersect::IntersectRayBox( rayOrigin, rayDirection, m_center, m_axis1, m_axis2, m_axis3, m_halfExtents.GetX(), m_halfExtents.GetY(), - m_halfExtents.GetZ(), rayIntersectionDistance) > 0; + m_halfExtents.GetZ(), rayIntersectionDistance); } void ManipulatorBoundBox::SetShapeData(const BoundRequestShapeBase& shapeData) diff --git a/Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp b/Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp index a776a01ccc..4f6089ba16 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp @@ -166,7 +166,7 @@ namespace LmbrCentral return intersection; } - const bool intersection = AZ::Intersect::IntersectRayObb(src, dir, m_intersectionDataCache.m_obb, distance) > 0; + const bool intersection = AZ::Intersect::IntersectRayObb(src, dir, m_intersectionDataCache.m_obb, distance); return intersection; } diff --git a/Gems/LmbrCentral/Code/Source/Shape/DiskShape.cpp b/Gems/LmbrCentral/Code/Source/Shape/DiskShape.cpp index 8eaf03457f..1c4a94ced3 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/DiskShape.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/DiskShape.cpp @@ -153,7 +153,7 @@ namespace LmbrCentral m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_diskShapeConfig); return AZ::Intersect::IntersectRayDisk( - src, dir, m_intersectionDataCache.m_position, m_intersectionDataCache.m_radius, m_intersectionDataCache.m_normal, distance) > 0; + src, dir, m_intersectionDataCache.m_position, m_intersectionDataCache.m_radius, m_intersectionDataCache.m_normal, distance); } void DiskShape::DiskIntersectionDataCache::UpdateIntersectionParamsImpl( From ec10bb078e1e21f5a749f55c33c5a05758cb53be Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 14 Oct 2021 16:06:13 +0100 Subject: [PATCH 31/52] improve wording for all PhysX gem tooltips apart from pipeline, fixes 3898 Signed-off-by: greerdv --- Gems/PhysX/Code/Editor/DebugDraw.cpp | 6 +- .../Code/Editor/EditorJointConfiguration.cpp | 52 +++++++++------- .../Configuration/PhysXConfiguration.cpp | 10 ++-- .../Configuration/PhysXDebugConfiguration.cpp | 25 ++++---- .../Code/Source/EditorBallJointComponent.cpp | 6 +- .../Code/Source/EditorColliderComponent.cpp | 30 +++++----- .../Code/Source/EditorFixedJointComponent.cpp | 5 +- .../Source/EditorForceRegionComponent.cpp | 9 +-- .../Code/Source/EditorHingeJointComponent.cpp | 6 +- .../Code/Source/EditorJointComponent.cpp | 4 +- .../Code/Source/EditorRigidBodyComponent.cpp | 59 ++++++++++--------- .../Source/EditorShapeColliderComponent.cpp | 9 +-- Gems/PhysX/Code/Source/ForceRegion.cpp | 4 +- Gems/PhysX/Code/Source/ForceRegionForces.cpp | 39 ++++++------ .../Configuration/PhysXJointConfiguration.cpp | 8 +-- .../API/CharacterController.cpp | 6 +- .../Components/CharacterGameplayComponent.cpp | 2 +- .../EditorCharacterControllerComponent.cpp | 15 ++--- .../EditorCharacterGameplayComponent.cpp | 4 +- .../Components/RagdollComponent.cpp | 20 ++++--- Gems/PhysX/Code/Source/SystemComponent.cpp | 2 +- 21 files changed, 174 insertions(+), 147 deletions(-) diff --git a/Gems/PhysX/Code/Editor/DebugDraw.cpp b/Gems/PhysX/Code/Editor/DebugDraw.cpp index 440b198675..5936312ecf 100644 --- a/Gems/PhysX/Code/Editor/DebugDraw.cpp +++ b/Gems/PhysX/Code/Editor/DebugDraw.cpp @@ -148,16 +148,16 @@ namespace PhysX using VisibilityFunc = bool(*)(); editContext->Class( - "PhysX Collider Debug Draw", "Manages global and per-collider debug draw settings and logic") + "PhysX Collider Debug Draw", "Global and per-collider debug draw preferences.") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Collider::m_locallyEnabled, "Draw collider", - "Shows the geometry for the collider in the viewport") + "Display collider geometry in the viewport.") ->Attribute(AZ::Edit::Attributes::CheckboxTooltip, "If set, the geometry of this collider is visible in the viewport. 'Draw Helpers' needs to be enabled to use.") ->Attribute(AZ::Edit::Attributes::Visibility, VisibilityFunc{ []() { return IsGlobalColliderDebugCheck(GlobalCollisionDebugState::Manual); } }) ->Attribute(AZ::Edit::Attributes::ReadOnly, &IsDrawColliderReadOnly) ->DataElement(AZ::Edit::UIHandlers::Button, &Collider::m_globalButtonState, "Draw collider", - "Shows the geometry for the collider in the viewport") + "Display collider geometry in the viewport.") ->Attribute(AZ::Edit::Attributes::ButtonText, "Global override") ->Attribute(AZ::Edit::Attributes::ButtonTooltip, "A global setting is overriding this property (to disable the override, " diff --git a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp index b9ed827ce0..ee3988ded4 100644 --- a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp +++ b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp @@ -51,23 +51,27 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "Editor Joint Limit Config Base", "Base joint limit parameters") + "Editor Joint Limit Config Base", "Base joint limit parameters.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(0, &PhysX::EditorJointLimitConfig::m_isLimited, "Limit", "True if the motion about the unconstrained axes of this joint are limited") + ->DataElement(0, &PhysX::EditorJointLimitConfig::m_isLimited, "Limit", + "When active, the joint's degrees of freedom are limited.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->Attribute(AZ::Edit::Attributes::ReadOnly, &EditorJointLimitConfig::IsInComponentMode) - ->DataElement(0, &PhysX::EditorJointLimitConfig::m_isSoftLimit, "Soft limit", "True if the joint is allowed to rotate beyond limits and spring back") + ->DataElement(0, &PhysX::EditorJointLimitConfig::m_isSoftLimit, "Soft limit", + "When active, motion beyond the joint limit with a spring-like return is allowed.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConfig::m_isLimited) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->Attribute(AZ::Edit::Attributes::ReadOnly, &EditorJointLimitConfig::IsInComponentMode) - ->DataElement(0, &PhysX::EditorJointLimitConfig::m_damping, "Damping", "The damping strength of the drive, the force proportional to the velocity error") + ->DataElement(0, &PhysX::EditorJointLimitConfig::m_damping, "Damping", + "Dissipation of energy and reduction in spring oscillations when outside the joint limit.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConfig::IsSoftLimited) ->Attribute(AZ::Edit::Attributes::Max, s_springMax) ->Attribute(AZ::Edit::Attributes::Min, s_springMin) - ->DataElement(0, &PhysX::EditorJointLimitConfig::m_stiffness, "Stiffness", "The spring strength of the drive, the force proportional to the position error") + ->DataElement(0, &PhysX::EditorJointLimitConfig::m_stiffness, "Stiffness", + "The spring's drive relative to the position of the follower when outside the rotation limit.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConfig::IsSoftLimited) ->Attribute(AZ::Edit::Attributes::Max, s_springMax) ->Attribute(AZ::Edit::Attributes::Min, s_springMin) @@ -115,18 +119,20 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "Angular Limit", "Rotation limitation") + "Angular Limit", "Rotation limitation.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(0, &PhysX::EditorJointLimitPairConfig::m_standardLimitConfig , "Standard limit configuration" - , "Common limit parameters to all joint types") - ->DataElement(0, &PhysX::EditorJointLimitPairConfig::m_limitPositive, "Positive angular limit", "Positive rotation angle") + , "Common limit parameters to all joint types.") + ->DataElement(0, &PhysX::EditorJointLimitPairConfig::m_limitPositive, "Positive angular limit", + "Positive rotation angle.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitPairConfig::IsLimited) ->Attribute(AZ::Edit::Attributes::Max, s_angleMax) ->Attribute(AZ::Edit::Attributes::Min, s_angleMin) - ->DataElement(0, &PhysX::EditorJointLimitPairConfig::m_limitNegative, "Negative angular limit", "Negative rotation angle") + ->DataElement(0, &PhysX::EditorJointLimitPairConfig::m_limitNegative, "Negative angular limit", + "Negative rotation angle.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitPairConfig::IsLimited) ->Attribute(AZ::Edit::Attributes::Max, s_angleMin) ->Attribute(AZ::Edit::Attributes::Min, -s_angleMax) @@ -164,18 +170,20 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "Angular Limit", "Rotation limitation") + "Angular Limit", "Rotation limitation.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(0, &PhysX::EditorJointLimitConeConfig::m_standardLimitConfig , "Standard limit configuration" - , "Common limit parameters to all joint types") - ->DataElement(0, &PhysX::EditorJointLimitConeConfig::m_limitY, "Y axis angular limit", "Limit for swing angle about Y axis") + , "Common limit parameters to all joint types.") + ->DataElement(0, &PhysX::EditorJointLimitConeConfig::m_limitY, "Y axis angular limit", + "Limit for swing angle about Y axis.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConeConfig::IsLimited) ->Attribute(AZ::Edit::Attributes::Max, s_angleMax) ->Attribute(AZ::Edit::Attributes::Min, s_angleMin) - ->DataElement(0, &PhysX::EditorJointLimitConeConfig::m_limitZ, "Z axis angular limit", "Limit for swing angle about Z axis") + ->DataElement(0, &PhysX::EditorJointLimitConeConfig::m_limitZ, "Z axis angular limit", + "Limit for swing angle about Z axis.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConeConfig::IsLimited) ->Attribute(AZ::Edit::Attributes::Max, s_angleMax) ->Attribute(AZ::Edit::Attributes::Min, s_angleMin) @@ -226,33 +234,33 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(0, &PhysX::EditorJointConfig::m_localPosition, "Local Position" - , "Local Position of joint, relative to its entity") + , "Local Position of joint, relative to its entity.") ->DataElement(0, &PhysX::EditorJointConfig::m_localRotation, "Local Rotation" - , "Local Rotation of joint, relative to its entity") + , "Local Rotation of joint, relative to its entity.") ->Attribute(AZ::Edit::Attributes::Min, LocalRotationMin) ->Attribute(AZ::Edit::Attributes::Max, LocalRotationMax) ->DataElement(0, &PhysX::EditorJointConfig::m_leadEntity, "Lead Entity" - , "Parent entity associated with joint") + , "Parent entity associated with joint.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorJointConfig::ValidateLeadEntityId) ->DataElement(0, &PhysX::EditorJointConfig::m_selfCollide, "Lead-Follower Collide" - , "Lead and follower pair will collide with each other") + , "When active, the lead and follower pair will collide with each other.") ->DataElement(0, &PhysX::EditorJointConfig::m_displayJointSetup, "Display Setup in Viewport" - , "Display joint setup in the viewport") + , "Display joint setup in the viewport.") ->Attribute(AZ::Edit::Attributes::ReadOnly, &EditorJointConfig::IsInComponentMode) ->DataElement(0, &PhysX::EditorJointConfig::m_selectLeadOnSnap, "Select Lead on Snap" - , "Select lead entity on snap to position in component mode") + , "Select lead entity on snap to position in component mode.") ->DataElement(0, &PhysX::EditorJointConfig::m_breakable , "Breakable" - , "Joint is breakable when force or torque exceeds limit") + , "Joint is breakable when force or torque exceeds limit.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->Attribute(AZ::Edit::Attributes::ReadOnly, &EditorJointConfig::IsInComponentMode) ->DataElement(0, &PhysX::EditorJointConfig::m_forceMax, - "Maximum Force", "Amount of force joint can withstand before breakage") + "Maximum Force", "Amount of force joint can withstand before breakage.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointConfig::m_breakable) ->Attribute(AZ::Edit::Attributes::Max, s_breakageMax) ->Attribute(AZ::Edit::Attributes::Min, s_breakageMin) ->DataElement(0, &PhysX::EditorJointConfig::m_torqueMax, - "Maximum Torque", "Amount of torque joint can withstand before breakage") + "Maximum Torque", "Amount of torque joint can withstand before breakage.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointConfig::m_breakable) ->Attribute(AZ::Edit::Attributes::Max, s_breakageMax) ->Attribute(AZ::Edit::Attributes::Min, s_breakageMin) diff --git a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp index 7a441a1c55..02f0bc038a 100644 --- a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp +++ b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp @@ -54,17 +54,17 @@ namespace PhysX if (AZ::EditContext* editContext = serialize->GetEditContext()) { - editContext->Class("Wind Configuration", "Wind settings for PhysX") + editContext->Class("Wind Configuration", "Wind force entity tags.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &WindConfiguration::m_globalWindTag, "Global wind tag", - "Tag value that will be used to mark entities that provide global wind value.\n" - "Global wind has no bounds and affects objects across entire level.") + "Global wind provider tags.\n" + "Global winds apply to entire world.") ->DataElement(AZ::Edit::UIHandlers::Default, &WindConfiguration::m_localWindTag, "Local wind tag", - "Tag value that will be used to mark entities that provide local wind value.\n" - "Local wind is only applied within bounds defined by PhysX collider.") + "Local wind provider tags.\n" + "Local winds are constrained to a PhysX collider's boundaries.") ; } } diff --git a/Gems/PhysX/Code/Source/Debug/Configuration/PhysXDebugConfiguration.cpp b/Gems/PhysX/Code/Source/Debug/Configuration/PhysXDebugConfiguration.cpp index e14ce62537..c199159a43 100644 --- a/Gems/PhysX/Code/Source/Debug/Configuration/PhysXDebugConfiguration.cpp +++ b/Gems/PhysX/Code/Source/Debug/Configuration/PhysXDebugConfiguration.cpp @@ -31,38 +31,39 @@ namespace PhysX if (AZ::EditContext* editContext = serialize->GetEditContext()) { - editContext->Class("PhysX PVD Settings", "PhysX PVD Settings") + editContext->Class("PhysX PVD Settings", + "Connection configuration settings for the PhysX Visual Debugger (PVD). Requires PhysX Debug Gem.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::ComboBox, &PvdConfiguration::m_transportType, - "PVD Transport Type", "PVD supports writing to a TCP/IP network socket or to a file.") + "PVD Transport Type", "Output PhysX Visual Debugger data to a TCP/IP network socket or to a file.") ->EnumAttribute(Debug::PvdTransportType::Network, "Network") ->EnumAttribute(Debug::PvdTransportType::File, "File") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &PvdConfiguration::m_host, - "PVD Host", "Host IP address of the PhysX Visual Debugger application") + "PVD Host", "Host IP address of the PhysX Visual Debugger server.") ->Attribute(AZ::Edit::Attributes::Visibility, &PvdConfiguration::IsNetworkDebug) ->DataElement(AZ::Edit::UIHandlers::Default, &PvdConfiguration::m_port, - "PVD Port", "Port of the PhysX Visual Debugger application") + "PVD Port", "Port of the PhysX Visual Debugger server.") ->Attribute(AZ::Edit::Attributes::Visibility, &PvdConfiguration::IsNetworkDebug) + ->Attribute(AZ::Edit::Attributes::Min, AZStd::numeric_limits::min()) + ->Attribute(AZ::Edit::Attributes::Max, AZStd::numeric_limits::max()) ->DataElement(AZ::Edit::UIHandlers::Default, &PvdConfiguration::m_timeoutInMilliseconds, - "PVD Timeout", "Timeout (in milliseconds) used when connecting to the PhysX Visual Debugger application") + "PVD Timeout", "Timeout (in milliseconds) when connecting to the PhysX Visual Debugger server.") ->Attribute(AZ::Edit::Attributes::Visibility, &PvdConfiguration::IsNetworkDebug) ->DataElement(AZ::Edit::UIHandlers::Default, &PvdConfiguration::m_fileName, - "PVD FileName", "Filename to output PhysX Visual Debugger data.") + "PVD FileName", "Output filename for PhysX Visual Debugger data.") ->Attribute(AZ::Edit::Attributes::Visibility, &PvdConfiguration::IsFileDebug) ->DataElement(AZ::Edit::UIHandlers::ComboBox, &PvdConfiguration::m_autoConnectMode, - "PVD Auto Connect", "Automatically connect to the PhysX Visual Debugger " - "(Requires PhysX Debug gem for Editor and Game modes).") + "PVD Auto Connect", "Automatically connect to the PhysX Visual Debugger.") ->EnumAttribute(Debug::PvdAutoConnectMode::Disabled, "Disabled") ->EnumAttribute(Debug::PvdAutoConnectMode::Editor, "Editor") ->EnumAttribute(Debug::PvdAutoConnectMode::Game, "Game") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &PvdConfiguration::m_reconnect, - "PVD Reconnect", "Reconnect (Disconnect and Connect) when switching between game and edit mode " - "(Requires PhysX Debug gem).") + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &PvdConfiguration::m_reconnect, "PVD Reconnect", + "Reconnect (disconnect and connect) to the PhysX Visual Debugger server when switching between game and edit mode.") ; } } @@ -131,7 +132,7 @@ namespace PhysX if (AZ::EditContext* editContext = serialize->GetEditContext()) { - editContext->Class("Editor Configuration", "Editor settings for PhysX") + editContext->Class("Editor Configuration", "Editor settings for PhysX.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Slider, &DebugDisplayData::m_centerOfMassDebugSize, diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp index 92952bcdaa..fa71fa0061 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp @@ -33,14 +33,14 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Ball Joint", "The ball joint supports a cone limiting the maximum rotation around the y and z axes.") + "PhysX Ball Joint", "A dynamic joint constraint with swing rotation limits around the Y and Z axes of the joint.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/ball-joint/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(0, &EditorBallJointComponent::m_swingLimit, "Swing Limit", "Limitations for the swing (Y and Z axis) about joint") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorBallJointComponent::m_componentModeDelegate, "Component Mode", "Ball Joint Component Mode") + ->DataElement(0, &EditorBallJointComponent::m_swingLimit, "Swing Limit", "The rotation angle limit around the joint's Y and Z axes.") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorBallJointComponent::m_componentModeDelegate, "Component Mode", "Ball Joint Component Mode.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ; } diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index f8d0adf156..262e40cb99 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -53,13 +53,15 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { - editContext->Class("EditorProxyShapeConfig", "PhysX Base shape collider") + editContext->Class("EditorProxyShapeConfig", "PhysX Base collider.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyAssetShapeConfig::m_pxAsset, "PhysX Mesh", "PhysX mesh collider asset") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyAssetShapeConfig::m_pxAsset, "PhysX Mesh", + "Specifies the PhysX mesh collider asset for this PhysX collider component.") ->Attribute(AZ_CRC_CE("EditButton"), "") ->Attribute(AZ_CRC_CE("EditDescription"), "Open in Scene Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyAssetShapeConfig::m_configuration, "Configuration", "Configuration of asset shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyAssetShapeConfig::m_configuration, "Configuration", + "PhysX mesh asset collider configuration.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly); } } @@ -86,7 +88,7 @@ namespace PhysX { editContext->Class( "EditorProxyShapeConfig", "PhysX Base shape collider") - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorProxyShapeConfig::m_shapeType, "Shape", "The shape of the collider") + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorProxyShapeConfig::m_shapeType, "Shape", "The shape of the collider.") ->EnumAttribute(Physics::ShapeType::Sphere, "Sphere") ->EnumAttribute(Physics::ShapeType::Box, "Box") ->EnumAttribute(Physics::ShapeType::Capsule, "Capsule") @@ -96,20 +98,20 @@ namespace PhysX // potentially be different ComponentModes for different shape types) ->Attribute(AZ::Edit::Attributes::ReadOnly, &AzToolsFramework::ComponentModeFramework::InComponentMode) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_sphere, "Sphere", "Configuration of sphere shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_sphere, "Sphere", "Configuration of sphere shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorProxyShapeConfig::IsSphereConfig) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorProxyShapeConfig::OnConfigurationChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_box, "Box", "Configuration of box shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_box, "Box", "Configuration of box shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorProxyShapeConfig::IsBoxConfig) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorProxyShapeConfig::OnConfigurationChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_capsule, "Capsule", "Configuration of capsule shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_capsule, "Capsule", "Configuration of capsule shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorProxyShapeConfig::IsCapsuleConfig) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorProxyShapeConfig::OnConfigurationChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_physicsAsset, "Asset", "Configuration of asset shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_physicsAsset, "Asset", "Configuration of asset shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorProxyShapeConfig::IsAssetConfig) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorProxyShapeConfig::OnConfigurationChanged) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyShapeConfig::m_subdivisionLevel, "Subdivision level", - "The level of subdivision if a primitive shape is replaced with a convex mesh due to scaling") + "The level of subdivision if a primitive shape is replaced with a convex mesh due to scaling.") ->Attribute(AZ::Edit::Attributes::Min, Utils::MinCapsuleSubdivisionLevel) ->Attribute(AZ::Edit::Attributes::Max, Utils::MaxCapsuleSubdivisionLevel) ->Attribute(AZ::Edit::Attributes::Visibility, &EditorProxyShapeConfig::ShowingSubdivisionLevel) @@ -200,7 +202,7 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Collider", "PhysX shape collider") + "PhysX Collider", "Creates geometry in the PhysX simulation, using either a primitive shape or geometry from an asset.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCollider.svg") @@ -208,17 +210,17 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/collider/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_configuration, "Collider Configuration", "Configuration of the collider") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_configuration, "Collider Configuration", "Configuration of the collider.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorColliderComponent::OnConfigurationChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_shapeConfiguration, "Shape Configuration", "Configuration of the shape") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_shapeConfiguration, "Shape Configuration", "Configuration of the shape.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorColliderComponent::OnConfigurationChanged) ->Attribute(AZ::Edit::Attributes::RemoveNotify, &EditorColliderComponent::ValidateRigidBodyMeshGeometryType) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_componentModeDelegate, "Component Mode", "Collider Component Mode") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_componentModeDelegate, "Component Mode", "Collider Component Mode.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorColliderComponent::m_colliderDebugDraw, - "Debug draw settings", "Debug draw settings") + "Debug draw settings", "Debug draw settings.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ; } diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp index 94f57690ba..692671174b 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp @@ -30,13 +30,14 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Fixed Joint", "The fixed joint constraints the position and orientation of a body to another.") + "PhysX Fixed Joint", + "A dynamic joint constraint that constrains a rigid body to the joint with no free translation or rotation on any axis.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/fixed-joint/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorFixedJointComponent::m_componentModeDelegate, "Component Mode", "Fixed Joint Component Mode") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorFixedJointComponent::m_componentModeDelegate, "Component Mode", "Fixed Joint Component Mode.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ; } diff --git a/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp b/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp index 610a0a9b2e..dff1ff86bb 100644 --- a/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp @@ -164,7 +164,7 @@ namespace PhysX { // EditorForceRegionComponent editContext->Class( - "PhysX Force Region", "The force region component is used to apply a physical force on objects within the region") + "PhysX Force Region", "The force region component is used to apply a physical force on objects within the region.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/ForceVolume.svg") @@ -173,9 +173,10 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/force-region/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::RequiredService, AZ_CRC("PhysXTriggerService", 0x3a117d7b)) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_visibleInEditor, "Visible", "Always show the component in viewport") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_debugForces, "Debug Forces", "Draws debug arrows when an entity enters a force region. This occurs in gameplay mode to show the force direction on an entity.") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_forces, "Forces", "Forces in force region") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_visibleInEditor, "Visible", "Always show the component in viewport.") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_debugForces, "Debug Forces", + "Draws debug arrows when an entity enters a force region. This occurs in gameplay mode to show the force direction on an entity.") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_forces, "Forces", "Forces in force region.") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorForceRegionComponent::OnForcesChanged) ; diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp index 5537502327..1b575074e2 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp @@ -33,14 +33,14 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Hinge Joint", "The entity constrains two actors in PhysX, keeping the origins and x-axes together, and allows free rotation around this common axis") + "PhysX Hinge Joint", "A dynamic joint that constrains a rigid body with rotation limits around a single axis.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/hinge-joint/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(0, &EditorHingeJointComponent::m_angularLimit, "Angular Limit", "Limitations for the rotation about hinge axis") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorHingeJointComponent::m_componentModeDelegate, "Component Mode", "Hinge Joint Component Mode") + ->DataElement(0, &EditorHingeJointComponent::m_angularLimit, "Angular Limit", "The rotation angle limit around the joint's axis.") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorHingeJointComponent::m_componentModeDelegate, "Component Mode", "Hinge Joint Component Mode.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ; } diff --git a/Gems/PhysX/Code/Source/EditorJointComponent.cpp b/Gems/PhysX/Code/Source/EditorJointComponent.cpp index 88e192026d..9a24392fd0 100644 --- a/Gems/PhysX/Code/Source/EditorJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorJointComponent.cpp @@ -37,11 +37,11 @@ namespace PhysX if (auto* editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Joint", "The joint constrains the position and orientation of a body to another.") + "PhysX Joint", "A dynamic joint that constrains the position and orientation of one rigid body to another.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(0, &EditorJointComponent::m_config, "Standard Joint Parameters", "Joint parameters shared by all joint types") + ->DataElement(0, &EditorJointComponent::m_config, "Standard Joint Parameters", "Joint parameters shared by all joint types.") ; } } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index 24b2586c9e..e384f222e8 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -122,38 +122,38 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_initialLinearVelocity, - "Initial linear velocity", "Initial linear velocity") + "Initial linear velocity", "Linear velocity applied when the rigid body is activated.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInitialVelocitiesVisibility) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetSpeedUnit()) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_initialAngularVelocity, - "Initial angular velocity", "Initial angular velocity (limited by maximum angular velocity)") + "Initial angular velocity", "Angular velocity applied when the rigid body is activated (limited by maximum angular velocity).") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInitialVelocitiesVisibility) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetAngularVelocityUnit()) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_linearDamping, - "Linear damping", "Linear damping (must be non-negative)") + "Linear damping", "The rate of decay over time for linear velocity even if no forces are acting on the rigid body.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetDampingVisibility) ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_angularDamping, - "Angular damping", "Angular damping (must be non-negative)") + "Angular damping", "The rate of decay over time for angular velocity even if no forces are acting on the rigid body.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetDampingVisibility) ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_sleepMinEnergy, - "Sleep threshold", "Kinetic energy per unit mass below which body can go to sleep (must be non-negative)") + "Sleep threshold", "The rigid body can go to sleep (settle) when kinetic energy per unit mass is persistently below this value.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetSleepOptionsVisibility) ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetSleepThresholdUnit()) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_startAsleep, - "Start asleep", "The rigid body will be asleep when spawned") + "Start asleep", "When active, the rigid body will be asleep when spawned, and wake when the body is disturbed.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetSleepOptionsVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_interpolateMotion, - "Interpolate motion", "Makes object motion look smoother") + "Interpolate motion", "When active, simulation results are interpolated resulting in smoother motion.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInterpolationVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_gravityEnabled, - "Gravity enabled", "Rigid body will be affected by gravity") + "Gravity enabled", "When active, global gravity affects this rigid body.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetGravityVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_kinematic, - "Kinematic", "Rigid body is kinematic") + "Kinematic", "When active, the rigid body is not affected by gravity or other forces and is moved by script.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetKinematicVisibility) // Linear axis locking properties @@ -161,85 +161,90 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::AutoExpand, false) ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockLinearX, "Lock X", - "Lock motion along X direction") + "When active, forces won't create translation on the X axis of the rigid body.") ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockLinearY, "Lock Y", - "Lock motion along Y direction") + "When active, forces won't create translation on the Y axis of the rigid body.") ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockLinearZ, "Lock Z", - "Lock motion along Z direction") + "When active, forces won't create translation on the Z axis of the rigid body.") // Angular axis locking properties ->ClassElement(AZ::Edit::ClassElements::Group, "Angular Axis Locking") ->Attribute(AZ::Edit::Attributes::AutoExpand, false) ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockAngularX, "Lock X", - "Lock rotation around X direction") + "When active, forces won't create rotation on the X axis of the rigid body.") ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockAngularY, "Lock Y", - "Lock rotation around Y direction") + "When active, forces won't create rotation on the Y axis of the rigid body.") ->DataElement( AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_lockAngularZ, "Lock Z", - "Lock rotation around Z direction") + "When active, forces won't create rotation on the Z axis of the rigid body.") ->ClassElement(AZ::Edit::ClassElements::Group, "Continuous Collision Detection") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetCCDVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_ccdEnabled, - "CCD enabled", "Whether continuous collision detection is enabled for this body") + "CCD enabled", "When active, the rigid body has continuous collision detection (CCD). Use this to ensure accurate " + "collision detection, particularly for fast moving rigid bodies. CCD must be activated in the global PhysX preferences.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetCCDVisibility) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_ccdMinAdvanceCoefficient, - "Min advance coefficient", "Lower values reduce clipping but can affect simulation smoothness") + "Min advance coefficient", "Lower values reduce clipping but can affect simulation smoothness.") ->Attribute(AZ::Edit::Attributes::Min, 0.01f) ->Attribute(AZ::Edit::Attributes::Step, 0.01f) ->Attribute(AZ::Edit::Attributes::Max, 0.99f) ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::IsCCDEnabled) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_ccdFrictionEnabled, - "CCD friction", "Whether friction is applied when CCD collisions are resolved") + "CCD friction", "When active, friction is applied when continuous collision detection (CCD) collisions are resolved.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::IsCCDEnabled) ->ClassElement(AZ::Edit::ClassElements::Group, "") // end previous group by starting new unnamed expanded group ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_maxAngularVelocity, - "Maximum angular velocity", "The PhysX solver will clamp angular velocities with magnitude exceeding this value") + "Maximum angular velocity", "Clamp angular velocities to this maximum value. " + "This prevents rigid bodies from rotating at unrealistic velocities after collisions.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetMaxVelocitiesVisibility) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetAngularVelocityUnit()) // Mass properties ->DataElement(AZ::Edit::UIHandlers::Default, &RigidBodyConfiguration::m_computeCenterOfMass, - "Compute COM", "Whether to automatically compute the center of mass") + "Compute COM", "Compute the center of mass (COM) for this rigid body.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInertiaSettingsVisibility) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &RigidBodyConfiguration::m_centerOfMassOffset, - "COM offset", "Center of mass offset in local frame") + "COM offset", "Local space offset for the center of mass (COM).") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetCoMVisibility) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetLengthUnit()) ->DataElement(AZ::Edit::UIHandlers::Default, &RigidBodyConfiguration::m_computeMass, - "Compute Mass", "Whether to automatically compute the mass") + "Compute Mass", "When active, the mass of the rigid body is computed based on the volume and density values of its colliders.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInertiaSettingsVisibility) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &AzPhysics::RigidBodyConfiguration::m_mass, - "Mass", "The mass of the object (must be non-negative, with a value of zero treated as infinite)") + "Mass", "The mass of the rigid body in kilograms. A value of 0 is treated as infinite. " + "The trajectory of infinite mass bodies cannot be affected by any collisions or forces other than gravity.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetMassUnit()) ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetMassVisibility) ->DataElement(AZ::Edit::UIHandlers::Default, &RigidBodyConfiguration::m_computeInertiaTensor, - "Compute inertia", "Whether to automatically compute the inertia values based on the mass and shape of the rigid body") + "Compute inertia", "When active, inertia is computed based on the mass and shape of the rigid body.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInertiaSettingsVisibility) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(Editor::InertiaHandler, &AzPhysics::RigidBodyConfiguration::m_inertiaTensor, - "Inertia diagonal", "Diagonal elements of the inertia tensor") + "Inertia diagonal", "Inertia diagonal elements that specify an inertia tensor; determines the " + "torque required to rotate the rigid body on each axis.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInertiaVisibility) ->Attribute(AZ::Edit::Attributes::Suffix, " " + Physics::NameConstants::GetInertiaUnit()) ->DataElement(AZ::Edit::UIHandlers::Default, &RigidBodyConfiguration::m_includeAllShapesInMassCalculation, - "Include non-simulated shapes in Mass", "If set, non-simulated shapes will also be included in the center of mass, inertia and mass calculations.") + "Include non-simulated shapes in Mass", + "When active, non-simulated shapes are included in the center of mass, inertia, and mass calculations.") ->Attribute(AZ::Edit::Attributes::Visibility, &AzPhysics::RigidBodyConfiguration::GetInertiaSettingsVisibility) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ; @@ -250,7 +255,7 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorRigidBodyConfiguration::m_centerOfMassDebugDraw, - "Debug draw COM", "Whether to debug draw the center of mass for this body") + "Debug draw COM", "Display the rigid body's center of mass (COM) in the viewport.") ; } } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index 2bbc04faae..4ee51d7787 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -79,7 +79,7 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Shape Collider", "Creates geometry in the PhysX simulation based on an attached shape component") + "PhysX Shape Collider", "Create a PhysX collider using a shape provided by a Shape component.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCollider.svg") @@ -88,13 +88,14 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/shape-collider/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorShapeColliderComponent::m_colliderConfig, - "Collider configuration", "Configuration of the collider") + "Collider configuration", "Configuration of the collider.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorShapeColliderComponent::OnConfigurationChanged) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorShapeColliderComponent::m_colliderDebugDraw, - "Debug draw settings", "Debug draw settings") + "Debug draw settings", "Debug draw settings.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorShapeColliderComponent::m_subdivisionCount, "Subdivision count", "Number of angular subdivisions in the PhysX cylinder") + ->DataElement(AZ::Edit::UIHandlers::Default, &EditorShapeColliderComponent::m_subdivisionCount, "Subdivision count", + "Number of angular subdivisions in the PhysX cylinder.") ->Attribute(AZ::Edit::Attributes::Min, Utils::MinFrustumSubdivisions) ->Attribute(AZ::Edit::Attributes::Max, Utils::MaxFrustumSubdivisions) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorShapeColliderComponent::OnSubdivisionCountChange) diff --git a/Gems/PhysX/Code/Source/ForceRegion.cpp b/Gems/PhysX/Code/Source/ForceRegion.cpp index 63426d304e..5314f97f9a 100644 --- a/Gems/PhysX/Code/Source/ForceRegion.cpp +++ b/Gems/PhysX/Code/Source/ForceRegion.cpp @@ -62,10 +62,10 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Force Region", "Applies forces on entities within a region") + "Force Region", "Applies forces on entities within a region.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceRegion::m_forces, "Forces", "Forces acting in the region") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceRegion::m_forces, "Forces", "Forces acting in the region.") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } diff --git a/Gems/PhysX/Code/Source/ForceRegionForces.cpp b/Gems/PhysX/Code/Source/ForceRegionForces.cpp index 202a073640..6ed4c3e93a 100644 --- a/Gems/PhysX/Code/Source/ForceRegionForces.cpp +++ b/Gems/PhysX/Code/Source/ForceRegionForces.cpp @@ -37,13 +37,13 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "World Space Force", "Applies a force in world space") + "World Space Force", "Applies a force in world space.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Vector3, &ForceWorldSpace::m_direction, "Direction", "Direction of the force in world space") + ->DataElement(AZ::Edit::UIHandlers::Vector3, &ForceWorldSpace::m_direction, "Direction", "Direction of the force in world space.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceWorldSpace::m_magnitude, "Magnitude", "Magnitude of the force in world space") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceWorldSpace::m_magnitude, "Magnitude", "Magnitude of the force in world space.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) ; @@ -109,13 +109,13 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Local Space Force", "Applies a force in the volume's local space") + "Local Space Force", "Applies a force in the volume's local space.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Vector3, &ForceLocalSpace::m_direction, "Direction", "Direction of the force in local space") + ->DataElement(AZ::Edit::UIHandlers::Vector3, &ForceLocalSpace::m_direction, "Direction", "Direction of the force in local space.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceLocalSpace::m_magnitude, "Magnitude", "Magnitude of the force in local space") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceLocalSpace::m_magnitude, "Magnitude", "Magnitude of the force in local space.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) ; @@ -179,10 +179,10 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Point Force", "Applies a force relative to the center of the volume") + "Point Force", "Applies a force directed towards or away from the center of the volume.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForcePoint::m_magnitude, "Magnitude", "Magnitude of the point force") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForcePoint::m_magnitude, "Magnitude", "Magnitude of the point force.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) ; @@ -242,19 +242,24 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Spline Follow Force", "Applies a force to make objects follow a spline at a given speed") + "Spline Follow Force", "Applies a force to make objects follow a spline at a given speed.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_dampingRatio, "Damping Ratio", "Amount of damping applied to an entity that is moving towards a spline") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_dampingRatio, "Damping Ratio", + "Values below 1 cause the entity to approach the spline faster but lead to overshooting and oscillation, " + "while higher values will cause it to approach more slowly but more smoothly.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionZeroValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxDampingRatio) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_frequency, "Frequency", "Frequency at which an entity moves towards a spline") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_frequency, "Frequency", + "Affects how quickly the entity approaches the spline.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinFrequency) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxFrequency) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_targetSpeed, "Target Speed", "Speed at which entities in the force region move along a spline") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_targetSpeed, "Target Speed", + "Speed at which entities in the force region move along a spline.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionMinValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_lookAhead, "Lookahead", "Distance at which entities look ahead in their path to reach a point on a spline") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSplineFollow::m_lookAhead, "Lookahead", + "Distance at which entities look ahead in their path to reach a point on a spline.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionZeroValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxValue) ; @@ -393,10 +398,10 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Simple Drag Force", "Simulates a drag force on entities") + "Simple Drag Force", "Simulates a drag force on entities.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSimpleDrag::m_volumeDensity, "Region Density", "Density of the region") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceSimpleDrag::m_volumeDensity, "Region Density", "Density of the region.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionZeroValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxDensity) ; @@ -463,10 +468,10 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "Linear Damping Force", "Applies an opposite force to the entity's velocity") + "Linear Damping Force", "Applies an opposite force to the entity's velocity.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &ForceLinearDamping::m_damping, "Damping", "Amount of damping applied to an opposite force") + ->DataElement(AZ::Edit::UIHandlers::Default, &ForceLinearDamping::m_damping, "Damping", "Amount of damping applied to an opposite force.") ->Attribute(AZ::Edit::Attributes::Min, s_forceRegionZeroValue) ->Attribute(AZ::Edit::Attributes::Max, s_forceRegionMaxDamping) ; diff --git a/Gems/PhysX/Code/Source/Joint/Configuration/PhysXJointConfiguration.cpp b/Gems/PhysX/Code/Source/Joint/Configuration/PhysXJointConfiguration.cpp index 530bd03732..ae74859528 100644 --- a/Gems/PhysX/Code/Source/Joint/Configuration/PhysXJointConfiguration.cpp +++ b/Gems/PhysX/Code/Source/Joint/Configuration/PhysXJointConfiguration.cpp @@ -59,22 +59,22 @@ namespace PhysX ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &D6JointLimitConfiguration::m_swingLimitY, "Swing limit Y", - "Maximum angle from the Y axis of the joint frame") + "The rotation angle limit around the joint's Y axis.") ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Min, JointConstants::MinSwingLimitDegrees) ->Attribute(AZ::Edit::Attributes::Max, 180.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &D6JointLimitConfiguration::m_swingLimitZ, "Swing limit Z", - "Maximum angle from the Z axis of the joint frame") + "The rotation angle limit around the joint's Z axis.") ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Min, JointConstants::MinSwingLimitDegrees) ->Attribute(AZ::Edit::Attributes::Max, 180.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &D6JointLimitConfiguration::m_twistLimitLower, "Twist lower limit", - "Lower limit for rotation about the X axis of the joint frame") + "The lower rotation angle limit around the joint's X axis.") ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Min, -180.0f) ->Attribute(AZ::Edit::Attributes::Max, 180.0f) ->DataElement(AZ::Edit::UIHandlers::Default, &D6JointLimitConfiguration::m_twistLimitUpper, "Twist upper limit", - "Upper limit for rotation about the X axis of the joint frame") + "The upper rotation angle limit around the joint's X axis.") ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") ->Attribute(AZ::Edit::Attributes::Min, -180.0f) ->Attribute(AZ::Edit::Attributes::Max, 180.0f) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp index ed9030ac4f..6af08cfaeb 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp @@ -42,16 +42,16 @@ namespace PhysX "PhysX Character Controller Configuration", "PhysX Character Controller Configuration") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->DataElement(AZ::Edit::UIHandlers::ComboBox, &CharacterControllerConfiguration::m_slopeBehaviour, - "Slope Behaviour", "Behaviour of the controller on surfaces above the maximum slope") + "Slope Behavior", "Behavior of the controller on surfaces that exceed the Maximum Slope Angle.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->EnumAttribute(SlopeBehaviour::PreventClimbing, "Prevent Climbing") ->EnumAttribute(SlopeBehaviour::ForceSliding, "Force Sliding") ->DataElement(AZ::Edit::UIHandlers::Default, &CharacterControllerConfiguration::m_contactOffset, - "Contact Offset", "Extra distance outside the controller used for smoother contact resolution") + "Contact Offset", "Distance from the controller boundary where contact with surfaces can be resolved.") ->Attribute(AZ::Edit::Attributes::Min, 0.01f) ->Attribute(AZ::Edit::Attributes::Step, 0.01f) ->DataElement(AZ::Edit::UIHandlers::Default, &CharacterControllerConfiguration::m_scaleCoefficient, - "Scale", "Scalar coefficient used to scale the controller, usually slightly smaller than 1") + "Scale", "Scales the controller. Usually less than 1.0 to ensure visual contact between the character and surface.") ->Attribute(AZ::Edit::Attributes::Min, 0.01f) ->Attribute(AZ::Edit::Attributes::Step, 0.01f) ; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp index 4a4f12558d..e86b81359c 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp @@ -33,7 +33,7 @@ namespace PhysX "PhysX Character Gameplay Configuration", "PhysX Character Gameplay Configuration") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->DataElement(AZ::Edit::UIHandlers::Default, &CharacterGameplayConfiguration::m_gravityMultiplier, - "Gravity Multiplier", "Multiplier to be combined with the world gravity value for applying character gravity") + "Gravity Multiplier", "Multiplier for global gravity value that applies only to this character entity.") ->Attribute(AZ::Edit::Attributes::Step, 0.1f) ; } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.cpp index 4e24067dbf..114f9bc2f7 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.cpp @@ -36,18 +36,18 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "EditorCharacterControllerProxyShapeConfig", "PhysX character controller shape") + "EditorCharacterControllerProxyShapeConfig", "PhysX character controller shape.") ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorCharacterControllerProxyShapeConfig::m_shapeType, "Shape", - "The shape associated with the character controller") + "The shape of the character controller.") ->EnumAttribute(Physics::ShapeType::Capsule, "Capsule") ->EnumAttribute(Physics::ShapeType::Box, "Box") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerProxyShapeConfig::m_box, "Box", - "Configuration of box shape") + "Configuration of box shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorCharacterControllerProxyShapeConfig::IsBoxConfig) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerProxyShapeConfig::m_capsule, "Capsule", - "Configuration of capsule shape") + "Configuration of capsule shape.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorCharacterControllerProxyShapeConfig::IsCapsuleConfig) ; } @@ -93,7 +93,8 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Character Controller", "PhysX Character Controller") + "PhysX Character Controller", + "Provides basic character interactions with the physical world, such as preventing movement through other PhysX bodies.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCharacter.svg") @@ -101,12 +102,12 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/character-controller/") ->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerComponent::m_configuration, - "Configuration", "Configuration for the character controller") + "Configuration", "Configuration for the character controller.") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorCharacterControllerComponent::OnControllerConfigChanged) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerComponent::m_proxyShapeConfiguration, - "Shape Configuration", "The configuration for the shape associated with the character controller") + "Shape Configuration", "The configuration for the shape associated with the character controller.") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorCharacterControllerComponent::OnShapeConfigChanged) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp index 81d158d81c..de4deb442f 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp @@ -43,7 +43,7 @@ namespace PhysX if (auto editContext = serializeContext->GetEditContext()) { editContext->Class( - "PhysX Character Gameplay", "PhysX Character Gameplay") + "PhysX Character Gameplay", "An example implementation of character physics behavior such as gravity.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCharacter.svg") @@ -51,7 +51,7 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/character-gameplay/") ->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterGameplayComponent::m_gameplayConfig, - "Gameplay Configuration", "Gameplay Configuration") + "Gameplay Configuration", "Gameplay Configuration.") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp index 6fa3bdbffd..57972fea3e 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.cpp @@ -82,7 +82,7 @@ namespace PhysX if (editContext) { editContext->Class( - "PhysX Ragdoll", "Provides simulation of characters in PhysX.") + "PhysX Ragdoll", "Creates a PhysX ragdoll simulation for an animation actor.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXRagdoll.svg") @@ -91,26 +91,28 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/physx/ragdoll/") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_positionIterations, "Position Iteration Count", - "A higher iteration count generally improves fidelity at the cost of performance, but note that very high " - "values may lead to severe instability if ragdoll colliders interfere with satisfying joint constraints") + "The frequency at which ragdoll collider positions are resolved. Higher values can increase fidelity but decrease " + "performance. Very high values might introduce instability.") ->Attribute(AZ::Edit::Attributes::Min, 1) ->Attribute(AZ::Edit::Attributes::Max, 255) ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_velocityIterations, "Velocity Iteration Count", - "A higher iteration count generally improves fidelity at the cost of performance, but note that very high " - "values may lead to severe instability if ragdoll colliders interfere with satisfying joint constraints") + "The frequency at which ragdoll collider velocities are resolved. Higher values can increase fidelity but decrease " + "performance. Very high values might introduce instability.") ->Attribute(AZ::Edit::Attributes::Min, 1) ->Attribute(AZ::Edit::Attributes::Max, 255) ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_enableJointProjection, - "Enable Joint Projection", "Whether to use joint projection to preserve joint constraints " - "in demanding situations at the expense of potentially reducing physical correctness") + "Enable Joint Projection", "When active, preserves joint constraints in volatile simulations. " + "Might not be physically correct in all simulations.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionLinearTolerance, - "Joint Projection Linear Tolerance", "Linear joint error above which projection will be applied") + "Joint Projection Linear Tolerance", + "Maximum linear joint error. Projection is applied to linear joint errors above this value.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Step, 1e-3f) ->Attribute(AZ::Edit::Attributes::Visibility, &RagdollComponent::IsJointProjectionVisible) ->DataElement(AZ::Edit::UIHandlers::Default, &RagdollComponent::m_jointProjectionAngularToleranceDegrees, - "Joint Projection Angular Tolerance", "Angular joint error (in degrees) above which projection will be applied") + "Joint Projection Angular Tolerance", + "Maximum angular joint error. Projection is applied to angular joint errors above this value.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Step, 0.1f) ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") diff --git a/Gems/PhysX/Code/Source/SystemComponent.cpp b/Gems/PhysX/Code/Source/SystemComponent.cpp index f56ad43079..2f4d082ccb 100644 --- a/Gems/PhysX/Code/Source/SystemComponent.cpp +++ b/Gems/PhysX/Code/Source/SystemComponent.cpp @@ -101,7 +101,7 @@ namespace PhysX if (AZ::EditContext* editContext = serialize->GetEditContext()) { - editContext->Class("PhysX", "Global PhysX physics configuration") + editContext->Class("PhysX", "Global PhysX physics configuration.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) From cff2315654a016d5c1e8a40f0fc3e55f957dd3af Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 14 Oct 2021 16:55:07 +0100 Subject: [PATCH 32/52] small correction to wording Signed-off-by: greerdv --- Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp index ee3988ded4..02e684de63 100644 --- a/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp +++ b/Gems/PhysX/Code/Editor/EditorJointConfiguration.cpp @@ -71,7 +71,7 @@ namespace PhysX ->Attribute(AZ::Edit::Attributes::Max, s_springMax) ->Attribute(AZ::Edit::Attributes::Min, s_springMin) ->DataElement(0, &PhysX::EditorJointLimitConfig::m_stiffness, "Stiffness", - "The spring's drive relative to the position of the follower when outside the rotation limit.") + "The spring's drive relative to the position of the follower when outside the joint limit.") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorJointLimitConfig::IsSoftLimited) ->Attribute(AZ::Edit::Attributes::Max, s_springMax) ->Attribute(AZ::Edit::Attributes::Min, s_springMin) From 1fc69aa9c51dfc25ee26abac90c3202ea35b1e14 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 14 Oct 2021 11:15:21 -0500 Subject: [PATCH 33/52] Set EDITOR_TEST_SUPPORTED to false for Android/iOS in the template. Signed-off-by: Chris Galvan --- .../CustomTool/Template/Code/Platform/Android/PAL_android.cmake | 2 +- Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake b/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake index 49dfe71f53..90d1caccf4 100644 --- a/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake +++ b/Templates/CustomTool/Template/Code/Platform/Android/PAL_android.cmake @@ -8,4 +8,4 @@ set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) -set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED FALSE) diff --git a/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake b/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake index 0abcd887e8..332f4469b6 100644 --- a/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake +++ b/Templates/CustomTool/Template/Code/Platform/iOS/PAL_ios.cmake @@ -8,4 +8,4 @@ set(PAL_TRAIT_${NameUpper}_SUPPORTED TRUE) set(PAL_TRAIT_${NameUpper}_TEST_SUPPORTED TRUE) -set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED TRUE) \ No newline at end of file +set(PAL_TRAIT_${NameUpper}_EDITOR_TEST_SUPPORTED FALSE) \ No newline at end of file From 63ece6e3ca035087b9ee7e31151aefefef0f975c Mon Sep 17 00:00:00 2001 From: amzn-mike <80125227+amzn-mike@users.noreply.github.com> Date: Thu, 14 Oct 2021 11:54:13 -0500 Subject: [PATCH 34/52] Change Asset Hint fixup code to not request assets be queued for load. (#4664) Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> --- .../AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index ea0fa55256..a84d6bf706 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -262,7 +262,7 @@ namespace AzToolsFramework if (assetId.IsValid()) { - asset.Create(assetId, true); + asset.Create(assetId, false); } } }; From c7e690706404ce745cf3fce9c6d92d82d5b905db Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Thu, 14 Oct 2021 13:03:19 -0500 Subject: [PATCH 35/52] Flipped y value on uv so that the macro material lines up with the corresponding height data. (#4701) Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> --- .../Code/Source/TerrainRenderer/TerrainFeatureProcessor.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainFeatureProcessor.cpp b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainFeatureProcessor.cpp index d7300cdc48..8c85e21490 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainFeatureProcessor.cpp +++ b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainFeatureProcessor.cpp @@ -567,13 +567,15 @@ namespace Terrain ShaderMacroMaterialData& shaderData = macroMaterialData.at(i); const AZ::Aabb& materialBounds = materialData.m_bounds; + // Use reverse coordinates (1 - y) for the y direction so that the lower left corner of the macro material images + // map to the lower left corner in world space. This will match up with the height uv coordinate mapping. shaderData.m_uvMin = { (xPatch - materialBounds.GetMin().GetX()) / materialBounds.GetXExtent(), - (yPatch - materialBounds.GetMin().GetY()) / materialBounds.GetYExtent() + 1.0f - ((yPatch - materialBounds.GetMin().GetY()) / materialBounds.GetYExtent()) }; shaderData.m_uvMax = { ((xPatch + GridMeters) - materialBounds.GetMin().GetX()) / materialBounds.GetXExtent(), - ((yPatch + GridMeters) - materialBounds.GetMin().GetY()) / materialBounds.GetYExtent() + 1.0f - (((yPatch + GridMeters) - materialBounds.GetMin().GetY()) / materialBounds.GetYExtent()) }; shaderData.m_normalFactor = materialData.m_normalFactor; shaderData.m_flipNormalX = materialData.m_normalFlipX; From 16a7b896ee27a4a2814361ef9b1e3d0e7fb6572c Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Thu, 14 Oct 2021 12:58:53 -0700 Subject: [PATCH 36/52] Fix to prevent using legacy windows based logic to create a Path on Linx (#4704) Signed-off-by: Steve Pham --- Code/Editor/Util/FileUtil.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp index eeb6912acf..baca69d628 100644 --- a/Code/Editor/Util/FileUtil.cpp +++ b/Code/Editor/Util/FileUtil.cpp @@ -1195,7 +1195,7 @@ bool CFileUtil::IsFileExclusivelyAccessable(const QString& strFilePath) ////////////////////////////////////////////////////////////////////////// bool CFileUtil::CreatePath(const QString& strPath) { -#if defined(AZ_PLATFORM_MAC) +#if !AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS bool pathCreated = true; QString cleanPath = QDir::cleanPath(strPath); @@ -1252,7 +1252,7 @@ bool CFileUtil::CreatePath(const QString& strPath) } return true; -#endif +#endif // !AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS } ////////////////////////////////////////////////////////////////////////// From c510ef105093d641eb0a77c7c321308cbb6f1219 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Thu, 14 Oct 2021 16:44:14 -0500 Subject: [PATCH 37/52] Palify RenderDoc cmake include directories Signed-off-by: rgba16f <82187279+rgba16f@users.noreply.github.com> --- Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake | 3 --- Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake b/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake index 4fc54b9733..b95a246afe 100644 --- a/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake +++ b/Gems/Atom/RHI/3rdParty/Findrenderdoc.cmake @@ -10,8 +10,5 @@ ly_add_external_target( NAME renderdoc 3RDPARTY_ROOT_DIRECTORY "${LY_RENDERDOC_PATH}" VERSION - INCLUDE_DIRECTORIES - . - include COMPILE_DEFINITIONS USE_RENDERDOC ) diff --git a/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake b/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake index 6225cc292a..5e88fcec2f 100644 --- a/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake +++ b/Gems/Atom/RHI/3rdParty/Platform/Linux/renderdoc_linux.cmake @@ -7,3 +7,4 @@ # set(RENDERDOC_RUNTIME_DEPENDENCIES "${BASE_PATH}/lib/librenderdoc.so") +set(RENDERDOC_INCLUDE_DIRECTORIES "include") From b7c478b85efa13f9e7e0c325e11bf2360e770278 Mon Sep 17 00:00:00 2001 From: chcurran <82187351+carlitosan@users.noreply.github.com> Date: Thu, 14 Oct 2021 15:02:16 -0700 Subject: [PATCH 38/52] fix for empty expression primitive type serialization Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com> --- .../ExpressionPrimitivesSerializers.inl | 80 +++++++++++++------ 1 file changed, 54 insertions(+), 26 deletions(-) diff --git a/Gems/ExpressionEvaluation/Code/Source/ExpressionPrimitivesSerializers.inl b/Gems/ExpressionEvaluation/Code/Source/ExpressionPrimitivesSerializers.inl index be9ddb4f20..800257e157 100644 --- a/Gems/ExpressionEvaluation/Code/Source/ExpressionPrimitivesSerializers.inl +++ b/Gems/ExpressionEvaluation/Code/Source/ExpressionPrimitivesSerializers.inl @@ -28,6 +28,19 @@ namespace AZ private: using VariableDescriptor = ExpressionEvaluation::ExpressionTree::VariableDescriptor; + static constexpr AZStd::string_view EmptyAnyIdentifier = "Empty AZStd::any"; + + static bool IsEmptyAny(const rapidjson::Value& typeId) + { + if (typeId.IsString()) + { + AZStd::string_view typeName(typeId.GetString(), typeId.GetStringLength()); + return typeName == EmptyAnyIdentifier; + } + + return false; + } + JsonSerializationResult::Result Load ( void* outputValue , [[maybe_unused]] const Uuid& outputValueTypeId @@ -62,22 +75,25 @@ namespace AZ , JsonSerialization::TypeIdFieldIdentifier)); } - result.Combine(LoadTypeId(typeId, typeIdMember->value, context)); - if (typeId.IsNull()) + if (!IsEmptyAny(typeIdMember->value)) { - return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic - , "ExpressionTreeVariableDescriptorSerializer::Load failed to load the AZ TypeId of the value"); - } + result.Combine(LoadTypeId(typeId, typeIdMember->value, context)); + if (typeId.IsNull()) + { + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic + , "ExpressionTreeVariableDescriptorSerializer::Load failed to load the AZ TypeId of the value"); + } - AZStd::any storage = context.GetSerializeContext()->CreateAny(typeId); - if (storage.empty() || storage.type() != typeId) - { - return context.Report(result, "ExpressionTreeVariableDescriptorSerializer::Load failed to load a value matched the " - "reported AZ TypeId. The C++ declaration may have been deleted or changed."); - } + AZStd::any storage = context.GetSerializeContext()->CreateAny(typeId); + if (storage.empty() || storage.type() != typeId) + { + return context.Report(result, "ExpressionTreeVariableDescriptorSerializer::Load failed to load a value matched the " + "reported AZ TypeId. The C++ declaration may have been deleted or changed."); + } - result.Combine(ContinueLoadingFromJsonObjectField(AZStd::any_cast(&storage), typeId, inputValue, "Value", context)); - outputDatum->m_value = storage; + result.Combine(ContinueLoadingFromJsonObjectField(AZStd::any_cast(&storage), typeId, inputValue, "Value", context)); + outputDatum->m_value = storage; + } // any storage end return context.Report(result, result.GetProcessing() != JSR::Processing::Halted @@ -123,20 +139,32 @@ namespace AZ , azrtti_typeidm_supportedTypes)>() , context)); - rapidjson::Value typeValue; - result.Combine(StoreTypeId(typeValue, inputScriptDataPtr->m_value.type(), context)); - outputValue.AddMember - ( rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier) - , AZStd::move(typeValue) - , context.GetJsonAllocator()); + if (!inputScriptDataPtr->m_value.empty()) + { + rapidjson::Value typeValue; + result.Combine(StoreTypeId(typeValue, inputScriptDataPtr->m_value.type(), context)); + outputValue.AddMember + ( rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier) + , AZStd::move(typeValue) + , context.GetJsonAllocator()); - result.Combine(ContinueStoringToJsonObjectField - ( outputValue - , "Value" - , AZStd::any_cast(const_cast(&inputScriptDataPtr->m_value)) - , defaultScriptDataPtr ? AZStd::any_cast(const_cast(&defaultScriptDataPtr->m_value)) : nullptr - , inputScriptDataPtr->m_value.type() - , context)); + result.Combine(ContinueStoringToJsonObjectField + ( outputValue + , "Value" + , AZStd::any_cast(const_cast(&inputScriptDataPtr->m_value)) + , defaultScriptDataPtr ? AZStd::any_cast(const_cast(&defaultScriptDataPtr->m_value)) : nullptr + , inputScriptDataPtr->m_value.type() + , context)); + } + else + { + rapidjson::Value emptyAny; + emptyAny.SetString(EmptyAnyIdentifier.data(), aznumeric_caster(EmptyAnyIdentifier.size()), context.GetJsonAllocator()); + outputValue.AddMember + ( rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier) + , AZStd::move(emptyAny) + , context.GetJsonAllocator()); + } return context.Report(result, result.GetProcessing() != JSR::Processing::Halted ? "VariableDescriptor Store finished saving VariableDescriptor" From bcf3980de6295a1cb522f20e8482c3222625542c Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Thu, 14 Oct 2021 15:32:34 -0700 Subject: [PATCH 39/52] LYN-7191 + LYN-7194 | Adjust Prefab operations to conform with Prefab Focus/Edit workflows. (#4684) * Disable ability to delete container entity of focused prefab. Default entity creation to parent to container entity of focused prefab. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * Disable detach and duplicate operations for the container of the focused prefab. Update the context menu accordingly. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * Fix spacing Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * Address minor issues from PR (error message, optimization in RetrieveAndSortPrefabEntitiesAndInstances). Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../Prefab/PrefabPublicHandler.cpp | 76 +++++++++++++------ .../Prefab/PrefabPublicHandler.h | 4 +- .../UI/Prefab/PrefabIntegrationManager.cpp | 56 +++++++++----- .../UI/Prefab/PrefabUiHandler.cpp | 6 -- 4 files changed, 91 insertions(+), 51 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index b5f61b33bf..081655a166 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -43,6 +43,12 @@ namespace AzToolsFramework m_instanceToTemplateInterface = AZ::Interface::Get(); AZ_Assert(m_instanceToTemplateInterface, "PrefabPublicHandler - Could not retrieve instance of InstanceToTemplateInterface"); + m_prefabFocusInterface = AZ::Interface::Get(); + AZ_Assert(m_prefabFocusInterface, "Could not get PrefabFocusInterface on PrefabPublicHandler construction."); + + m_prefabFocusPublicInterface = AZ::Interface::Get(); + AZ_Assert(m_prefabFocusPublicInterface, "Could not get PrefabFocusPublicInterface on PrefabPublicHandler construction."); + m_prefabLoaderInterface = AZ::Interface::Get(); AZ_Assert(m_prefabLoaderInterface, "Could not get PrefabLoaderInterface on PrefabPublicHandler construction."); @@ -552,6 +558,13 @@ namespace AzToolsFramework PrefabEntityResult PrefabPublicHandler::CreateEntity(AZ::EntityId parentId, const AZ::Vector3& position) { + // If the parent is invalid, parent to the container of the currently focused prefab. + if (!parentId.IsValid()) + { + AzFramework::EntityContextId editorEntityContextId = AzToolsFramework::GetEntityContextId(); + parentId = m_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId); + } + InstanceOptionalReference owningInstanceOfParentEntity = GetOwnerInstanceByEntityId(parentId); if (!owningInstanceOfParentEntity) { @@ -968,13 +981,13 @@ namespace AzToolsFramework return AZ::Failure(AZStd::string("No entities to duplicate.")); } - const EntityIdList entityIdsNoLevelInstance = GenerateEntityIdListWithoutLevelInstance(entityIds); - if (entityIdsNoLevelInstance.empty()) + const EntityIdList entityIdsNoFocusContainer = GenerateEntityIdListWithoutFocusedInstanceContainer(entityIds); + if (entityIdsNoFocusContainer.empty()) { - return AZ::Failure(AZStd::string("No entities to duplicate because only instance selected is the level instance.")); + return AZ::Failure(AZStd::string("No entities to duplicate because only instance selected is the container entity of the focused instance.")); } - if (!EntitiesBelongToSameInstance(entityIdsNoLevelInstance)) + if (!EntitiesBelongToSameInstance(entityIdsNoFocusContainer)) { return AZ::Failure(AZStd::string("Cannot duplicate multiple entities belonging to different instances with one operation." "Change your selection to contain entities in the same instance.")); @@ -982,7 +995,7 @@ namespace AzToolsFramework // We've already verified the entities are all owned by the same instance, // so we can just retrieve our instance from the first entity in the list. - AZ::EntityId firstEntityIdToDuplicate = entityIdsNoLevelInstance[0]; + AZ::EntityId firstEntityIdToDuplicate = entityIdsNoFocusContainer[0]; InstanceOptionalReference commonOwningInstance = GetOwnerInstanceByEntityId(firstEntityIdToDuplicate); if (!commonOwningInstance.has_value()) { @@ -1002,7 +1015,7 @@ namespace AzToolsFramework // This will cull out any entities that have ancestors in the list, since we will end up duplicating // the full nested hierarchy with what is returned from RetrieveAndSortPrefabEntitiesAndInstances - AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entityIdsNoLevelInstance); + AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entityIdsNoFocusContainer); AZ_PROFILE_FUNCTION(AzToolsFramework); @@ -1106,19 +1119,21 @@ namespace AzToolsFramework PrefabOperationResult PrefabPublicHandler::DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants) { - const EntityIdList entityIdsNoLevelInstance = GenerateEntityIdListWithoutLevelInstance(entityIds); + // Remove the container entity of the focused prefab from the list, if it is included. + const EntityIdList entityIdsNoFocusContainer = GenerateEntityIdListWithoutFocusedInstanceContainer(entityIds); - if (entityIdsNoLevelInstance.empty()) + if (entityIdsNoFocusContainer.empty()) { return AZ::Success(); } - if (!EntitiesBelongToSameInstance(entityIdsNoLevelInstance)) + // All entities in this list need to belong to the same prefab instance for the operation to be valid. + if (!EntitiesBelongToSameInstance(entityIdsNoFocusContainer)) { return AZ::Failure(AZStd::string("Cannot delete multiple entities belonging to different instances with one operation.")); } - AZ::EntityId firstEntityIdToDelete = entityIdsNoLevelInstance[0]; + AZ::EntityId firstEntityIdToDelete = entityIdsNoFocusContainer[0]; InstanceOptionalReference commonOwningInstance = GetOwnerInstanceByEntityId(firstEntityIdToDelete); // If the first entity id is a container entity id, then we need to mark its parent as the common owning instance because you @@ -1128,8 +1143,15 @@ namespace AzToolsFramework commonOwningInstance = commonOwningInstance->get().GetParentInstance(); } + // We only allow explicit deletions for entities inside the currently focused prefab. + AzFramework::EntityContextId editorEntityContextId = AzToolsFramework::GetEntityContextId(); + if (&m_prefabFocusInterface->GetFocusedPrefabInstance(editorEntityContextId)->get() != &commonOwningInstance->get()) + { + return AZ::Failure(AZStd::string("Cannot delete entities belonging to an instance that is not being edited.")); + } + // Retrieve entityList from entityIds - EntityList inputEntityList = EntityIdListToEntityList(entityIdsNoLevelInstance); + EntityList inputEntityList = EntityIdListToEntityList(entityIdsNoFocusContainer); AZ_PROFILE_FUNCTION(AzToolsFramework); @@ -1186,7 +1208,7 @@ namespace AzToolsFramework } else { - for (AZ::EntityId entityId : entityIdsNoLevelInstance) + for (AZ::EntityId entityId : entityIdsNoFocusContainer) { InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entityId); // If this is the container entity, it actually represents the instance so get its owner @@ -1227,9 +1249,12 @@ namespace AzToolsFramework return AZ::Failure(AZStd::string("Cannot detach Prefab Instance with invalid container entity.")); } - if (IsLevelInstanceContainerEntity(containerEntityId)) + auto editorEntityContextId = AzFramework::EntityContextId::CreateNull(); + EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); + + if (containerEntityId == m_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId)) { - return AZ::Failure(AZStd::string("Cannot detach level Prefab Instance.")); + return AZ::Failure(AZStd::string("Cannot detach focused Prefab Instance.")); } InstanceOptionalReference owningInstance = GetOwnerInstanceByEntityId(containerEntityId); @@ -1452,9 +1477,14 @@ namespace AzToolsFramework AZStd::queue entityQueue; + auto editorEntityContextId = AzFramework::EntityContextId::CreateNull(); + EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); + + AZ::EntityId focusedPrefabContainerEntityId = + m_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId); for (auto inputEntity : inputEntities) { - if (inputEntity && !IsLevelInstanceContainerEntity(inputEntity->GetId())) + if (inputEntity && inputEntity->GetId() != focusedPrefabContainerEntityId) { entityQueue.push(inputEntity); } @@ -1548,19 +1578,19 @@ namespace AzToolsFramework return AZ::Success(); } - EntityIdList PrefabPublicHandler::GenerateEntityIdListWithoutLevelInstance( + EntityIdList PrefabPublicHandler::GenerateEntityIdListWithoutFocusedInstanceContainer( const EntityIdList& entityIds) const { - EntityIdList outEntityIds; - outEntityIds.reserve(entityIds.size()); // Actual size could be smaller. + EntityIdList outEntityIds(entityIds); - for (const AZ::EntityId& entityId : entityIds) + AzFramework::EntityContextId editorEntityContextId = AzToolsFramework::GetEntityContextId(); + AZ::EntityId focusedInstanceContainerEntityId = m_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId); + + if (auto iter = AZStd::find(outEntityIds.begin(), outEntityIds.end(), focusedInstanceContainerEntityId); iter != outEntityIds.end()) { - if (!IsLevelInstanceContainerEntity(entityId)) - { - outEntityIds.emplace_back(entityId); - } + outEntityIds.erase(iter); } + return outEntityIds; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index f3c0e67d46..a9dadc3336 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -74,7 +74,7 @@ namespace AzToolsFramework Instance& commonRootEntityOwningInstance, EntityList& outEntities, AZStd::vector& outInstances) const; - EntityIdList GenerateEntityIdListWithoutLevelInstance(const EntityIdList& entityIds) const; + EntityIdList GenerateEntityIdListWithoutFocusedInstanceContainer(const EntityIdList& entityIds) const; InstanceOptionalReference GetOwnerInstanceByEntityId(AZ::EntityId entityId) const; bool EntitiesBelongToSameInstance(const EntityIdList& entityIds) const; @@ -187,6 +187,8 @@ namespace AzToolsFramework InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr; InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr; + PrefabFocusInterface* m_prefabFocusInterface = nullptr; + PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr; PrefabLoaderInterface* m_prefabLoaderInterface = nullptr; PrefabSystemComponentInterface* m_prefabSystemComponentInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 6ffa3aab69..16e3c047b5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -175,12 +176,16 @@ namespace AzToolsFramework AzFramework::ApplicationRequests::Bus::BroadcastResult( prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled); + auto editorEntityContextId = AzFramework::EntityContextId::CreateNull(); + EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); + // Create Prefab { if (!selectedEntities.empty()) { - // Hide if the only selected entity is the Level Container - if (selectedEntities.size() > 1 || !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntities[0])) + // Hide if the only selected entity is the Focused Instance Container + if (selectedEntities.size() > 1 || + selectedEntities[0] != s_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId)) { bool layerInSelection = false; @@ -247,14 +252,14 @@ namespace AzToolsFramework // Edit Prefab if (prefabWipFeaturesEnabled && !s_prefabFocusPublicInterface->IsOwningPrefabBeingFocused(selectedEntity)) { - QAction* editAction = menu->addAction(QObject::tr("Edit Prefab")); - editAction->setToolTip(QObject::tr("Edit the prefab in focus mode.")); + QAction* editAction = menu->addAction(QObject::tr("Edit Prefab")); + editAction->setToolTip(QObject::tr("Edit the prefab in focus mode.")); - QObject::connect(editAction, &QAction::triggered, editAction, [selectedEntity] { - ContextMenu_EditPrefab(selectedEntity); - }); + QObject::connect(editAction, &QAction::triggered, editAction, [selectedEntity] { + ContextMenu_EditPrefab(selectedEntity); + }); - itemWasShown = true; + itemWasShown = true; } // Save Prefab @@ -283,8 +288,9 @@ namespace AzToolsFramework QAction* deleteAction = menu->addAction(QObject::tr("Delete")); QObject::connect(deleteAction, &QAction::triggered, deleteAction, [] { ContextMenu_DeleteSelected(); }); - if (selectedEntities.size() == 0 || - (selectedEntities.size() == 1 && s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntities[0]))) + + if (selectedEntities.empty() || + (selectedEntities.size() == 1 && selectedEntities[0] == s_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId))) { deleteAction->setDisabled(true); } @@ -292,17 +298,17 @@ namespace AzToolsFramework // Detach Prefab if (selectedEntities.size() == 1) { - AZ::EntityId selectedEntity = selectedEntities[0]; + AZ::EntityId selectedEntityId = selectedEntities[0]; - if (s_prefabPublicInterface->IsInstanceContainerEntity(selectedEntity) && - !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntity)) + if (s_prefabPublicInterface->IsInstanceContainerEntity(selectedEntityId) && + selectedEntityId != s_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId)) { QAction* detachPrefabAction = menu->addAction(QObject::tr("Detach Prefab...")); QObject::connect( detachPrefabAction, &QAction::triggered, detachPrefabAction, - [selectedEntity] + [selectedEntityId] { - ContextMenu_DetachPrefab(selectedEntity); + ContextMenu_DetachPrefab(selectedEntityId); }); } } @@ -331,13 +337,21 @@ namespace AzToolsFramework QWidget* activeWindow = QApplication::activeWindow(); const AZStd::string prefabFilesPath = "@projectroot@/Prefabs"; - // Remove Level entity if it's part of the list - - auto levelContainerIter = - AZStd::find(selectedEntities.begin(), selectedEntities.end(), s_prefabPublicInterface->GetLevelInstanceContainerEntityId()); - if (levelContainerIter != selectedEntities.end()) + // Remove focused instance container entity if it's part of the list + auto editorEntityContextId = AzFramework::EntityContextId::CreateNull(); + EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId); + + auto focusedContainerIter = AZStd::find( + selectedEntities.begin(), selectedEntities.end(), + s_prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId)); + if (focusedContainerIter != selectedEntities.end()) { - selectedEntities.erase(levelContainerIter); + selectedEntities.erase(focusedContainerIter); + } + + if (selectedEntities.empty()) + { + return; } // Set default folder for prefabs diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp index 00522b29dc..ccad85e32b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp @@ -178,12 +178,6 @@ namespace AzToolsFramework AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); - // We hide the root instance container entity from the Outliner, so avoid drawing its full container on children - if (m_prefabPublicInterface->IsLevelInstanceContainerEntity(entityId)) - { - return; - } - const QTreeView* outlinerTreeView(qobject_cast(option.widget)); const int ancestorLeft = outlinerTreeView->visualRect(index).left() + (m_prefabBorderThickness / 2) - 1; const int curveRectSize = m_prefabCapsuleRadius * 2; From 0ace221eb82bace5eb5b1037beca199f99c29046 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Thu, 14 Oct 2021 18:13:32 -0500 Subject: [PATCH 40/52] Add '.' path to render doc include directories on windows Signed-off-by: rgba16f <82187279+rgba16f@users.noreply.github.com> --- Gems/Atom/RHI/3rdParty/Platform/Windows/renderdoc_windows.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/Atom/RHI/3rdParty/Platform/Windows/renderdoc_windows.cmake b/Gems/Atom/RHI/3rdParty/Platform/Windows/renderdoc_windows.cmake index 559863ca07..70c8564a82 100644 --- a/Gems/Atom/RHI/3rdParty/Platform/Windows/renderdoc_windows.cmake +++ b/Gems/Atom/RHI/3rdParty/Platform/Windows/renderdoc_windows.cmake @@ -7,3 +7,4 @@ # set(RENDERDOC_RUNTIME_DEPENDENCIES "${BASE_PATH}/renderdoc.dll") +set(RENDERDOC_INCLUDE_DIRECTORIES ".") From 3b9762142a198c6d35ddc8b9fa1ea492e41beffe Mon Sep 17 00:00:00 2001 From: moraaar Date: Fri, 15 Oct 2021 08:58:18 +0100 Subject: [PATCH 41/52] Triangle Mesh with a Kinematic PhysX Rigid Body warns the user instead of error. (#4657) Using triangle mesh with a kinematic rigid body is allowed, but the options "Compute COM", "Compute Mass" and "Compute Inertia" are not supported by PhysX and an error in logged that default values for COM, Mass and Inertia will be used. Now this situation is captured and an explanatory warning is used instead. - Improved RigidBody::UpdateMassProperties function to apply the same logic in the treatment of shapes for all three parameters: COM, Mass and Inertia. - Improved UpdateMassProperties function by using references for the override parameters instead of pointers. - Improved function that computes the Center of Mass UpdateCenterOfMass (renamed from UpdateComputedCenterOfMass), to include the same shapes that the compute mass and inertia functions in physx updateMassAndInertia, which is to include all shapes if includeAllShapesInMassCalculation is true, else include only the shapes with eSIMULATION_SHAPE flag. - Removed unused private function RigidBody::ComputeInertia. - Added unit test to check when the warnings are fired correctly when COM, Mass or Inertia are asked to be computed on a rigid body with triangle mesh shapes. - Improved MassComputeFixture tests by not only using Box shape, but also sphere and capture, plus improved the PossibleMassComputeFlags parameters to include all possible variations of the MassComputeFlags flags. Fixes #3322 Fixes #3979 Signed-off-by: moraaar --- .../AzFramework/Physics/RigidBody.h | 234 -------------- .../Physics/SimulatedBodies/RigidBody.h | 6 +- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 6 +- Gems/PhysX/Code/Source/RigidBody.cpp | 287 ++++++++++-------- Gems/PhysX/Code/Source/RigidBody.h | 10 +- Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 4 +- Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp | 223 ++++++++++---- Gems/PhysX/Code/Tests/PhysXTestCommon.cpp | 30 ++ Gems/PhysX/Code/Tests/PhysXTestCommon.h | 1 + .../Components/WhiteBoxColliderComponent.cpp | 5 + 10 files changed, 372 insertions(+), 434 deletions(-) delete mode 100644 Code/Framework/AzFramework/AzFramework/Physics/RigidBody.h diff --git a/Code/Framework/AzFramework/AzFramework/Physics/RigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/RigidBody.h deleted file mode 100644 index 13d29b6bb9..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Physics/RigidBody.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include - -#include -#include - -namespace -{ - class ReflectContext; -} - -namespace Physics -{ - class ShapeConfiguration; - class World; - class Shape; - - /// Default values used for initializing RigidBodySettings. - /// These can be modified by Physics Implementation gems. // O3DE_DEPRECATED(LY-114472) - DefaultRigidBodyConfiguration values are not shared across modules. - // Use RigidBodyConfiguration default values. - struct DefaultRigidBodyConfiguration - { - static float m_mass; - static bool m_computeInertiaTensor; - static float m_linearDamping; - static float m_angularDamping; - static float m_sleepMinEnergy; - static float m_maxAngularVelocity; - }; - - enum class MassComputeFlags : AZ::u8 - { - NONE = 0, - - //! Flags indicating whether a certain mass property should be auto-computed or not. - COMPUTE_MASS = 1, - COMPUTE_INERTIA = 1 << 1, - COMPUTE_COM = 1 << 2, - - //! If set, non-simulated shapes will also be included in the mass properties calculation. - INCLUDE_ALL_SHAPES = 1 << 3, - - DEFAULT = COMPUTE_COM | COMPUTE_INERTIA | COMPUTE_MASS - }; - - class RigidBodyConfiguration - : public WorldBodyConfiguration - { - public: - AZ_CLASS_ALLOCATOR(RigidBodyConfiguration, AZ::SystemAllocator, 0); - AZ_RTTI(RigidBodyConfiguration, "{ACFA8900-8530-4744-AF00-AA533C868A8E}", WorldBodyConfiguration); - static void Reflect(AZ::ReflectContext* context); - - enum PropertyVisibility : AZ::u16 - { - InitialVelocities = 1 << 0, ///< Whether the initial linear and angular velocities are visible. - InertiaProperties = 1 << 1, ///< Whether the whole category of inertia properties (mass, compute inertia, - ///< inertia tensor etc) is visible. - Damping = 1 << 2, ///< Whether linear and angular damping are visible. - SleepOptions = 1 << 3, ///< Whether the sleep threshold and start asleep options are visible. - Interpolation = 1 << 4, ///< Whether the interpolation option is visible. - Gravity = 1 << 5, ///< Whether the effected by gravity option is visible. - Kinematic = 1 << 6, ///< Whether the option to make the body kinematic is visible. - ContinuousCollisionDetection = 1 << 7, ///< Whether the option to enable continuous collision detection is visible. - MaxVelocities = 1 << 8 ///< Whether upper limits on velocities are visible. - }; - - RigidBodyConfiguration() = default; - RigidBodyConfiguration(const RigidBodyConfiguration& settings) = default; - - // Visibility functions. - AZ::Crc32 GetPropertyVisibility(PropertyVisibility property) const; - void SetPropertyVisibility(PropertyVisibility property, bool isVisible); - - AZ::Crc32 GetInitialVelocitiesVisibility() const; - /// Returns whether the whole category of inertia settings (mass, inertia, center of mass offset etc) is visible. - AZ::Crc32 GetInertiaSettingsVisibility() const; - /// Returns whether the individual inertia tensor field is visible or is hidden because the compute inertia option is selected. - AZ::Crc32 GetInertiaVisibility() const; - /// Returns whether the mass field is visible or is hidden because compute mass option is selected. - AZ::Crc32 GetMassVisibility() const; - /// Returns whether the individual centre of mass offset field is visible or is hidden because compute CoM option is selected. - AZ::Crc32 GetCoMVisibility() const; - AZ::Crc32 GetDampingVisibility() const; - AZ::Crc32 GetSleepOptionsVisibility() const; - AZ::Crc32 GetInterpolationVisibility() const; - AZ::Crc32 GetGravityVisibility() const; - AZ::Crc32 GetKinematicVisibility() const; - AZ::Crc32 GetCCDVisibility() const; - AZ::Crc32 GetMaxVelocitiesVisibility() const; - MassComputeFlags GetMassComputeFlags() const; - void SetMassComputeFlags(MassComputeFlags flags); - - bool IsCCDEnabled() const; - - // Basic initial settings. - AZ::Vector3 m_initialLinearVelocity = AZ::Vector3::CreateZero(); - AZ::Vector3 m_initialAngularVelocity = AZ::Vector3::CreateZero(); - AZ::Vector3 m_centerOfMassOffset = AZ::Vector3::CreateZero(); - - // Simulation parameters. - float m_mass = DefaultRigidBodyConfiguration::m_mass; - AZ::Matrix3x3 m_inertiaTensor = AZ::Matrix3x3::CreateIdentity(); - float m_linearDamping = DefaultRigidBodyConfiguration::m_linearDamping; - float m_angularDamping = DefaultRigidBodyConfiguration::m_angularDamping; - float m_sleepMinEnergy = DefaultRigidBodyConfiguration::m_sleepMinEnergy; - float m_maxAngularVelocity = DefaultRigidBodyConfiguration::m_maxAngularVelocity; - - // Visibility settings. - AZ::u16 m_propertyVisibilityFlags = (std::numeric_limits::max)(); - - bool m_startAsleep = false; - bool m_interpolateMotion = false; - bool m_gravityEnabled = true; - bool m_simulated = true; - bool m_kinematic = false; - bool m_ccdEnabled = false; ///< Whether continuous collision detection is enabled. - float m_ccdMinAdvanceCoefficient = 0.15f; ///< Coefficient affecting how granularly time is subdivided in CCD. - bool m_ccdFrictionEnabled = false; ///< Whether friction is applied when resolving CCD collisions. - - bool m_computeCenterOfMass = true; - bool m_computeInertiaTensor = true; - bool m_computeMass = true; - - //! If set, non-simulated shapes will also be included in the mass properties calculation. - bool m_includeAllShapesInMassCalculation = false; - }; - - /// Dynamic rigid body. - class RigidBody - : public WorldBody - { - public: - - AZ_CLASS_ALLOCATOR(RigidBody, AZ::SystemAllocator, 0); - AZ_RTTI(RigidBody, "{156E459F-7BB7-4B4E-ADA0-2130D96B7E80}", WorldBody); - - public: - RigidBody() = default; - explicit RigidBody(const RigidBodyConfiguration& settings); - - - virtual void AddShape(AZStd::shared_ptr shape) = 0; - virtual void RemoveShape(AZStd::shared_ptr shape) = 0; - virtual AZ::u32 GetShapeCount() { return 0; } - virtual AZStd::shared_ptr GetShape(AZ::u32 /*index*/) { return nullptr; } - - virtual AZ::Vector3 GetCenterOfMassWorld() const = 0; - virtual AZ::Vector3 GetCenterOfMassLocal() const = 0; - - virtual AZ::Matrix3x3 GetInverseInertiaWorld() const = 0; - virtual AZ::Matrix3x3 GetInverseInertiaLocal() const = 0; - - virtual float GetMass() const = 0; - virtual float GetInverseMass() const = 0; - virtual void SetMass(float mass) = 0; - virtual void SetCenterOfMassOffset(const AZ::Vector3& comOffset) = 0; - - /// Retrieves the velocity at center of mass; only linear velocity, no rotational velocity contribution. - virtual AZ::Vector3 GetLinearVelocity() const = 0; - virtual void SetLinearVelocity(const AZ::Vector3& velocity) = 0; - virtual AZ::Vector3 GetAngularVelocity() const = 0; - virtual void SetAngularVelocity(const AZ::Vector3& angularVelocity) = 0; - virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) = 0; - virtual void ApplyLinearImpulse(const AZ::Vector3& impulse) = 0; - virtual void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) = 0; - virtual void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) = 0; - - virtual float GetLinearDamping() const = 0; - virtual void SetLinearDamping(float damping) = 0; - virtual float GetAngularDamping() const = 0; - virtual void SetAngularDamping(float damping) = 0; - - virtual bool IsAwake() const = 0; - virtual void ForceAsleep() = 0; - virtual void ForceAwake() = 0; - virtual float GetSleepThreshold() const = 0; - virtual void SetSleepThreshold(float threshold) = 0; - - virtual bool IsKinematic() const = 0; - virtual void SetKinematic(bool kinematic) = 0; - virtual void SetKinematicTarget(const AZ::Transform& targetPosition) = 0; - - virtual bool IsGravityEnabled() const = 0; - virtual void SetGravityEnabled(bool enabled) = 0; - virtual void SetSimulationEnabled(bool enabled) = 0; - virtual void SetCCDEnabled(bool enabled) = 0; - - //! Recalculates mass, inertia and center of mass based on the flags passed. - //! @param flags MassComputeFlags specifying which properties should be recomputed. - //! @param centerOfMassOffsetOverride Optional override of the center of mass. Note: This parameter will be ignored if COMPUTE_COM is passed in flags. - //! @param inertiaTensorOverride Optional override of the inertia. Note: This parameter will be ignored if COMPUTE_INERTIA is passed in flags. - //! @param massOverride Optional override of the mass. Note: This parameter will be ignored if COMPUTE_MASS is passed in flags. - virtual void UpdateMassProperties(MassComputeFlags flags = MassComputeFlags::DEFAULT, - const AZ::Vector3* centerOfMassOffsetOverride = nullptr, - const AZ::Matrix3x3* inertiaTensorOverride = nullptr, - const float* massOverride = nullptr) = 0; - }; - - /// Bitwise operators for MassComputeFlags - inline MassComputeFlags operator|(MassComputeFlags lhs, MassComputeFlags rhs) - { - return aznumeric_cast(aznumeric_cast(lhs) | aznumeric_cast(rhs)); - } - - inline MassComputeFlags operator&(MassComputeFlags lhs, MassComputeFlags rhs) - { - return aznumeric_cast(aznumeric_cast(lhs) & aznumeric_cast(rhs)); - } - - /// Static rigid body. - class RigidBodyStatic - : public WorldBody - { - public: - AZ_CLASS_ALLOCATOR(RigidBodyStatic, AZ::SystemAllocator, 0); - AZ_RTTI(RigidBodyStatic, "{13A677BB-7085-4EDB-BCC8-306548238692}", WorldBody); - - virtual void AddShape(const AZStd::shared_ptr& shape) = 0; - virtual AZ::u32 GetShapeCount() { return 0; } - virtual AZStd::shared_ptr GetShape(AZ::u32 /*index*/) { return nullptr; } - }; -} // namespace Physics diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h index 3c0a1afa1d..e9bf8a7307 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h @@ -89,9 +89,9 @@ namespace AzPhysics //! @param inertiaTensorOverride Optional override of the inertia. Note: This parameter will be ignored if COMPUTE_INERTIA is passed in flags. //! @param massOverride Optional override of the mass. Note: This parameter will be ignored if COMPUTE_MASS is passed in flags. virtual void UpdateMassProperties(MassComputeFlags flags = MassComputeFlags::DEFAULT, - const AZ::Vector3* centerOfMassOffsetOverride = nullptr, - const AZ::Matrix3x3* inertiaTensorOverride = nullptr, - const float* massOverride = nullptr) = 0; + const AZ::Vector3& centerOfMassOffsetOverride = AZ::Vector3::CreateZero(), + const AZ::Matrix3x3& inertiaTensorOverride = AZ::Matrix3x3::CreateIdentity(), + const float massOverride = 1.0f) = 0; }; } // namespace AzPhysics diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index dddd1e275a..1fe6e35d75 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -344,9 +344,9 @@ namespace Blast void UpdateMassProperties( [[maybe_unused]] AzPhysics::MassComputeFlags flags, - [[maybe_unused]] const AZ::Vector3* centerOfMassOffsetOverride, - [[maybe_unused]] const AZ::Matrix3x3* inertiaTensorOverride, - [[maybe_unused]] const float* massOverride) override + [[maybe_unused]] const AZ::Vector3& centerOfMassOffsetOverride, + [[maybe_unused]] const AZ::Matrix3x3& inertiaTensorOverride, + [[maybe_unused]] const float massOverride) override { } diff --git a/Gems/PhysX/Code/Source/RigidBody.cpp b/Gems/PhysX/Code/Source/RigidBody.cpp index f8b22affe0..5b36376da5 100644 --- a/Gems/PhysX/Code/Source/RigidBody.cpp +++ b/Gems/PhysX/Code/Source/RigidBody.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -23,6 +24,28 @@ namespace PhysX { + namespace + { + const AZ::Vector3 DefaultCenterOfMass = AZ::Vector3::CreateZero(); + const float DefaultMass = 1.0f; + const AZ::Matrix3x3 DefaultInertiaTensor = AZ::Matrix3x3::CreateIdentity(); + + bool IsSimulationShape(const physx::PxShape& pxShape) + { + return (pxShape.getFlags() & physx::PxShapeFlag::eSIMULATION_SHAPE); + } + + bool CanShapeComputeMassProperties(const physx::PxShape& pxShape) + { + // Note: List based on computeMassAndInertia function in ExtRigidBodyExt.cpp file in PhysX. + const physx::PxGeometryType::Enum geometryType = pxShape.getGeometryType(); + return geometryType == physx::PxGeometryType::eSPHERE + || geometryType == physx::PxGeometryType::eBOX + || geometryType == physx::PxGeometryType::eCAPSULE + || geometryType == physx::PxGeometryType::eCONVEXMESH; + } + } + void RigidBody::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); @@ -152,104 +175,120 @@ namespace PhysX m_shapes.erase(found); } - void RigidBody::UpdateMassProperties(AzPhysics::MassComputeFlags flags, const AZ::Vector3* centerOfMassOffsetOverride, const AZ::Matrix3x3* inertiaTensorOverride, const float* massOverride) + void RigidBody::UpdateMassProperties(AzPhysics::MassComputeFlags flags, const AZ::Vector3& centerOfMassOffsetOverride, const AZ::Matrix3x3& inertiaTensorOverride, const float massOverride) { - // Input validation - bool computeCenterOfMass = AzPhysics::MassComputeFlags::COMPUTE_COM == (flags & AzPhysics::MassComputeFlags::COMPUTE_COM); - AZ_Assert(computeCenterOfMass || centerOfMassOffsetOverride, - "UpdateMassProperties: MassComputeFlags::COMPUTE_COM is not set but COM offset is not specified"); - computeCenterOfMass = computeCenterOfMass || !centerOfMassOffsetOverride; + const bool computeCenterOfMass = AzPhysics::MassComputeFlags::COMPUTE_COM == (flags & AzPhysics::MassComputeFlags::COMPUTE_COM); + const bool computeInertiaTensor = AzPhysics::MassComputeFlags::COMPUTE_INERTIA == (flags & AzPhysics::MassComputeFlags::COMPUTE_INERTIA); + const bool computeMass = AzPhysics::MassComputeFlags::COMPUTE_MASS == (flags & AzPhysics::MassComputeFlags::COMPUTE_MASS); + const bool needsCompute = computeCenterOfMass || computeInertiaTensor || computeMass; + const bool includeAllShapesInMassCalculation = AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES == (flags & AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES); - bool computeInertiaTensor = AzPhysics::MassComputeFlags::COMPUTE_INERTIA == (flags & AzPhysics::MassComputeFlags::COMPUTE_INERTIA); - AZ_Assert(computeInertiaTensor || inertiaTensorOverride, - "UpdateMassProperties: MassComputeFlags::COMPUTE_INERTIA is not set but inertia tensor is not specified"); - computeInertiaTensor = computeInertiaTensor || !inertiaTensorOverride; - - bool computeMass = AzPhysics::MassComputeFlags::COMPUTE_MASS == (flags & AzPhysics::MassComputeFlags::COMPUTE_MASS); - AZ_Assert(computeMass || massOverride, - "UpdateMassProperties: MassComputeFlags::COMPUTE_MASS is not set but mass is not specified"); - computeMass = computeMass || !massOverride; - - AZ::u32 shapesCount = GetShapeCount(); - - // Basic cases when we don't need to compute anything - if (shapesCount == 0 || flags == AzPhysics::MassComputeFlags::NONE) + // Basic case where all properties are set directly. + if (!needsCompute) { - if (massOverride) - { - SetMass(*massOverride); - } - - if (inertiaTensorOverride) - { - SetInertia(*inertiaTensorOverride); - } - - if (centerOfMassOffsetOverride) - { - SetCenterOfMassOffset(*centerOfMassOffsetOverride); - } + SetCenterOfMassOffset(centerOfMassOffsetOverride); + SetMass(massOverride); + SetInertia(inertiaTensorOverride); return; } - // Setup center of mass offset pointer for PxRigidBodyExt::updateMassAndInertia function - AZStd::optional optionalComOverride; - if (!computeCenterOfMass && centerOfMassOffsetOverride) + // If there are no shapes then set the properties directly without computing anything. + if (m_shapes.empty()) { - optionalComOverride = PxMathConvert(*centerOfMassOffsetOverride); - } - - const physx::PxVec3* massLocalPose = optionalComOverride.has_value() ? &optionalComOverride.value() : nullptr; - - bool includeAllShapesInMassCalculation = - AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES == (flags & AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES); - - // Handle the case when we don't compute mass - if (!computeMass) - { - { - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - physx::PxRigidBodyExt::setMassAndUpdateInertia(*m_pxRigidActor, *massOverride, massLocalPose, - includeAllShapesInMassCalculation); - } - - if (!computeInertiaTensor) - { - SetInertia(*inertiaTensorOverride); - } - + SetCenterOfMassOffset(computeCenterOfMass ? DefaultCenterOfMass : centerOfMassOffsetOverride); + SetMass(computeMass ? DefaultMass : massOverride); + SetInertia(computeInertiaTensor ? DefaultInertiaTensor : inertiaTensorOverride); return; } - // Handle the cases when mass should be computed from density - if (shapesCount == 1) + auto cannotComputeMassProperties = [this, includeAllShapesInMassCalculation] { - AZStd::shared_ptr shape = GetShape(0); - float density = shape->GetMaterial()->GetDensity(); + PHYSX_SCENE_READ_LOCK(m_pxRigidActor->getScene()); + return AZStd::any_of(m_shapes.cbegin(), m_shapes.cend(), + [includeAllShapesInMassCalculation](const AZStd::shared_ptr& shape) + { + const physx::PxShape& pxShape = *shape->GetPxShape(); + const bool includeShape = includeAllShapesInMassCalculation || IsSimulationShape(pxShape); - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - physx::PxRigidBodyExt::updateMassAndInertia(*m_pxRigidActor, density, massLocalPose, - includeAllShapesInMassCalculation); + return includeShape && !CanShapeComputeMassProperties(pxShape); + }); + }; + + // If contains shapes that cannot compute mass properties (triangle mesh, + // plane or heightfield) then default values will be used. + if (cannotComputeMassProperties()) + { + AZ_Warning("RigidBody", !computeCenterOfMass, + "Rigid body '%s' cannot compute COM because it contains triangle mesh, plane or heightfield shapes, it will default to %s.", + GetName().c_str(), AZ::ToString(DefaultCenterOfMass).c_str()); + AZ_Warning("RigidBody", !computeMass, + "Rigid body '%s' cannot compute Mass because it contains triangle mesh, plane or heightfield shapes, it will default to %0.1f.", + GetName().c_str(), DefaultMass); + AZ_Warning("RigidBody", !computeInertiaTensor, + "Rigid body '%s' cannot compute Inertia because it contains triangle mesh, plane or heightfield shapes, it will default to %s.", + GetName().c_str(), AZ::ToString(DefaultInertiaTensor.RetrieveScale()).c_str()); + + SetCenterOfMassOffset(computeCenterOfMass ? DefaultCenterOfMass : centerOfMassOffsetOverride); + SetMass(computeMass ? DefaultMass : massOverride); + SetInertia(computeInertiaTensor ? DefaultInertiaTensor : inertiaTensorOverride); + return; + } + + // Center of mass needs to be considered first since + // it's needed when computing mass and inertia. + if (computeCenterOfMass) + { + // Compute Center of Mass + UpdateCenterOfMass(includeAllShapesInMassCalculation); } else { - AZStd::vector densities(shapesCount); - for (AZ::u32 i = 0; i < shapesCount; ++i) + SetCenterOfMassOffset(centerOfMassOffsetOverride); + } + const physx::PxVec3 pxCenterOfMass = PxMathConvert(GetCenterOfMassLocal()); + + if (computeMass) + { + // Gather material densities from all shapes, + // mass computation is based on them. + AZStd::vector densities; + densities.reserve(m_shapes.size()); + for (const auto& shape : m_shapes) { - densities[i] = GetShape(i)->GetMaterial()->GetDensity(); + densities.emplace_back(shape->GetMaterial()->GetDensity()); } - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - physx::PxRigidBodyExt::updateMassAndInertia(*m_pxRigidActor, densities.data(), - shapesCount, massLocalPose, includeAllShapesInMassCalculation); - } + // Compute Mass + Inertia + { + PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); + physx::PxRigidBodyExt::updateMassAndInertia(*m_pxRigidActor, + densities.data(), static_cast(densities.size()), + &pxCenterOfMass, includeAllShapesInMassCalculation); + } - // Set the overrides if provided. - // Note: We don't set the center of mass here because it was already provided - // to PxRigidBodyExt::updateMassAndInertia above - if (!computeInertiaTensor) + // There is no physx function to only compute the mass without + // computing the inertia. So now that both have been computed + // we can override the inertia if it's suppose to use a + // specific value set by the user. + if (!computeInertiaTensor) + { + SetInertia(inertiaTensorOverride); + } + } + else { - SetInertia(*inertiaTensorOverride); + if (computeInertiaTensor) + { + // Set Mass + Compute Inertia + PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); + physx::PxRigidBodyExt::setMassAndUpdateInertia(*m_pxRigidActor, massOverride, + &pxCenterOfMass, includeAllShapesInMassCalculation); + } + else + { + SetMass(massOverride); + SetInertia(inertiaTensorOverride); + } } } @@ -344,52 +383,49 @@ namespace PhysX } } - void RigidBody::UpdateComputedCenterOfMass() + void RigidBody::UpdateCenterOfMass(bool includeAllShapesInMassCalculation) { - if (m_pxRigidActor) + if (m_shapes.empty()) { - physx::PxU32 shapeCount = 0; + SetCenterOfMassOffset(DefaultCenterOfMass); + return; + } + + AZStd::vector pxShapes; + pxShapes.reserve(m_shapes.size()); + { + // Filter shapes in the same way that updateMassAndInertia function does. + PHYSX_SCENE_READ_LOCK(m_pxRigidActor->getScene()); + for (const auto& shape : m_shapes) { - PHYSX_SCENE_READ_LOCK(m_pxRigidActor->getScene()); - shapeCount = m_pxRigidActor->getNbShapes(); - } - if (shapeCount > 0) - { - AZStd::vector shapes; - shapes.resize(shapeCount); + const physx::PxShape& pxShape = *shape->GetPxShape(); + const bool includeShape = includeAllShapesInMassCalculation || IsSimulationShape(pxShape); + if (includeShape && CanShapeComputeMassProperties(pxShape)) { - PHYSX_SCENE_READ_LOCK(m_pxRigidActor->getScene()); - m_pxRigidActor->getShapes(&shapes[0], shapeCount); + pxShapes.emplace_back(&pxShape); } - - shapes.erase(AZStd::remove_if(shapes.begin() - , shapes.end() - , [](const physx::PxShape* shape) - { - return shape->getFlags() & physx::PxShapeFlag::eTRIGGER_SHAPE; - }) - , shapes.end()); - shapeCount = static_cast(shapes.size()); - - if (shapeCount == 0) - { - SetZeroCenterOfMass(); - return; - } - - const auto properties = physx::PxRigidBodyExt::computeMassPropertiesFromShapes(&shapes[0], shapeCount); - const physx::PxTransform computedCenterOfMass(properties.centerOfMass); - { - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - m_pxRigidActor->setCMassLocalPose(computedCenterOfMass); - } - } - else - { - SetZeroCenterOfMass(); } } + + if (pxShapes.empty()) + { + SetCenterOfMassOffset(DefaultCenterOfMass); + return; + } + + const physx::PxMassProperties pxMassProperties = [this, &pxShapes] + { + // Note: PhysX computeMassPropertiesFromShapes function does not use densities + // to compute the shape's masses, which are needed to calculate the center of mass. + // This differs from updateMassAndInertia function, which uses material density values. + // So the masses used during center of mass calculation do not match the masses + // used during mass/inertia calculation. This is an inconsistency in PhysX. + PHYSX_SCENE_READ_LOCK(m_pxRigidActor->getScene()); + return physx::PxRigidBodyExt::computeMassPropertiesFromShapes(pxShapes.data(), static_cast(pxShapes.size())); + }(); + + SetCenterOfMassOffset(PxMathConvert(pxMassProperties.centerOfMass)); } void RigidBody::SetInertia(const AZ::Matrix3x3& inertia) @@ -401,16 +437,6 @@ namespace PhysX } } - void RigidBody::ComputeInertia() - { - if (m_pxRigidActor) - { - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - auto localPose = m_pxRigidActor->getCMassLocalPose().p; - physx::PxRigidBodyExt::setMassAndUpdateInertia(*m_pxRigidActor, m_pxRigidActor->getMass(), &localPose); - } - } - AZ::Vector3 RigidBody::GetLinearVelocity() const { if (m_pxRigidActor) @@ -783,13 +809,4 @@ namespace PhysX { return m_name; } - - void RigidBody::SetZeroCenterOfMass() - { - if (m_pxRigidActor) - { - PHYSX_SCENE_WRITE_LOCK(m_pxRigidActor->getScene()); - m_pxRigidActor->setCMassLocalPose(physx::PxTransform(PxMathConvert(AZ::Vector3::CreateZero()))); - } - } } diff --git a/Gems/PhysX/Code/Source/RigidBody.h b/Gems/PhysX/Code/Source/RigidBody.h index 10f2ebb556..a20f79b161 100644 --- a/Gems/PhysX/Code/Source/RigidBody.h +++ b/Gems/PhysX/Code/Source/RigidBody.h @@ -109,17 +109,15 @@ namespace PhysX void RemoveShape(AZStd::shared_ptr shape) override; void UpdateMassProperties(AzPhysics::MassComputeFlags flags = AzPhysics::MassComputeFlags::DEFAULT, - const AZ::Vector3* centerOfMassOffsetOverride = nullptr, - const AZ::Matrix3x3* inertiaTensorOverride = nullptr, - const float* massOverride = nullptr) override; + const AZ::Vector3& centerOfMassOffsetOverride = AZ::Vector3::CreateZero(), + const AZ::Matrix3x3& inertiaTensorOverride = AZ::Matrix3x3::CreateIdentity(), + const float massOverride = 1.0f) override; private: void CreatePhysXActor(const AzPhysics::RigidBodyConfiguration& configuration); - void UpdateComputedCenterOfMass(); - void ComputeInertia(); + void UpdateCenterOfMass(bool includeAllShapesInMassCalculation); void SetInertia(const AZ::Matrix3x3& inertia); - void SetZeroCenterOfMass(); AZStd::shared_ptr m_pxRigidActor; AZStd::vector> m_shapes; diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 3b5c98ba2d..86e3ceb98f 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -198,8 +198,8 @@ namespace PhysX AZ_Warning("PhysXScene", shapeAdded, "No Collider or Shape information found when creating Rigid body [%s]", configuration->m_debugName.c_str()); } const AzPhysics::MassComputeFlags& flags = configuration->GetMassComputeFlags(); - newBody->UpdateMassProperties(flags, &configuration->m_centerOfMassOffset, - &configuration->m_inertiaTensor, &configuration->m_mass); + newBody->UpdateMassProperties(flags, configuration->m_centerOfMassOffset, + configuration->m_inertiaTensor, configuration->m_mass); crc = AZ::Crc32(newBody, sizeof(*newBody)); return newBody; diff --git a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp index 0c0eee3eb0..9e3a738370 100644 --- a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp @@ -12,6 +12,8 @@ #include #include #include +#include +#include #include #include @@ -1283,11 +1285,13 @@ namespace PhysX EXPECT_TRUE(AZ::IsClose(expectedMass, mass, 0.001f)); } + // Valid material density values: [0.01f, 1e5f] INSTANTIATE_TEST_CASE_P(PhysX, MultiShapesDensityTestFixture, ::testing::Values( - AZStd::make_pair(std::numeric_limits::min(), std::numeric_limits::max()), - AZStd::make_pair(-std::numeric_limits::max(), 0.0f), - AZStd::make_pair(1.0f, 1e9f) + AZStd::make_pair(0.01f, 0.01f), + AZStd::make_pair(1e5f, 1e5f), + AZStd::make_pair(0.01f, 1e5f), + AZStd::make_pair(2364.0f, 10.0f) )); // Fixture for testing extreme density values @@ -1311,6 +1315,7 @@ namespace PhysX && resultingDensity <= Physics::MaterialConfiguration::MaxDensityLimit); } + // Valid material density values: [0.01f, 1e5f] INSTANTIATE_TEST_CASE_P(PhysX, DensityBoundariesTestFixture, ::testing::Values( std::numeric_limits::min(), @@ -1318,7 +1323,9 @@ namespace PhysX -std::numeric_limits::max(), 0.0f, 1.0f, - 1e9f + 1e9f, + 0.01f, + 1e5f )); enum class SimulatedShapesMode @@ -1329,7 +1336,7 @@ namespace PhysX }; class MassComputeFixture - : public ::testing::TestWithParam<::testing::tuple> + : public ::testing::TestWithParam<::testing::tuple> { public: void SetUp() override final @@ -1349,6 +1356,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandle simBodyHandle = sceneInterface->AddSimulatedBody(m_testSceneHandle, &m_rigidBodyConfig); m_rigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_testSceneHandle, simBodyHandle)); } + + ASSERT_TRUE(m_rigidBody != nullptr); } void TearDown() override final @@ -1363,130 +1372,242 @@ namespace PhysX m_rigidBody = nullptr; } - SimulatedShapesMode GetShapesMode() const + Physics::ShapeType GetShapeType() const { return ::testing::get<0>(GetParam()); } - AzPhysics::MassComputeFlags GetMassComputeFlags() const + SimulatedShapesMode GetShapesMode() const { return ::testing::get<1>(GetParam()); } + AzPhysics::MassComputeFlags GetMassComputeFlags() const + { + const AzPhysics::MassComputeFlags massComputeFlags = ::testing::get<2>(GetParam()); + if (IncludeAllShapes()) + { + return massComputeFlags | AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES; + } + else + { + return massComputeFlags; + } + } + + bool IncludeAllShapes() const + { + return ::testing::get<3>(GetParam()); + } + bool IsMultiShapeTest() const { - return ::testing::get<2>(GetParam()); + return ::testing::get<4>(GetParam()); } bool IsMassExpectedToChange() const { return m_rigidBodyConfig.m_computeMass && - (!(GetShapesMode() == SimulatedShapesMode::NONE) || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); + (GetShapesMode() != SimulatedShapesMode::NONE || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); } bool IsComExpectedToChange() const { return m_rigidBodyConfig.m_computeCenterOfMass && - (!(GetShapesMode() == SimulatedShapesMode::NONE) || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); + (GetShapesMode() != SimulatedShapesMode::NONE || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); } bool IsInertiaExpectedToChange() const { return m_rigidBodyConfig.m_computeInertiaTensor && - (!(GetShapesMode() == SimulatedShapesMode::NONE) || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); + (GetShapesMode() != SimulatedShapesMode::NONE || m_rigidBodyConfig.m_includeAllShapesInMassCalculation); } + AZStd::shared_ptr CreateShape(const Physics::ColliderConfiguration& colliderConfiguration, Physics::ShapeType shapeType) + { + AZStd::shared_ptr shape; + Physics::System* physics = AZ::Interface::Get(); + switch (shapeType) + { + case Physics::ShapeType::Sphere: + shape = physics->CreateShape(colliderConfiguration, Physics::SphereShapeConfiguration()); + break; + case Physics::ShapeType::Box: + shape = physics->CreateShape(colliderConfiguration, Physics::BoxShapeConfiguration()); + break; + case Physics::ShapeType::Capsule: + shape = physics->CreateShape(colliderConfiguration, Physics::CapsuleShapeConfiguration()); + break; + } + return shape; + }; + AzPhysics::RigidBodyConfiguration m_rigidBodyConfig; - AzPhysics::RigidBody* m_rigidBody; + AzPhysics::RigidBody* m_rigidBody = nullptr; AzPhysics::SceneHandle m_testSceneHandle = AzPhysics::InvalidSceneHandle; }; TEST_P(MassComputeFixture, RigidBody_ComputeMassFlagsCombinationsTwoShapes_MassPropertiesCalculatedAccordingly) { - SimulatedShapesMode shapeMode = GetShapesMode(); - AzPhysics::MassComputeFlags massComputeFlags = GetMassComputeFlags(); - bool multiShapeTest = IsMultiShapeTest(); - Physics::System* physics = AZ::Interface::Get(); + const Physics::ShapeType shapeType = GetShapeType(); + const SimulatedShapesMode shapeMode = GetShapesMode(); + const AzPhysics::MassComputeFlags massComputeFlags = GetMassComputeFlags(); + const bool multiShapeTest = IsMultiShapeTest(); // Save initial values - AZ::Vector3 comBefore = m_rigidBody->GetCenterOfMassWorld(); - AZ::Matrix3x3 inertiaBefore = m_rigidBody->GetInverseInertiaWorld(); - float massBefore = m_rigidBody->GetMass(); + const AZ::Vector3 comBefore = m_rigidBody->GetCenterOfMassWorld(); + const AZ::Matrix3x3 inertiaBefore = m_rigidBody->GetInverseInertiaWorld(); + const float massBefore = m_rigidBody->GetMass(); - // Box shape will be simulated for ALL and MIXED shape modes - Physics::ColliderConfiguration boxColliderConfig; - boxColliderConfig.m_isSimulated = + // Shape will be simulated for ALL and MIXED shape modes + Physics::ColliderConfiguration colliderConfig; + colliderConfig.m_isSimulated = (shapeMode == SimulatedShapesMode::ALL || shapeMode == SimulatedShapesMode::MIXED); - boxColliderConfig.m_position = AZ::Vector3(1.0f, 0.0f, 0.0f); + colliderConfig.m_position = AZ::Vector3(1.0f, 0.0f, 0.0f); - AZStd::shared_ptr boxShape = - physics->CreateShape(boxColliderConfig, Physics::BoxShapeConfiguration()); - m_rigidBody->AddShape(boxShape); + AZStd::shared_ptr shape = CreateShape(colliderConfig, shapeType); + m_rigidBody->AddShape(shape); if (multiShapeTest) { // Sphere shape will be simulated only for the ALL shape mode Physics::ColliderConfiguration sphereColliderConfig; sphereColliderConfig.m_isSimulated = (shapeMode == SimulatedShapesMode::ALL); - sphereColliderConfig.m_position = AZ::Vector3(-1.0f, 0.0f, 0.0f); - AZStd::shared_ptr sphereShape = - physics->CreateShape(sphereColliderConfig, Physics::SphereShapeConfiguration()); + sphereColliderConfig.m_position = AZ::Vector3(-2.0f, 0.0f, 0.0f); + AZStd::shared_ptr sphereShape = CreateShape(sphereColliderConfig, Physics::ShapeType::Sphere); m_rigidBody->AddShape(sphereShape); } // Verify swapping materials results in changes in the mass. - m_rigidBody->UpdateMassProperties(massComputeFlags, &m_rigidBodyConfig.m_centerOfMassOffset, - &m_rigidBodyConfig.m_inertiaTensor, &m_rigidBodyConfig.m_mass); + m_rigidBody->UpdateMassProperties(massComputeFlags, m_rigidBodyConfig.m_centerOfMassOffset, + m_rigidBodyConfig.m_inertiaTensor, m_rigidBodyConfig.m_mass); - float massAfter = m_rigidBody->GetMass(); - AZ::Vector3 comAfter = m_rigidBody->GetCenterOfMassWorld(); - AZ::Matrix3x3 inertiaAfter = m_rigidBody->GetInverseInertiaWorld(); + const float massAfter = m_rigidBody->GetMass(); + const AZ::Vector3 comAfter = m_rigidBody->GetCenterOfMassWorld(); + const AZ::Matrix3x3 inertiaAfter = m_rigidBody->GetInverseInertiaWorld(); + using ::testing::Not; + using ::testing::FloatNear; + using ::UnitTest::IsClose; if (IsMassExpectedToChange()) { - EXPECT_FALSE(AZ::IsClose(massBefore, massAfter, FLT_EPSILON)); + EXPECT_THAT(massBefore, Not(FloatNear(massAfter, FLT_EPSILON))); } else { - EXPECT_TRUE(AZ::IsClose(massBefore, massAfter, FLT_EPSILON)); + EXPECT_THAT(massBefore, FloatNear(massAfter, FLT_EPSILON)); } if (IsComExpectedToChange()) { - EXPECT_FALSE(comBefore.IsClose(comAfter)); + EXPECT_THAT(comBefore, Not(IsClose(comAfter))); } else { - EXPECT_TRUE(comBefore.IsClose(comAfter)); + EXPECT_THAT(comBefore, IsClose(comAfter)); } if (IsInertiaExpectedToChange()) { - EXPECT_FALSE(inertiaBefore.IsClose(inertiaAfter)); + EXPECT_THAT(inertiaBefore, Not(IsClose(inertiaAfter))); } else { - EXPECT_TRUE(inertiaBefore.IsClose(inertiaAfter)); + EXPECT_THAT(inertiaBefore, IsClose(inertiaAfter)); } } - AzPhysics::MassComputeFlags possibleMassComputeFlags[] = { - AzPhysics::MassComputeFlags::NONE, AzPhysics::MassComputeFlags::DEFAULT, AzPhysics::MassComputeFlags::COMPUTE_MASS, - AzPhysics::MassComputeFlags::COMPUTE_COM, AzPhysics::MassComputeFlags::COMPUTE_INERTIA, - AzPhysics::MassComputeFlags::DEFAULT | AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES, - AzPhysics::MassComputeFlags::COMPUTE_COM, AzPhysics::MassComputeFlags::COMPUTE_INERTIA, AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES, + static const AzPhysics::MassComputeFlags PossibleMassComputeFlags[] = + { + // No compute + AzPhysics::MassComputeFlags::NONE, + + // Compute Mass only + AzPhysics::MassComputeFlags::COMPUTE_MASS, + + // Compute Inertia only + AzPhysics::MassComputeFlags::COMPUTE_INERTIA, + + // Compute COM only + AzPhysics::MassComputeFlags::COMPUTE_COM, + + // Compute combinations of 2 AzPhysics::MassComputeFlags::COMPUTE_MASS | AzPhysics::MassComputeFlags::COMPUTE_COM, - AzPhysics::MassComputeFlags::COMPUTE_MASS | AzPhysics::MassComputeFlags::COMPUTE_COM | AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES, AzPhysics::MassComputeFlags::COMPUTE_MASS | AzPhysics::MassComputeFlags::COMPUTE_INERTIA, - AzPhysics::MassComputeFlags::COMPUTE_MASS | AzPhysics::MassComputeFlags::COMPUTE_INERTIA | AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES, AzPhysics::MassComputeFlags::COMPUTE_COM | AzPhysics::MassComputeFlags::COMPUTE_INERTIA, - AzPhysics::MassComputeFlags::COMPUTE_COM | AzPhysics::MassComputeFlags::COMPUTE_INERTIA | AzPhysics::MassComputeFlags::INCLUDE_ALL_SHAPES + + // Compute all + AzPhysics::MassComputeFlags::DEFAULT, // COMPUTE_COM | COMPUTE_INERTIA | COMPUTE_MASS }; INSTANTIATE_TEST_CASE_P(PhysX, MassComputeFixture, ::testing::Combine( - ::testing::ValuesIn({ SimulatedShapesMode::NONE, SimulatedShapesMode::MIXED, SimulatedShapesMode::ALL }), - ::testing::ValuesIn(possibleMassComputeFlags), - ::testing::Bool())); + ::testing::ValuesIn({ Physics::ShapeType::Sphere, Physics::ShapeType::Box, Physics::ShapeType::Capsule }), // Values for GetShapeType() + ::testing::ValuesIn({ SimulatedShapesMode::NONE, SimulatedShapesMode::MIXED, SimulatedShapesMode::ALL }), // Values for GetShapesMode() + ::testing::ValuesIn(PossibleMassComputeFlags), // Values for GetMassComputeFlags() + ::testing::Bool(), // Values for IncludeAllShapes() + ::testing::Bool())); // Values for IsMultiShapeTest() + class MassPropertiesWithTriangleMesh + : public ::testing::TestWithParam + { + public: + void SetUp() override + { + if (auto* physicsSystem = AZ::Interface::Get()) + { + AzPhysics::SceneConfiguration sceneConfiguration = physicsSystem->GetDefaultSceneConfiguration(); + sceneConfiguration.m_sceneName = AzPhysics::DefaultPhysicsSceneName; + m_testSceneHandle = physicsSystem->AddScene(sceneConfiguration); + } + } + + void TearDown() override + { + // Clean up the Test scene + if (auto* physicsSystem = AZ::Interface::Get()) + { + physicsSystem->RemoveScene(m_testSceneHandle); + } + m_testSceneHandle = AzPhysics::InvalidSceneHandle; + } + + AzPhysics::MassComputeFlags GetMassComputeFlags() const + { + return GetParam(); + } + + AzPhysics::SceneHandle m_testSceneHandle = AzPhysics::InvalidSceneHandle; + }; + + TEST_P(MassPropertiesWithTriangleMesh, KinematicRigidBody_ComputeMassProperties_TriggersWarnings) + { + const AzPhysics::MassComputeFlags flags = GetMassComputeFlags(); + + const bool doesComputeCenterOfMass = AzPhysics::MassComputeFlags::COMPUTE_COM == (flags & AzPhysics::MassComputeFlags::COMPUTE_COM); + const bool doesComputeMass = AzPhysics::MassComputeFlags::COMPUTE_MASS == (flags & AzPhysics::MassComputeFlags::COMPUTE_MASS); + const bool doesComputeInertia = AzPhysics::MassComputeFlags::COMPUTE_INERTIA == (flags & AzPhysics::MassComputeFlags::COMPUTE_INERTIA); + + UnitTest::ErrorHandler computeCenterOfMassWarningHandler( + "cannot compute COM"); + UnitTest::ErrorHandler computeMassWarningHandler( + "cannot compute Mass"); + UnitTest::ErrorHandler computeIneriaWarningHandler( + "cannot compute Inertia"); + + AzPhysics::SimulatedBodyHandle rigidBodyhandle = TestUtils::AddKinematicTriangleMeshCubeToScene(m_testSceneHandle, 3.0f, flags); + + EXPECT_TRUE(rigidBodyhandle != AzPhysics::InvalidSimulatedBodyHandle); + EXPECT_EQ(computeCenterOfMassWarningHandler.GetExpectedWarningCount(), doesComputeCenterOfMass ? 1 : 0); + EXPECT_EQ(computeMassWarningHandler.GetExpectedWarningCount(), doesComputeMass ? 1 : 0); + EXPECT_EQ(computeIneriaWarningHandler.GetExpectedWarningCount(), doesComputeInertia ? 1 : 0); + + if (auto* sceneInterface = AZ::Interface::Get()) + { + sceneInterface->RemoveSimulatedBody(m_testSceneHandle, rigidBodyhandle); + } + } + + INSTANTIATE_TEST_CASE_P(PhysX, MassPropertiesWithTriangleMesh, + ::testing::ValuesIn(PossibleMassComputeFlags)); // Values for GetMassComputeFlags() } // namespace PhysX diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp index 6186db6f1e..67fe67bc23 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp @@ -253,6 +253,36 @@ namespace PhysX return AzPhysics::InvalidSimulatedBodyHandle; } + AzPhysics::SimulatedBodyHandle AddKinematicTriangleMeshCubeToScene(AzPhysics::SceneHandle scene, float halfExtent, AzPhysics::MassComputeFlags massComputeFlags) + { + // Generate input data + VertexIndexData cubeMeshData = GenerateCubeMeshData(halfExtent); + AZStd::vector cookedData; + bool cookingResult = false; + Physics::SystemRequestBus::BroadcastResult(cookingResult, &Physics::SystemRequests::CookTriangleMeshToMemory, + cubeMeshData.first.data(), static_cast(cubeMeshData.first.size()), + cubeMeshData.second.data(), static_cast(cubeMeshData.second.size()), + cookedData); + AZ_Assert(cookingResult, "Failed to cook the cube mesh."); + + // Setup shape & collider configurations + auto shapeConfig = AZStd::make_shared(); + shapeConfig->SetCookedMeshData(cookedData.data(), cookedData.size(), + Physics::CookedMeshShapeConfiguration::MeshType::TriangleMesh); + + AzPhysics::RigidBodyConfiguration rigidBodyConfiguration; + rigidBodyConfiguration.m_kinematic = true; + rigidBodyConfiguration.SetMassComputeFlags(massComputeFlags); + rigidBodyConfiguration.m_colliderAndShapeData = AzPhysics::ShapeColliderPair( + AZStd::make_shared(), shapeConfig); + + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->AddSimulatedBody(scene, &rigidBodyConfiguration); + } + return AzPhysics::InvalidSimulatedBodyHandle; + } + void SetCollisionLayer(EntityPtr& entity, const AZStd::string& layerName, const AZStd::string& colliderTag) { Physics::CollisionFilteringRequestBus::Event(entity->GetId(), &Physics::CollisionFilteringRequests::SetCollisionLayer, layerName, AZ::Crc32(colliderTag.c_str())); diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.h b/Gems/PhysX/Code/Tests/PhysXTestCommon.h index ef12ca8350..95859a3f86 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.h +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.h @@ -89,6 +89,7 @@ namespace PhysX const AzPhysics::CollisionLayer& layer = AzPhysics::CollisionLayer::Default); AzPhysics::SimulatedBodyHandle AddStaticTriangleMeshCubeToScene(AzPhysics::SceneHandle scene, float halfExtent); + AzPhysics::SimulatedBodyHandle AddKinematicTriangleMeshCubeToScene(AzPhysics::SceneHandle scene, float halfExtent, AzPhysics::MassComputeFlags massComputeFlags); // Collision Filtering void SetCollisionLayer(EntityPtr& entity, const AZStd::string& layerName, const AZStd::string& colliderTag = ""); diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index a7e6b6c707..18bddfa26f 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -91,6 +91,11 @@ namespace WhiteBox bodyConfiguration.m_position = worldTransform.GetTranslation(); bodyConfiguration.m_kinematic = true; // note: this field is ignored in the WhiteBoxBodyType::Static case bodyConfiguration.m_colliderAndShapeData = shape; + // Since the shape used is a triangle mesh the COM, Mass and Inertia + // cannot be computed. Disable them to use default values. + bodyConfiguration.m_computeCenterOfMass = false; + bodyConfiguration.m_computeMass = false; + bodyConfiguration.m_computeInertiaTensor = false; m_simulatedBodyHandle = sceneInterface->AddSimulatedBody(defaultScene, &bodyConfiguration); } break; From f7eb906516644d3e628f739d33324f89460da4da Mon Sep 17 00:00:00 2001 From: AMZN-Igarri <82394219+AMZN-Igarri@users.noreply.github.com> Date: Fri, 15 Oct 2021 10:55:41 +0200 Subject: [PATCH 42/52] Moved Max Number of Entries Shown in Asset Browser Search View to EditorViewportSettings (#4660) * removed references to maxNumberOfItemsShownInSearch Signed-off-by: igarri * Move Max Number of Entries Shown in Asset Browser Search View to EditorViewportSettings Signed-off-by: igarri * Fixed extra spaces Signed-off-by: igarri * Code review feedback Signed-off-by: igarri --- Code/Editor/EditorPreferencesPageFiles.cpp | 22 ++++++++++--------- Code/Editor/EditorPreferencesPageFiles.h | 11 ++++------ Code/Editor/EditorViewportSettings.cpp | 11 ++++++++++ Code/Editor/EditorViewportSettings.h | 3 +++ Code/Editor/Settings.cpp | 7 +++--- Code/Editor/Settings.h | 10 +-------- .../AssetBrowser/AssetBrowserTableModel.h | 2 +- .../Editor/EditorSettingsAPIBus.h | 2 +- 8 files changed, 36 insertions(+), 32 deletions(-) diff --git a/Code/Editor/EditorPreferencesPageFiles.cpp b/Code/Editor/EditorPreferencesPageFiles.cpp index 4be3269d42..c3423c4e5b 100644 --- a/Code/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Editor/EditorPreferencesPageFiles.cpp @@ -14,6 +14,7 @@ // Editor #include "Settings.h" +#include "EditorViewportSettings.h" @@ -43,17 +44,16 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Field("MaxCount", &AutoBackup::m_maxCount) ->Field("RemindTime", &AutoBackup::m_remindTime); - serialize.Class() + serialize.Class() ->Version(1) - ->Field("Max number of items displayed", &AssetBrowserSearch::m_maxNumberOfItemsShownInSearch); + ->Field("MaxEntriesShownCount", &AssetBrowserSettings::m_maxNumberOfItemsShownInSearch); serialize.Class() ->Version(1) ->Field("Files", &CEditorPreferencesPage_Files::m_files) ->Field("Editors", &CEditorPreferencesPage_Files::m_editors) ->Field("AutoBackup", &CEditorPreferencesPage_Files::m_autoBackup) - ->Field("AssetBrowserSearch", &CEditorPreferencesPage_Files::m_assetBrowserSearch); - + ->Field("AssetBrowserSettings", &CEditorPreferencesPage_Files::m_assetBrowserSettings); AZ::EditContext* editContext = serialize.GetEditContext(); if (editContext) @@ -85,9 +85,10 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Attribute(AZ::Edit::Attributes::Max, 100) ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AutoBackup::m_remindTime, "Remind Time", "Auto Remind Every (Minutes)"); - editContext->Class("Asset Browser Search View", "Asset Browser Search View") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AssetBrowserSearch::m_maxNumberOfItemsShownInSearch, "Maximum number of displayed items", - "Maximum number of displayed items displayed in the Search View") + editContext->Class("Asset Browser Settings", "Asset Browser Settings") + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &AssetBrowserSettings::m_maxNumberOfItemsShownInSearch, "Maximum number of displayed items", + "Maximum number of items to display in the Search View.") ->Attribute(AZ::Edit::Attributes::Min, 50) ->Attribute(AZ::Edit::Attributes::Max, 5000); @@ -97,7 +98,7 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_files, "Files", "File Preferences") ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_editors, "External Editors", "External Editors") ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_autoBackup, "Auto Backup", "Auto Backup") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_assetBrowserSearch, "Asset Browser Search", "Asset Browser Search"); + ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_assetBrowserSettings, "Asset Browser Settings","Asset Browser Settings"); } } @@ -117,6 +118,7 @@ QIcon& CEditorPreferencesPage_Files::GetIcon() void CEditorPreferencesPage_Files::OnApply() { using namespace AzToolsFramework::SliceUtilities; + auto sliceSettings = AZ::UserSettings::CreateFind(AZ_CRC("SliceUserSettings", 0x055b32eb), AZ::UserSettings::CT_LOCAL); sliceSettings->m_autoNumber = m_files.m_autoNumberSlices; sliceSettings->m_saveLocation = m_files.m_saveLocation; @@ -137,7 +139,7 @@ void CEditorPreferencesPage_Files::OnApply() gSettings.autoBackupMaxCount = m_autoBackup.m_maxCount; gSettings.autoRemindTime = m_autoBackup.m_remindTime; - gSettings.maxNumberOfItemsShownInSearch = m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch; + SandboxEditor::SetMaxItemsShownInAssetBrowserSearch(m_assetBrowserSettings.m_maxNumberOfItemsShownInSearch); } void CEditorPreferencesPage_Files::InitializeSettings() @@ -163,5 +165,5 @@ void CEditorPreferencesPage_Files::InitializeSettings() m_autoBackup.m_maxCount = gSettings.autoBackupMaxCount; m_autoBackup.m_remindTime = gSettings.autoRemindTime; - m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch = gSettings.maxNumberOfItemsShownInSearch; + m_assetBrowserSettings.m_maxNumberOfItemsShownInSearch = SandboxEditor::MaxItemsShownInAssetBrowserSearch(); } diff --git a/Code/Editor/EditorPreferencesPageFiles.h b/Code/Editor/EditorPreferencesPageFiles.h index 368cd91fc3..9022032edc 100644 --- a/Code/Editor/EditorPreferencesPageFiles.h +++ b/Code/Editor/EditorPreferencesPageFiles.h @@ -69,18 +69,15 @@ private: int m_remindTime; }; - struct AssetBrowserSearch + struct AssetBrowserSettings { - AZ_TYPE_INFO(AssetBrowserSearch, "{9FBFCD24-9452-49DF-99F4-2711443CEAAE}") - - int m_maxNumberOfItemsShownInSearch; + AZ_TYPE_INFO(AssetBrowserSettings, "{5F407EC4-BBD1-4A87-92DB-D938D7127BB0}") + AZ::u64 m_maxNumberOfItemsShownInSearch; }; Files m_files; ExternalEditors m_editors; AutoBackup m_autoBackup; - AssetBrowserSearch m_assetBrowserSearch; + AssetBrowserSettings m_assetBrowserSettings; QIcon m_icon; }; - - diff --git a/Code/Editor/EditorViewportSettings.cpp b/Code/Editor/EditorViewportSettings.cpp index 2354c6d63a..2b54622d1c 100644 --- a/Code/Editor/EditorViewportSettings.cpp +++ b/Code/Editor/EditorViewportSettings.cpp @@ -15,6 +15,7 @@ namespace SandboxEditor { + constexpr AZStd::string_view AssetBrowserMaxItemsShownInSearchSetting = "/Amazon/Preferences/Editor/AssetBrowser/MaxItemsShowInSearch"; constexpr AZStd::string_view GridSnappingSetting = "/Amazon/Preferences/Editor/GridSnapping"; constexpr AZStd::string_view GridSizeSetting = "/Amazon/Preferences/Editor/GridSize"; constexpr AZStd::string_view AngleSnappingSetting = "/Amazon/Preferences/Editor/AngleSnapping"; @@ -110,6 +111,16 @@ namespace SandboxEditor return AZStd::make_unique(); } + AZ::u64 MaxItemsShownInAssetBrowserSearch() + { + return GetRegistry(AssetBrowserMaxItemsShownInSearchSetting, aznumeric_cast(50)); + } + + void SetMaxItemsShownInAssetBrowserSearch(const AZ::u64 numberOfItemsShown) + { + SetRegistry(AssetBrowserMaxItemsShownInSearchSetting, numberOfItemsShown); + } + bool GridSnappingEnabled() { return GetRegistry(GridSnappingSetting, false); diff --git a/Code/Editor/EditorViewportSettings.h b/Code/Editor/EditorViewportSettings.h index c1394f7404..c6f51cf461 100644 --- a/Code/Editor/EditorViewportSettings.h +++ b/Code/Editor/EditorViewportSettings.h @@ -32,6 +32,9 @@ namespace SandboxEditor //! event will fire when a value in the settings registry (editorpreferences.setreg) is modified. SANDBOX_API AZStd::unique_ptr CreateEditorViewportSettingsCallbacks(); + SANDBOX_API AZ::u64 MaxItemsShownInAssetBrowserSearch(); + SANDBOX_API void SetMaxItemsShownInAssetBrowserSearch(AZ::u64 numberOfItemsShown); + SANDBOX_API bool GridSnappingEnabled(); SANDBOX_API void SetGridSnapping(bool enabled); diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 47743d1c42..d548cffb52 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -10,6 +10,7 @@ #include "EditorDefs.h" #include "Settings.h" +#include "EditorViewportSettings.h" // Qt #include @@ -487,7 +488,6 @@ void SEditorSettings::Save() SaveValue("Settings", "AutoBackupTime", autoBackupTime); SaveValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); SaveValue("Settings", "AutoRemindTime", autoRemindTime); - SaveValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); SaveValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); SaveValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); SaveValue("Settings", "StylusMode", stylusMode); @@ -682,7 +682,6 @@ void SEditorSettings::Load() LoadValue("Settings", "AutoBackupTime", autoBackupTime); LoadValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); LoadValue("Settings", "AutoRemindTime", autoRemindTime); - LoadValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); LoadValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); LoadValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); LoadValue("Settings", "StylusMode", stylusMode); @@ -1174,7 +1173,7 @@ AzToolsFramework::ConsoleColorTheme SEditorSettings::GetConsoleColorTheme() cons return consoleBackgroundColorTheme; } -int SEditorSettings::GetMaxNumberOfItemsShownInSearchView() const +AZ::u64 SEditorSettings::GetMaxNumberOfItemsShownInSearchView() const { - return SEditorSettings::maxNumberOfItemsShownInSearch; + return SandboxEditor::MaxItemsShownInAssetBrowserSearch(); } diff --git a/Code/Editor/Settings.h b/Code/Editor/Settings.h index 8bf22b43e5..426d2300d3 100644 --- a/Code/Editor/Settings.h +++ b/Code/Editor/Settings.h @@ -279,7 +279,7 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING SettingOutcome GetValue(const AZStd::string_view path) override; SettingOutcome SetValue(const AZStd::string_view path, const AZStd::any& value) override; AzToolsFramework::ConsoleColorTheme GetConsoleColorTheme() const override; - int GetMaxNumberOfItemsShownInSearchView() const override; + AZ::u64 GetMaxNumberOfItemsShownInSearchView() const override; void ConvertPath(const AZStd::string_view sourcePath, AZStd::string& category, AZStd::string& attribute); @@ -353,14 +353,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING int autoRemindTime; ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // Asset Browser Search View. - ////////////////////////////////////////////////////////////////////////// - //! Current maximum number of items that can be displayed in the AssetBrowser Search View. - int maxNumberOfItemsShownInSearch; - ////////////////////////////////////////////////////////////////////////// - - //! If true preview windows is displayed when browsing geometries. bool bPreviewGeometryWindow; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 55dcbb1532..f84e6bd81c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -53,7 +53,7 @@ namespace AzToolsFramework private slots: void SourceDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight); private: - int m_numberOfItemsDisplayed = 50; + AZ::u64 m_numberOfItemsDisplayed = 0; int m_displayedItemsCounter = 0; QPointer m_filterModel; QMap m_indexMap; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h index fedb889fbb..52d8395377 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h @@ -38,7 +38,7 @@ namespace AzToolsFramework virtual SettingOutcome GetValue(const AZStd::string_view path) = 0; virtual SettingOutcome SetValue(const AZStd::string_view path, const AZStd::any& value) = 0; virtual ConsoleColorTheme GetConsoleColorTheme() const = 0; - virtual int GetMaxNumberOfItemsShownInSearchView() const = 0; + virtual AZ::u64 GetMaxNumberOfItemsShownInSearchView() const = 0; }; using EditorSettingsAPIBus = AZ::EBus; From 606de5427b161d7cad7e1abfc0b5f10c7f7938c8 Mon Sep 17 00:00:00 2001 From: ffarahmand-DPS Date: Fri, 15 Oct 2021 02:30:48 -0700 Subject: [PATCH 43/52] Fixes debug console autocomplete issues (#4223) * Fixed a crash caused by large autocomplete results in the debug console. A fixed vector was growing beyond its allocated size. Signed-off-by: ffarahmand-DPS * Fixes printing duplicate autocomplete results, caused by looping over multiple CVARs registered with the same name. Also adds an erase to prevent undefined behavior. Signed-off-by: ffarahmand-DPS * Adds a test case for autocomplete duplication in the event of multiple cvars existing under the same name. Two matching cvars are created and checked against the number of matches produced by autocomplete. Signed-off-by: ffarahmand-DPS * Added two safety checks and made a pointer const as per reviewer feedback. Signed-off-by: ffarahmand-DPS --- .../AzCore/AzCore/Console/Console.cpp | 27 ++++++++++++++++--- .../AzCore/Tests/Console/ConsoleTests.cpp | 15 +++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Console/Console.cpp b/Code/Framework/AzCore/AzCore/Console/Console.cpp index 9f207d9afd..79e1f79697 100644 --- a/Code/Framework/AzCore/AzCore/Console/Console.cpp +++ b/Code/Framework/AzCore/AzCore/Console/Console.cpp @@ -225,8 +225,16 @@ namespace AZ ConsoleCommandContainer commandSubset; - for (ConsoleFunctorBase* curr = m_head; curr != nullptr; curr = curr->m_next) + for (const auto& functor : m_commands) { + if (functor.second.empty()) + { + continue; + } + + // Filter functors registered with the same name + const ConsoleFunctorBase* curr = functor.second.front(); + if ((curr->GetFlags() & ConsoleFunctorFlags::IsInvisible) == ConsoleFunctorFlags::IsInvisible) { // Filter functors marked as invisible @@ -236,7 +244,12 @@ namespace AZ if (StringFunc::StartsWith(curr->m_name, command, false)) { AZLOG_INFO("- %s : %s\n", curr->m_name, curr->m_desc); - commandSubset.push_back(curr->m_name); + + if (commandSubset.size() < MaxConsoleCommandPlusArgsLength) + { + commandSubset.push_back(curr->m_name); + } + if (matches) { matches->push_back(curr->m_name); @@ -271,7 +284,10 @@ namespace AZ { for (auto& curr : m_commands) { - visitor(curr.second.front()); + if (!curr.second.empty()) + { + visitor(curr.second.front()); + } } } @@ -336,6 +352,11 @@ namespace AZ { iter->second.erase(iter2); } + + if (iter->second.empty()) + { + m_commands.erase(iter); + } } functor->Unlink(m_head); functor->m_console = nullptr; diff --git a/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp b/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp index d91ec5ba58..e01129a7bc 100644 --- a/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp +++ b/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp @@ -288,6 +288,21 @@ namespace AZ AZStd::string completeCommand = console->AutoCompleteCommand("testVec3"); AZ_TEST_ASSERT(completeCommand == "testVec3"); } + + // Duplicate names + { + // Register two cvars with the same name + auto id = AZ::TypeId(); + auto flag = AZ::ConsoleFunctorFlags::Null; + auto signature = AZ::ConsoleFunctor::FunctorSignature(); + AZ::ConsoleFunctor cvarOne(*console, "testAutoCompleteDuplication", "", flag, id, signature); + AZ::ConsoleFunctor cvarTwo(*console, "testAutoCompleteDuplication", "", flag, id, signature); + + // Autocomplete given name expecting one match (not two) + AZStd::vector matches; + AZStd::string completeCommand = console->AutoCompleteCommand("testAutoCompleteD", &matches); + AZ_TEST_ASSERT(matches.size() == 1 && completeCommand == "testAutoCompleteDuplication"); + } } TEST_F(ConsoleTests, ConsoleFunctor_FreeFunctorExecutionTest) From 5c8a1b573e8520315b093700626e73022861d547 Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Fri, 15 Oct 2021 12:56:05 +0100 Subject: [PATCH 44/52] Add support for border in Focus Mode (#4692) * restore component mode border Signed-off-by: hultonha * add viewport border for focus mode, remove dead code in ObjectManager Signed-off-by: hultonha * ensure the focus mode border is restored when leaving component mode Signed-off-by: hultonha * update FocusModeNotification call order after merge from development Signed-off-by: hultonha --- Code/Editor/Objects/ObjectManager.cpp | 35 ----------- Code/Editor/Objects/ObjectManager.h | 8 --- ...ViewportEditorModeTrackerNotificationBus.h | 10 ++-- .../ComponentMode/ComponentModeCollection.cpp | 52 ++++++++++++++++ .../ComponentMode/EditorBaseComponentMode.cpp | 2 +- .../FocusMode/FocusModeSystemComponent.cpp | 11 ++-- .../EditorTransformComponentSelection.cpp | 59 +++++++++++++++---- .../ViewportUi/ViewportUiDisplay.cpp | 8 ++- .../ViewportUi/ViewportUiDisplay.h | 4 +- .../ViewportUi/ViewportUiManager.cpp | 8 +-- .../ViewportUi/ViewportUiManager.h | 4 +- .../ViewportUi/ViewportUiRequestBus.h | 10 ++-- 12 files changed, 130 insertions(+), 81 deletions(-) diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index 7057cc5b7b..ee7e9a8e96 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -108,15 +108,11 @@ CObjectManager::CObjectManager() m_objectsByName.reserve(1024); LoadRegistry(); - - AzToolsFramework::ViewportEditorModeNotificationsBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); } ////////////////////////////////////////////////////////////////////////// CObjectManager::~CObjectManager() { - AzToolsFramework::ViewportEditorModeNotificationsBus::Handler::BusDisconnect(); - m_bExiting = true; SaveRegistry(); DeleteAllObjects(); @@ -2307,37 +2303,6 @@ void CObjectManager::SelectObjectInRect(CBaseObject* pObj, CViewport* view, HitC } } -void CObjectManager::OnEditorModeActivated( - [[maybe_unused]] const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) -{ - if (mode == AzToolsFramework::ViewportEditorMode::Component) - { - // hide current gizmo for entity (translate/rotate/scale) - IGizmoManager* gizmoManager = GetGizmoManager(); - const size_t gizmoCount = static_cast(gizmoManager->GetGizmoCount()); - for (size_t i = 0; i < gizmoCount; ++i) - { - gizmoManager->RemoveGizmo(gizmoManager->GetGizmoByIndex(static_cast(i))); - } - } -} - -void CObjectManager::OnEditorModeDeactivated( - [[maybe_unused]] const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) -{ - if (mode == AzToolsFramework::ViewportEditorMode::Component) - { - // show translate/rotate/scale gizmo again - if (IGizmoManager* gizmoManager = GetGizmoManager()) - { - if (CBaseObject* selectedObject = GetIEditor()->GetSelectedObject()) - { - gizmoManager->AddGizmo(new CAxisGizmo(selectedObject)); - } - } - } -} - ////////////////////////////////////////////////////////////////////////// namespace { diff --git a/Code/Editor/Objects/ObjectManager.h b/Code/Editor/Objects/ObjectManager.h index 7fb2342e40..7389dfa6a1 100644 --- a/Code/Editor/Objects/ObjectManager.h +++ b/Code/Editor/Objects/ObjectManager.h @@ -20,7 +20,6 @@ #include "ObjectManagerEventBus.h" #include -#include #include #include #include @@ -59,7 +58,6 @@ public: */ class CObjectManager : public IObjectManager - , private AzToolsFramework::ViewportEditorModeNotificationsBus::Handler { public: //! Selection functor callback. @@ -330,12 +328,6 @@ private: void FindDisplayableObjects(DisplayContext& dc, bool bDisplay); - // ViewportEditorModeNotificationsBus overrides ... - void OnEditorModeActivated( - const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) override; - void OnEditorModeDeactivated( - const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) override; - private: typedef std::map Objects; Objects m_objects; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h index 4fb4191d45..966b9f8478 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h @@ -43,8 +43,7 @@ namespace AzToolsFramework }; //! Provides a bus to notify when the different editor modes are entered/exit. - class ViewportEditorModeNotifications - : public AZ::EBusTraits + class ViewportEditorModeNotifications : public AZ::EBusTraits { public: ////////////////////////////////////////////////////////////////////////// @@ -58,14 +57,17 @@ namespace AzToolsFramework static void Reflect(AZ::ReflectContext* context); //! Notifies subscribers of the a given viewport to the activation of the specified editor mode. - virtual void OnEditorModeActivated([[maybe_unused]] const ViewportEditorModesInterface& editorModeState, [[maybe_unused]] ViewportEditorMode mode) + virtual void OnEditorModeActivated( + [[maybe_unused]] const ViewportEditorModesInterface& editorModeState, [[maybe_unused]] ViewportEditorMode mode) { } //! Notifies subscribers of the a given viewport to the deactivation of the specified editor mode. - virtual void OnEditorModeDeactivated([[maybe_unused]] const ViewportEditorModesInterface& editorModeState, [[maybe_unused]] ViewportEditorMode mode) + virtual void OnEditorModeDeactivated( + [[maybe_unused]] const ViewportEditorModesInterface& editorModeState, [[maybe_unused]] ViewportEditorMode mode) { } }; + using ViewportEditorModeNotificationsBus = AZ::EBus; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp index 1768cb5920..07e025fc60 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/ComponentModeCollection.cpp @@ -137,6 +137,7 @@ namespace AzToolsFramework if (componentTypeIt == m_activeComponentTypes.end()) { m_activeComponentTypes.push_back(componentType); + m_viewportUiHandlers.emplace_back(componentType); } // see if we already have a ComponentModeBuilder for the specific component on this entity @@ -225,6 +226,7 @@ namespace AzToolsFramework if (!m_entitiesAndComponentModes.empty()) { RefreshActions(); + PopulateViewportUi(); } // if entering ComponentMode not as an undo/redo step (an action was @@ -285,6 +287,10 @@ namespace AzToolsFramework componentModeCommand.release(); } + // remove the component mode viewport border + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::RemoveViewportBorder); + // notify listeners the editor has left ComponentMode - listeners may // wish to modify state to indicate this (e.g. appearance, functionality etc.) m_viewportEditorModeTracker->DeactivateMode({ GetEntityContextId() }, ViewportEditorMode::Component); @@ -301,6 +307,7 @@ namespace AzToolsFramework } m_entitiesAndComponentModeBuilders.clear(); m_activeComponentTypes.clear(); + m_viewportUiHandlers.clear(); m_componentMode = false; m_selectedComponentModeIndex = 0; @@ -385,6 +392,24 @@ namespace AzToolsFramework return m_activeComponentTypes.size() > 1; } + static ComponentModeViewportUi* FindViewportUiHandlerForType( + AZStd::vector& viewportUiHandlers, const AZ::Uuid& componentType) + { + auto handler = AZStd::find_if( + viewportUiHandlers.begin(), viewportUiHandlers.end(), + [componentType](const ComponentModeViewportUi& handler) + { + return handler.GetComponentType() == componentType; + }); + + if (handler == viewportUiHandlers.end()) + { + return nullptr; + } + + return handler; + } + bool ComponentModeCollection::ActiveComponentModeChanged(const AZ::Uuid& previousComponentType) { if (m_activeComponentTypes[m_selectedComponentModeIndex] != previousComponentType) @@ -410,6 +435,20 @@ namespace AzToolsFramework // replace the current component mode by invoking the builder // for the new 'active' component mode componentMode.m_componentMode = componentModeBuilder->m_componentModeBuilder(); + + // populate the viewport UI with the new component mode + PopulateViewportUi(); + + // set the appropriate viewportUiHandler to active + if (auto viewportUiHandler = + FindViewportUiHandlerForType(m_viewportUiHandlers, m_activeComponentTypes[m_selectedComponentModeIndex])) + { + viewportUiHandler->SetComponentModeViewportUiActive(true); + } + + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, + componentMode.m_componentMode->GetComponentModeName().c_str()); } RefreshActions(); @@ -519,5 +558,18 @@ namespace AzToolsFramework } } + void ComponentModeCollection::PopulateViewportUi() + { + // update viewport UI for new component type + if (m_selectedComponentModeIndex < m_activeComponentTypes.size()) + { + // iterate over all entities and their active Component Mode, populate viewport UI for the new mode + for (auto& entityAndComponentMode : m_entitiesAndComponentModes) + { + // build viewport UI based on current state + entityAndComponentMode.m_componentMode->PopulateViewportUi(); + } + } + } } // namespace ComponentModeFramework } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp index 9e043a5c86..f449478306 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentMode/EditorBaseComponentMode.cpp @@ -55,7 +55,7 @@ namespace AzToolsFramework GetEntityComponentIdPair(), elementIdsToDisplay); // create the component mode border with the specific name for this component mode ViewportUi::ViewportUiRequestBus::Event( - ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateComponentModeBorder, + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, GetComponentModeName()); // set the EntityComponentId for this ComponentMode to active in the ComponentModeViewportUi system ComponentModeViewportUiRequestBus::Event( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/FocusMode/FocusModeSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/FocusMode/FocusModeSystemComponent.cpp index f592c471d0..44ff603c0c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/FocusMode/FocusModeSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/FocusMode/FocusModeSystemComponent.cpp @@ -71,12 +71,7 @@ namespace AzToolsFramework return; } - AZ::EntityId previousFocusEntityId = m_focusRoot; - m_focusRoot = entityId; - FocusModeNotificationBus::Broadcast(&FocusModeNotifications::OnEditorFocusChanged, previousFocusEntityId, m_focusRoot); - - if (auto tracker = AZ::Interface::Get(); - tracker != nullptr) + if (auto tracker = AZ::Interface::Get()) { if (!m_focusRoot.IsValid() && entityId.IsValid()) { @@ -87,6 +82,10 @@ namespace AzToolsFramework tracker->DeactivateMode({ GetEntityContextId() }, ViewportEditorMode::Focus); } } + + AZ::EntityId previousFocusEntityId = m_focusRoot; + m_focusRoot = entityId; + FocusModeNotificationBus::Broadcast(&FocusModeNotifications::OnEditorFocusChanged, previousFocusEntityId, m_focusRoot); } void FocusModeSystemComponent::ClearFocusRoot([[maybe_unused]] AzFramework::EntityContextId entityContextId) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index d5a0595049..a37b84fdf8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -3663,26 +3663,63 @@ namespace AzToolsFramework void EditorTransformComponentSelection::OnEditorModeActivated( [[maybe_unused]] const ViewportEditorModesInterface& editorModeState, ViewportEditorMode mode) { - if (mode == ViewportEditorMode::Component) + switch (mode) { - SetAllViewportUiVisible(false); + case ViewportEditorMode::Component: + { + SetAllViewportUiVisible(false); - EditorEntityLockComponentNotificationBus::Router::BusRouterDisconnect(); - EditorEntityVisibilityNotificationBus::Router::BusRouterDisconnect(); - ToolsApplicationNotificationBus::Handler::BusDisconnect(); + EditorEntityLockComponentNotificationBus::Router::BusRouterDisconnect(); + EditorEntityVisibilityNotificationBus::Router::BusRouterDisconnect(); + ToolsApplicationNotificationBus::Handler::BusDisconnect(); + } + break; + case ViewportEditorMode::Focus: + { + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode"); + } + break; + case ViewportEditorMode::Default: + case ViewportEditorMode::Pick: + // noop + break; } } void EditorTransformComponentSelection::OnEditorModeDeactivated( - [[maybe_unused]] const ViewportEditorModesInterface& editorModeState, ViewportEditorMode mode) + const ViewportEditorModesInterface& editorModeState, const ViewportEditorMode mode) { - if (mode == ViewportEditorMode::Component) + switch (mode) { - SetAllViewportUiVisible(true); + case ViewportEditorMode::Component: + { + SetAllViewportUiVisible(true); - ToolsApplicationNotificationBus::Handler::BusConnect(); - EditorEntityVisibilityNotificationBus::Router::BusRouterConnect(); - EditorEntityLockComponentNotificationBus::Router::BusRouterConnect(); + ToolsApplicationNotificationBus::Handler::BusConnect(); + EditorEntityVisibilityNotificationBus::Router::BusRouterConnect(); + EditorEntityLockComponentNotificationBus::Router::BusRouterConnect(); + + // note: when leaving component mode, we check if we're still in focus mode (i.e. component mode was + // started from within focus mode), if we are, ensure we create/update the viewport border (as leaving + // component mode will attempt to remove it) + if (editorModeState.IsModeActive(ViewportEditorMode::Focus)) + { + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::CreateViewportBorder, "Focus Mode"); + } + } + break; + case ViewportEditorMode::Focus: + { + ViewportUi::ViewportUiRequestBus::Event( + ViewportUi::DefaultViewportId, &ViewportUi::ViewportUiRequestBus::Events::RemoveViewportBorder); + } + break; + case ViewportEditorMode::Default: + case ViewportEditorMode::Pick: + // noop + break; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index e27627eab6..a289d914d6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -290,9 +290,9 @@ namespace AzToolsFramework::ViewportUi::Internal return false; } - void ViewportUiDisplay::CreateComponentModeBorder(const AZStd::string& borderTitle) + void ViewportUiDisplay::CreateViewportBorder(const AZStd::string& borderTitle) { - AZStd::string styleSheet = AZStd::string::format( + const AZStd::string styleSheet = AZStd::string::format( "border: %dpx solid %s; border-top: %dpx solid %s;", HighlightBorderSize, HighlightBorderColor, TopHighlightBorderSize, HighlightBorderColor); m_uiOverlay.setStyleSheet(styleSheet.c_str()); @@ -303,7 +303,7 @@ namespace AzToolsFramework::ViewportUi::Internal m_componentModeBorderText.setText(borderTitle.c_str()); } - void ViewportUiDisplay::RemoveComponentModeBorder() + void ViewportUiDisplay::RemoveViewportBorder() { m_componentModeBorderText.setVisible(false); m_uiOverlay.setStyleSheet("border: none;"); @@ -420,6 +420,7 @@ namespace AzToolsFramework::ViewportUi::Internal m_uiMainWindow.setVisible(true); m_uiOverlay.setVisible(true); } + m_uiMainWindow.setMask(region); } @@ -437,6 +438,7 @@ namespace AzToolsFramework::ViewportUi::Internal { return element->second; } + return ViewportUiElementInfo{ nullptr, InvalidViewportUiElementId, false }; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index aafaf61ff3..5020241815 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -89,8 +89,8 @@ namespace AzToolsFramework::ViewportUi::Internal AZStd::shared_ptr GetViewportUiElement(ViewportUiElementId elementId); bool IsViewportUiElementVisible(ViewportUiElementId elementId); - void CreateComponentModeBorder(const AZStd::string& borderTitle); - void RemoveComponentModeBorder(); + void CreateViewportBorder(const AZStd::string& borderTitle); + void RemoveViewportBorder(); private: void PrepareWidgetForViewportUi(QPointer widget); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 255d11f561..1f14b12b7d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -240,14 +240,14 @@ namespace AzToolsFramework::ViewportUi } } - void ViewportUiManager::CreateComponentModeBorder(const AZStd::string& borderTitle) + void ViewportUiManager::CreateViewportBorder(const AZStd::string& borderTitle) { - m_viewportUi->CreateComponentModeBorder(borderTitle); + m_viewportUi->CreateViewportBorder(borderTitle); } - void ViewportUiManager::RemoveComponentModeBorder() + void ViewportUiManager::RemoveViewportBorder() { - m_viewportUi->RemoveComponentModeBorder(); + m_viewportUi->RemoveViewportBorder(); } void ViewportUiManager::PressButton(ClusterId clusterId, ButtonId buttonId) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index 9ec6648451..ce7e5aafe9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -50,8 +50,8 @@ namespace AzToolsFramework::ViewportUi void RegisterTextFieldCallback(TextFieldId textFieldId, AZ::Event::Handler& handler) override; void RemoveTextField(TextFieldId textFieldId) override; void SetTextFieldVisible(TextFieldId textFieldId, bool visible) override; - void CreateComponentModeBorder(const AZStd::string& borderTitle) override; - void RemoveComponentModeBorder() override; + void CreateViewportBorder(const AZStd::string& borderTitle) override; + void RemoveViewportBorder() override; void PressButton(ClusterId clusterId, ButtonId buttonId) override; void PressButton(SwitcherId switcherId, ButtonId buttonId) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 108d23950a..3c6f7094cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -78,7 +78,7 @@ namespace AzToolsFramework::ViewportUi virtual void RegisterSwitcherEventHandler(SwitcherId switcherId, AZ::Event::Handler& handler) = 0; //! Removes a cluster from the Viewport UI system. virtual void RemoveCluster(ClusterId clusterId) = 0; - //! + //! Removes a switcher from the Viewport UI system. virtual void RemoveSwitcher(SwitcherId switcherId) = 0; //! Sets the visibility of the cluster. virtual void SetClusterVisible(ClusterId clusterId, bool visible) = 0; @@ -96,12 +96,12 @@ namespace AzToolsFramework::ViewportUi //! Sets the visibility of the text field. virtual void SetTextFieldVisible(TextFieldId textFieldId, bool visible) = 0; //! Create the highlight border for Component Mode. - virtual void CreateComponentModeBorder(const AZStd::string& borderTitle) = 0; + virtual void CreateViewportBorder(const AZStd::string& borderTitle) = 0; //! Remove the highlight border for Component Mode. - virtual void RemoveComponentModeBorder() = 0; - //! Invoke a button press in a cluster. + virtual void RemoveViewportBorder() = 0; + //! Invoke a button press on a cluster. virtual void PressButton(ClusterId clusterId, ButtonId buttonId) = 0; - //! + //! Invoke a button press on a switcher. virtual void PressButton(SwitcherId switcherId, ButtonId buttonId) = 0; }; From 716c561cb7cd4f26ec85738503b93e3b62e09ed7 Mon Sep 17 00:00:00 2001 From: Michael Pollind Date: Fri, 15 Oct 2021 04:56:20 -0700 Subject: [PATCH 45/52] bugfix: correct broken layout when searching global preferences (#4689) Signed-off-by: Michael Pollind --- Code/Editor/EditorPreferencesDialog.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Editor/EditorPreferencesDialog.cpp b/Code/Editor/EditorPreferencesDialog.cpp index c56df15908..a1859b0f14 100644 --- a/Code/Editor/EditorPreferencesDialog.cpp +++ b/Code/Editor/EditorPreferencesDialog.cpp @@ -264,6 +264,9 @@ void EditorPreferencesDialog::SetFilter(const QString& filter) else if (m_currentPageItem) { m_currentPageItem->UpdateEditorFilter(ui->propertyEditor, m_filter); + + // Refresh the Stylesheet - when using search functionality. + AzQtComponents::StyleManager::repolishStyleSheet(this); } } From d84bb6a72fc9c7928b1fb2aa20c5235d2c1691e6 Mon Sep 17 00:00:00 2001 From: Allen Jackson <23512001+jackalbe@users.noreply.github.com> Date: Fri, 15 Oct 2021 07:32:10 -0500 Subject: [PATCH 46/52] {LYN5384} splitting Blast builder and processor Python scripts (#4712) splitting the asset builder and asset processor Python scripts for the Blast processor This fixes a mulitiple build issue found while developing other scripts Signed-off-by: jackalbe <23512001+jackalbe@users.noreply.github.com> --- .../Editor/Scripts/blast_asset_builder.py | 125 +--------------- .../Editor/Scripts/blast_chunk_processor.py | 141 ++++++++++++++++++ 2 files changed, 144 insertions(+), 122 deletions(-) create mode 100644 Gems/Blast/Editor/Scripts/blast_chunk_processor.py diff --git a/Gems/Blast/Editor/Scripts/blast_asset_builder.py b/Gems/Blast/Editor/Scripts/blast_asset_builder.py index 06dc15f5c1..a570489ed1 100644 --- a/Gems/Blast/Editor/Scripts/blast_asset_builder.py +++ b/Gems/Blast/Editor/Scripts/blast_asset_builder.py @@ -95,7 +95,9 @@ def generate_assetinfo_product(request): outputFilename = os.path.join(request.tempDirPath, assetinfoFilename) # the only rule in it is to run this file again as a scene processor - currentScript = pathlib.Path(__file__).resolve() + currentScript = str(pathlib.Path(__file__).resolve()) + currentScript = currentScript.replace('\\', '/').lower() + currentScript = currentScript.replace('blast_asset_builder.py', 'blast_chunk_processor.py') aDict = {"values": [{"$type": "ScriptProcessorRule", "scriptFilename": f"{currentScript}"}]} jsonString = json.dumps(aDict) jsonFile = open(outputFilename, "w") @@ -167,124 +169,3 @@ try: pythonAssetBuilderHandler = register_asset_builder() except: pythonAssetBuilderHandler = None - -# -# SceneAPI Processor -# -blastChunksAssetType = azlmbr.math.Uuid_CreateString('{993F0B0F-37D9-48C6-9CC2-E27D3F3E343E}', 0) - -def export_chunk_asset(scene, outputDirectory, platformIdentifier, productList): - import azlmbr.scene - import azlmbr.object - import azlmbr.paths - import json, os - - jsonFilename = os.path.basename(scene.sourceFilename) - jsonFilename = os.path.join(outputDirectory, jsonFilename + '.blast_chunks') - - # prepare output folder - basePath, _ = os.path.split(jsonFilename) - outputPath = os.path.join(outputDirectory, basePath) - if not os.path.exists(outputPath): - os.makedirs(outputPath, False) - - # write out a JSON file with the chunk file info - with open(jsonFilename, "w") as jsonFile: - jsonFile.write(scene.manifest.ExportToJson()) - - exportProduct = azlmbr.scene.ExportProduct() - exportProduct.filename = jsonFilename - exportProduct.sourceId = scene.sourceGuid - exportProduct.assetType = blastChunksAssetType - exportProduct.subId = 101 - - exportProductList = azlmbr.scene.ExportProductList() - exportProductList.AddProduct(exportProduct) - return exportProductList - -def on_prepare_for_export(args): - try: - scene = args[0] # azlmbr.scene.Scene - outputDirectory = args[1] # string - platformIdentifier = args[2] # string - productList = args[3] # azlmbr.scene.ExportProductList - return export_chunk_asset(scene, outputDirectory, platformIdentifier, productList) - except: - log_exception_traceback() - -def get_mesh_node_names(sceneGraph): - import azlmbr.scene as sceneApi - import azlmbr.scene.graph - from scene_api import scene_data as sceneData - - meshDataList = [] - node = sceneGraph.get_root() - children = [] - - while node.IsValid(): - # store children to process after siblings - if sceneGraph.has_node_child(node): - children.append(sceneGraph.get_node_child(node)) - - # store any node that has mesh data content - nodeContent = sceneGraph.get_node_content(node) - if nodeContent is not None and nodeContent.CastWithTypeName('MeshData'): - if sceneGraph.is_node_end_point(node) is False: - nodeName = sceneData.SceneGraphName(sceneGraph.get_node_name(node)) - nodePath = nodeName.get_path() - if (len(nodeName.get_path())): - meshDataList.append(sceneData.SceneGraphName(sceneGraph.get_node_name(node))) - - # advance to next node - if sceneGraph.has_node_sibling(node): - node = sceneGraph.get_node_sibling(node) - elif children: - node = children.pop() - else: - node = azlmbr.scene.graph.NodeIndex() - - return meshDataList - -def update_manifest(scene): - import uuid, os - import azlmbr.scene as sceneApi - import azlmbr.scene.graph - from scene_api import scene_data as sceneData - - graph = sceneData.SceneGraph(scene.graph) - meshNameList = get_mesh_node_names(graph) - sceneManifest = sceneData.SceneManifest() - sourceFilenameOnly = os.path.basename(scene.sourceFilename) - sourceFilenameOnly = sourceFilenameOnly.replace('.','_') - - for activeMeshIndex in range(len(meshNameList)): - chunkName = meshNameList[activeMeshIndex] - chunkPath = chunkName.get_path() - meshGroupName = '{}_{}'.format(sourceFilenameOnly, chunkName.get_name()) - meshGroup = sceneManifest.add_mesh_group(meshGroupName) - meshGroup['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, sourceFilenameOnly + chunkPath)) + '}' - sceneManifest.mesh_group_select_node(meshGroup, chunkPath) - - return sceneManifest.export() - -sceneJobHandler = None - -def on_update_manifest(args): - try: - scene = args[0] - return update_manifest(scene) - except: - global sceneJobHandler - sceneJobHandler = None - log_exception_traceback() - -# try to create SceneAPI handler for processing -try: - import azlmbr.scene as sceneApi - if (sceneJobHandler == None): - sceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler() - sceneJobHandler.connect() - sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) - sceneJobHandler.add_callback('OnPrepareForExport', on_prepare_for_export) -except: - sceneJobHandler = None diff --git a/Gems/Blast/Editor/Scripts/blast_chunk_processor.py b/Gems/Blast/Editor/Scripts/blast_chunk_processor.py new file mode 100644 index 0000000000..d112f465e9 --- /dev/null +++ b/Gems/Blast/Editor/Scripts/blast_chunk_processor.py @@ -0,0 +1,141 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +""" +This a Python Asset Builder script examines each .blast file to see if an +associated .fbx file needs to be processed by exporting all of its chunks +into a scene manifest + +This is also a SceneAPI script that executes from a foo.fbx.assetinfo scene +manifest that writes out asset chunk data for .blast files +""" +import os, traceback, binascii, sys, json, pathlib +import azlmbr.math +import azlmbr.asset +import azlmbr.asset.entity +import azlmbr.asset.builder +import azlmbr.bus + +# +# SceneAPI Processor +# +blastChunksAssetType = azlmbr.math.Uuid_CreateString('{993F0B0F-37D9-48C6-9CC2-E27D3F3E343E}', 0) + +def export_chunk_asset(scene, outputDirectory, platformIdentifier, productList): + import azlmbr.scene + import azlmbr.object + import azlmbr.paths + import json, os + + jsonFilename = os.path.basename(scene.sourceFilename) + jsonFilename = os.path.join(outputDirectory, jsonFilename + '.blast_chunks') + + # prepare output folder + basePath, _ = os.path.split(jsonFilename) + outputPath = os.path.join(outputDirectory, basePath) + if not os.path.exists(outputPath): + os.makedirs(outputPath, False) + + # write out a JSON file with the chunk file info + with open(jsonFilename, "w") as jsonFile: + jsonFile.write(scene.manifest.ExportToJson()) + + exportProduct = azlmbr.scene.ExportProduct() + exportProduct.filename = jsonFilename + exportProduct.sourceId = scene.sourceGuid + exportProduct.assetType = blastChunksAssetType + exportProduct.subId = 101 + + exportProductList = azlmbr.scene.ExportProductList() + exportProductList.AddProduct(exportProduct) + return exportProductList + +def on_prepare_for_export(args): + try: + scene = args[0] # azlmbr.scene.Scene + outputDirectory = args[1] # string + platformIdentifier = args[2] # string + productList = args[3] # azlmbr.scene.ExportProductList + return export_chunk_asset(scene, outputDirectory, platformIdentifier, productList) + except: + log_exception_traceback() + +def get_mesh_node_names(sceneGraph): + import azlmbr.scene as sceneApi + import azlmbr.scene.graph + from scene_api import scene_data as sceneData + + meshDataList = [] + node = sceneGraph.get_root() + children = [] + + while node.IsValid(): + # store children to process after siblings + if sceneGraph.has_node_child(node): + children.append(sceneGraph.get_node_child(node)) + + # store any node that has mesh data content + nodeContent = sceneGraph.get_node_content(node) + if nodeContent is not None and nodeContent.CastWithTypeName('MeshData'): + if sceneGraph.is_node_end_point(node) is False: + nodeName = sceneData.SceneGraphName(sceneGraph.get_node_name(node)) + nodePath = nodeName.get_path() + if (len(nodeName.get_path())): + meshDataList.append(sceneData.SceneGraphName(sceneGraph.get_node_name(node))) + + # advance to next node + if sceneGraph.has_node_sibling(node): + node = sceneGraph.get_node_sibling(node) + elif children: + node = children.pop() + else: + node = azlmbr.scene.graph.NodeIndex() + + return meshDataList + +def update_manifest(scene): + import uuid, os + import azlmbr.scene as sceneApi + import azlmbr.scene.graph + from scene_api import scene_data as sceneData + + graph = sceneData.SceneGraph(scene.graph) + meshNameList = get_mesh_node_names(graph) + sceneManifest = sceneData.SceneManifest() + sourceFilenameOnly = os.path.basename(scene.sourceFilename) + sourceFilenameOnly = sourceFilenameOnly.replace('.','_') + + for activeMeshIndex in range(len(meshNameList)): + chunkName = meshNameList[activeMeshIndex] + chunkPath = chunkName.get_path() + meshGroupName = '{}_{}'.format(sourceFilenameOnly, chunkName.get_name()) + meshGroup = sceneManifest.add_mesh_group(meshGroupName) + meshGroup['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, sourceFilenameOnly + chunkPath)) + '}' + sceneManifest.mesh_group_select_node(meshGroup, chunkPath) + + return sceneManifest.export() + +sceneJobHandler = None + +def on_update_manifest(args): + try: + scene = args[0] + return update_manifest(scene) + except: + global sceneJobHandler + sceneJobHandler = None + log_exception_traceback() + +# try to create SceneAPI handler for processing +try: + import azlmbr.scene as sceneApi + if (sceneJobHandler == None): + sceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler() + sceneJobHandler.connect() + sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) + sceneJobHandler.add_callback('OnPrepareForExport', on_prepare_for_export) +except: + sceneJobHandler = None From 969a55170e362e8d025c0354a825de0cafcb7f26 Mon Sep 17 00:00:00 2001 From: amzn-mike <80125227+amzn-mike@users.noreply.github.com> Date: Fri, 15 Oct 2021 07:33:01 -0500 Subject: [PATCH 47/52] Procedural Prefabs: Entity parenting fixes (#4669) * Parent top level entities to container entity when creating prefab Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> * Add to_json method to PythonProxyObject to allow serializing any AZ serialializable type Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> * Update scene_mesh_to_prefab.py to parent entities in a chain Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> * Remove redundant eval Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> * Improve error handling in ToJson Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> * Add maybe_unused for commonRoot since it's not used Signed-off-by: amzn-mike <80125227+amzn-mike@users.noreply.github.com> --- .../Editor/Scripts/scene_mesh_to_prefab.py | 30 +++++++++++++-- .../Prefab/PrefabSystemScriptingHandler.cpp | 27 ++++++++++++- .../Code/Source/PythonProxyObject.cpp | 38 +++++++++++++++++++ .../Code/Source/PythonProxyObject.h | 2 + 4 files changed, 91 insertions(+), 6 deletions(-) diff --git a/AutomatedTesting/Editor/Scripts/scene_mesh_to_prefab.py b/AutomatedTesting/Editor/Scripts/scene_mesh_to_prefab.py index d5a7acfe91..4aeff06f18 100644 --- a/AutomatedTesting/Editor/Scripts/scene_mesh_to_prefab.py +++ b/AutomatedTesting/Editor/Scripts/scene_mesh_to_prefab.py @@ -74,6 +74,7 @@ def update_manifest(scene): source_filename_only = os.path.basename(clean_filename) created_entities = [] + previous_entity_id = azlmbr.entity.InvalidEntityId # Loop every mesh node in the scene for activeMeshIndex in range(len(mesh_name_list)): @@ -102,14 +103,33 @@ def update_manifest(scene): # The MeshGroup we created will be output as a product in the asset's path named mesh_group_name.azmodel # The assetHint will be converted to an AssetId later during prefab loading json_update = json.dumps({ - "Controller": { "Configuration": { "ModelAsset": { - "assetHint": os.path.join(source_relative_path, mesh_group_name) + ".azmodel" }}} - }); + "Controller": { "Configuration": { "ModelAsset": { + "assetHint": os.path.join(source_relative_path, mesh_group_name) + ".azmodel" }}} + }); # Apply the JSON above to the component we created result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, editor_mesh_component, json_update) if not result: - raise RuntimeError("UpdateComponentForEntity failed") + raise RuntimeError("UpdateComponentForEntity failed for Mesh component") + + # Get the transform component + transform_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName", entity_id, "27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0") + + # Set this entity to be a child of the last entity we created + # This is just an example of how to do parenting and isn't necessarily useful to parent everything like this + if previous_entity_id is not None: + transform_json = json.dumps({ + "Parent Entity" : previous_entity_id.to_json() + }); + + # Apply the JSON update + result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, transform_component, transform_json) + + if not result: + raise RuntimeError("UpdateComponentForEntity failed for Transform component") + + # Update the last entity id for next time + previous_entity_id = entity_id # Keep track of the entity we set up, we'll add them all to the prefab we're creating later created_entities.append(entity_id) @@ -147,6 +167,8 @@ def on_update_manifest(args): except RuntimeError as err: print (f'ERROR - {err}') log_exception_traceback() + except: + log_exception_traceback() global sceneJobHandler sceneJobHandler = None diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemScriptingHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemScriptingHandler.cpp index d34e2cfc92..884c463bff 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemScriptingHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemScriptingHandler.cpp @@ -6,11 +6,14 @@ * */ +#include #include #include #include #include #include +#include +#include namespace AzToolsFramework::Prefab { @@ -61,9 +64,29 @@ namespace AzToolsFramework::Prefab entities.push_back(entity); } } - - auto prefab = m_prefabSystemComponentInterface->CreatePrefab(entities, {}, AZ::IO::PathView(AZStd::string_view(filePath))); + bool result = false; + [[maybe_unused]] AZ::EntityId commonRoot; + EntityList topLevelEntities; + AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(result, &AzToolsFramework::ToolsApplicationRequestBus::Events::FindCommonRootInactive, + entities, commonRoot, &topLevelEntities); + + auto containerEntity = AZStd::make_unique(); + + for (AZ::Entity* entity : topLevelEntities) + { + AzToolsFramework::Components::TransformComponent* transformComponent = + entity->FindComponent(); + + if (transformComponent) + { + transformComponent->SetParent(containerEntity->GetId()); + } + } + + auto prefab = m_prefabSystemComponentInterface->CreatePrefab( + entities, {}, AZ::IO::PathView(AZStd::string_view(filePath)), AZStd::move(containerEntity)); + if (!prefab) { AZ_Error("PrefabSystemComponenent", false, "Failed to create prefab %s", filePath.c_str()); diff --git a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp index 706ca48156..df246d230d 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.cpp @@ -17,10 +17,16 @@ #include #include +#include +#include #include +#include #include #include +#include +#include +#include namespace EditorPythonBindings { @@ -571,6 +577,37 @@ namespace EditorPythonBindings return false; } + pybind11::object PythonProxyObject::ToJson() + { + rapidjson::Document document; + AZ::JsonSerializerSettings settings; + settings.m_keepDefaults = true; + + auto resultCode = + AZ::JsonSerialization::Store(document, document.GetAllocator(), m_wrappedObject.m_address, nullptr, m_wrappedObject.m_typeId, settings); + + if (resultCode.GetProcessing() == AZ::JsonSerializationResult::Processing::Halted) + { + AZ_Error("PythonProxyObject", false, "Failed to serialize to json"); + return pybind11::cast(Py_None); + } + + AZStd::string jsonString; + AZ::Outcome outcome = AZ::JsonSerializationUtils::WriteJsonString(document, jsonString); + + if (!outcome.IsSuccess()) + { + AZ_Error("PythonProxyObject", false, "Failed to write json string: %s", outcome.GetError().c_str()); + return pybind11::cast(Py_None); + } + + jsonString.erase(AZStd::remove(jsonString.begin(), jsonString.end(), '\n'), jsonString.end()); + auto pythonCode = AZStd::string::format( + R"PYTHON(exec("import json") or json.loads("""%s"""))PYTHON", jsonString.c_str()); + + return pybind11::eval(pythonCode.c_str()); + } + bool PythonProxyObject::DoComparisonEvaluation(pybind11::object pythonOther, Comparison comparison) { bool invertLogic = false; @@ -912,6 +949,7 @@ namespace EditorPythonBindings .def("set_property", &PythonProxyObject::SetPropertyValue) .def("get_property", &PythonProxyObject::GetPropertyValue) .def("invoke", &PythonProxyObject::Invoke) + .def("to_json", &PythonProxyObject::ToJson) .def(Operator::s_isEqual, [](PythonProxyObject& self, pybind11::object rhs) { return self.DoEqualityEvaluation(rhs); diff --git a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.h b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.h index 5b611c32c0..a9d2fad5a0 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonProxyObject.h @@ -58,6 +58,8 @@ namespace EditorPythonBindings //! Performs an equality operation to compare this object with another object bool DoEqualityEvaluation(pybind11::object pythonOther); + pybind11::object ToJson(); + //! Perform a comparison of a Python operator enum class Comparison { From 87533d80c11812c14b1262b151493f3be655739e Mon Sep 17 00:00:00 2001 From: srikappa-amzn <82230713+srikappa-amzn@users.noreply.github.com> Date: Fri, 15 Oct 2021 18:25:26 +0530 Subject: [PATCH 48/52] Delay propagation for all template updates in detach prefab workflow (#4707) * Delay propagation for all template updates in detach prefab workflow Signed-off-by: srikappa-amzn * Some minor changes to the PrefabUndo constructor Signed-off-by: srikappa-amzn --- .../Prefab/PrefabPublicHandler.cpp | 6 +++--- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 14 ++++---------- .../AzToolsFramework/Prefab/PrefabUndo.h | 8 ++++---- .../AzToolsFramework/Prefab/PrefabUndoHelpers.cpp | 4 ++-- 4 files changed, 13 insertions(+), 19 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 081655a166..ee34b628bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -1052,10 +1052,10 @@ namespace AzToolsFramework DuplicateNestedEntitiesInInstance(commonOwningInstance->get(), entities, instanceDomAfter, duplicatedEntityAndInstanceIds, duplicateEntityAliasMap); - PrefabUndoInstance* command = aznew PrefabUndoInstance("Entity/Instance duplication"); + PrefabUndoInstance* command = aznew PrefabUndoInstance("Entity/Instance duplication", false); command->SetParent(undoBatch.GetUndoBatch()); command->Capture(instanceDomBefore, instanceDomAfter, commonOwningInstance->get().GetTemplateId()); - command->RedoBatched(); + command->Redo(); DuplicateNestedInstancesInInstance(commonOwningInstance->get(), instances, instanceDomAfter, duplicatedEntityAndInstanceIds, newInstanceAliasToOldInstanceMap); @@ -1323,7 +1323,7 @@ namespace AzToolsFramework Prefab::PrefabDom instanceDomAfter; m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomAfter, parentInstance); - PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance detachment"); + PrefabUndoInstance* command = aznew PrefabUndoInstance("Instance detachment", false); command->Capture(instanceDomBefore, instanceDomAfter, parentTemplateId); command->SetParent(undoBatch.GetUndoBatch()); { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index b298304e3b..6c96209d56 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -17,17 +17,16 @@ namespace AzToolsFramework { PrefabUndoBase::PrefabUndoBase(const AZStd::string& undoOperationName) : UndoSystem::URSequencePoint(undoOperationName) - , m_changed(true) - , m_templateId(InvalidTemplateId) { m_instanceToTemplateInterface = AZ::Interface::Get(); AZ_Assert(m_instanceToTemplateInterface, "Failed to grab instance to template interface"); } //PrefabInstanceUndo - PrefabUndoInstance::PrefabUndoInstance(const AZStd::string& undoOperationName) + PrefabUndoInstance::PrefabUndoInstance(const AZStd::string& undoOperationName, const bool useImmediatePropagation) : PrefabUndoBase(undoOperationName) { + m_useImmediatePropagation = useImmediatePropagation; } void PrefabUndoInstance::Capture( @@ -43,17 +42,12 @@ namespace AzToolsFramework void PrefabUndoInstance::Undo() { - m_instanceToTemplateInterface->PatchTemplate(m_undoPatch, m_templateId, true); + m_instanceToTemplateInterface->PatchTemplate(m_undoPatch, m_templateId, m_useImmediatePropagation); } void PrefabUndoInstance::Redo() { - m_instanceToTemplateInterface->PatchTemplate(m_redoPatch, m_templateId, true); - } - - void PrefabUndoInstance::RedoBatched() - { - m_instanceToTemplateInterface->PatchTemplate(m_redoPatch, m_templateId); + m_instanceToTemplateInterface->PatchTemplate(m_redoPatch, m_templateId, m_useImmediatePropagation); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 8669024df7..0946a36951 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -29,14 +29,15 @@ namespace AzToolsFramework bool Changed() const override { return m_changed; } protected: - TemplateId m_templateId; + TemplateId m_templateId = InvalidTemplateId; PrefabDom m_redoPatch; PrefabDom m_undoPatch; InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr; - bool m_changed; + bool m_changed = true; + bool m_useImmediatePropagation = true; }; //! handles the addition and removal of entities from instances @@ -44,7 +45,7 @@ namespace AzToolsFramework : public PrefabUndoBase { public: - explicit PrefabUndoInstance(const AZStd::string& undoOperationName); + explicit PrefabUndoInstance(const AZStd::string& undoOperationName, const bool useImmediatePropagation = true); void Capture( const PrefabDom& initialState, @@ -53,7 +54,6 @@ namespace AzToolsFramework void Undo() override; void Redo() override; - void RedoBatched(); }; //! handles entity updates, such as when the values on an entity change diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 9803b55324..31a0c60bcb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -23,10 +23,10 @@ namespace AzToolsFramework PrefabDom instanceDomAfterUpdate; PrefabDomUtils::StoreInstanceInPrefabDom(instance, instanceDomAfterUpdate); - PrefabUndoInstance* state = aznew Prefab::PrefabUndoInstance(undoMessage); + PrefabUndoInstance* state = aznew Prefab::PrefabUndoInstance(undoMessage, false); state->Capture(instanceDomBeforeUpdate, instanceDomAfterUpdate, instance.GetTemplateId()); state->SetParent(undoBatch); - state->RedoBatched(); + state->Redo(); } LinkId CreateLink( From 9aafc51ff5a2551cabed9fe322917ed6842f1dda Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Fri, 15 Oct 2021 15:25:27 +0100 Subject: [PATCH 49/52] Add first pass version of click feedback while in Focus Mode (#4693) * add first pass version of click feedback while in Focus Mode Signed-off-by: hultonha * add more WIP experimental feedback ideas for Focus Mode Signed-off-by: hultonha * small updates after UX feedback to improve focus mode feedback Signed-off-by: hultonha * refactor and improve invalid click feedback Signed-off-by: hultonha * update comments from review feedback Signed-off-by: hultonha --- .../ViewportSelection/EditorHelpers.cpp | 33 +++- .../ViewportSelection/EditorHelpers.h | 20 ++- .../EditorTransformComponentSelection.cpp | 2 + .../ViewportSelection/InvalidClicks.cpp | 142 ++++++++++++++++++ .../ViewportSelection/InvalidClicks.h | 108 +++++++++++++ .../aztoolsframework_files.cmake | 2 + .../AtomDebugDisplayViewportInterface.cpp | 3 +- 7 files changed, 297 insertions(+), 13 deletions(-) create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.cpp create mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index bb718d0dc9..6399a64635 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -9,6 +9,7 @@ #include "EditorHelpers.h" #include +#include #include #include #include @@ -123,6 +124,11 @@ namespace AzToolsFramework "EditorHelpers - " "Focus Mode Interface could not be found. " "Check that it is being correctly initialized."); + + AZStd::vector> invalidClicks; + invalidClicks.push_back(AZStd::make_unique("Not in focus")); + invalidClicks.push_back(AZStd::make_unique()); + m_invalidClicks = AZStd::make_unique(AZStd::move(invalidClicks)); } AZ::EntityId EditorHelpers::HandleMouseInteraction( @@ -186,13 +192,20 @@ namespace AzToolsFramework } } - // Verify if the entity Id corresponds to an entity that is focused; if not, halt selection. - if (!IsSelectableAccordingToFocusMode(entityIdUnderCursor)) + // verify if the entity Id corresponds to an entity that is focused; if not, halt selection. + if (entityIdUnderCursor.IsValid() && !IsSelectableAccordingToFocusMode(entityIdUnderCursor)) { + if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left() && + mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down || + mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::DoubleClick) + { + m_invalidClicks->AddInvalidClick(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); + } + return AZ::EntityId(); } - // Container Entity support - if the entity that is being selected is part of a closed container, + // container entity support - if the entity that is being selected is part of a closed container, // change the selection to the container instead. if (ContainerEntityInterface* containerEntityInterface = AZ::Interface::Get()) { @@ -202,6 +215,12 @@ namespace AzToolsFramework return entityIdUnderCursor; } + void EditorHelpers::Display2d( + [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + { + m_invalidClicks->Display2d(viewportInfo, debugDisplay); + } + void EditorHelpers::DisplayHelpers( const AzFramework::ViewportInfo& viewportInfo, const AzFramework::CameraState& cameraState, @@ -263,19 +282,19 @@ namespace AzToolsFramework } } - bool EditorHelpers::IsSelectableInViewport(AZ::EntityId entityId) + bool EditorHelpers::IsSelectableInViewport(const AZ::EntityId entityId) const { return IsSelectableAccordingToFocusMode(entityId) && IsSelectableAccordingToContainerEntities(entityId); } - bool EditorHelpers::IsSelectableAccordingToFocusMode(AZ::EntityId entityId) + bool EditorHelpers::IsSelectableAccordingToFocusMode(const AZ::EntityId entityId) const { return m_focusModeInterface->IsInFocusSubTree(entityId); } - bool EditorHelpers::IsSelectableAccordingToContainerEntities(AZ::EntityId entityId) + bool EditorHelpers::IsSelectableAccordingToContainerEntities(const AZ::EntityId entityId) const { - if (ContainerEntityInterface* containerEntityInterface = AZ::Interface::Get()) + if (const auto* containerEntityInterface = AZ::Interface::Get()) { return !containerEntityInterface->IsUnderClosedContainerEntity(entityId); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h index 909a231635..6623221bdc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.h @@ -11,6 +11,9 @@ #include #include #include +#include +#include +#include namespace AzFramework { @@ -58,20 +61,27 @@ namespace AzToolsFramework AzFramework::DebugDisplayRequests& debugDisplay, const AZStd::function& showIconCheck); + //! Handle 2d drawing for EditorHelper functionality. + void Display2d( + const AzFramework::ViewportInfo& viewportInfo, + AzFramework::DebugDisplayRequests& debugDisplay); + //! Returns whether the entityId can be selected in the viewport according //! to the current Editor Focus Mode and Container Entity setup. - bool IsSelectableInViewport(AZ::EntityId entityId); + bool IsSelectableInViewport(AZ::EntityId entityId) const; private: //! Returns whether the entityId can be selected in the viewport according //! to the current Editor Focus Mode setup. - bool IsSelectableAccordingToFocusMode(AZ::EntityId entityId); + bool IsSelectableAccordingToFocusMode(AZ::EntityId entityId) const; //! Returns whether the entityId can be selected in the viewport according - //! to the current Container Entityu setup. - bool IsSelectableAccordingToContainerEntities(AZ::EntityId entityId); + //! to the current Container Entity setup. + bool IsSelectableAccordingToContainerEntities(AZ::EntityId entityId) const; + + AZStd::unique_ptr m_invalidClicks; //!< Display for invalid click behavior. const EditorVisibleEntityDataCache* m_entityDataCache = nullptr; //!< Entity Data queried by the EditorHelpers. - const FocusModeInterface* m_focusModeInterface = nullptr; + const FocusModeInterface* m_focusModeInterface = nullptr; //!< API to interact with focus mode functionality. }; } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index a37b84fdf8..c73742da4d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -3560,6 +3560,8 @@ namespace AzToolsFramework DrawAxisGizmo(viewportInfo, debugDisplay); m_boxSelect.Display2d(viewportInfo, debugDisplay); + + m_editorHelpers->Display2d(viewportInfo, debugDisplay); } void EditorTransformComponentSelection::RefreshSelectedEntityIds() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.cpp new file mode 100644 index 0000000000..dfff4da08f --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +AZ_CVAR(float, ed_invalidClickRadius, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Maximum invalid click radius to expand to"); +AZ_CVAR(float, ed_invalidClickDuration, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "Duration to display the invalid click feedback"); +AZ_CVAR(float, ed_invalidClickMessageSize, 0.8f, nullptr, AZ::ConsoleFunctorFlags::Null, "Size of text for invalid message"); +AZ_CVAR( + float, + ed_invalidClickMessageVerticalOffset, + 30.0f, + nullptr, + AZ::ConsoleFunctorFlags::Null, + "Vertical offset from cursor of invalid click message"); + +namespace AzToolsFramework +{ + void ExpandingFadingCircles::Begin(const AzFramework::ScreenPoint& screenPoint) + { + FadingCircle fadingCircle; + fadingCircle.m_position = screenPoint; + fadingCircle.m_opacity = 1.0f; + fadingCircle.m_radius = 0.0f; + m_fadingCircles.push_back(fadingCircle); + } + + void ExpandingFadingCircles::Update(const float deltaTime) + { + for (auto& fadingCircle : m_fadingCircles) + { + fadingCircle.m_opacity = AZStd::max(fadingCircle.m_opacity - (deltaTime / ed_invalidClickDuration), 0.0f); + fadingCircle.m_radius += deltaTime * ed_invalidClickRadius; + } + + m_fadingCircles.erase( + AZStd::remove_if( + m_fadingCircles.begin(), m_fadingCircles.end(), + [](const FadingCircle& fadingCircle) + { + return fadingCircle.m_opacity <= 0.0f; + }), + m_fadingCircles.end()); + } + + bool ExpandingFadingCircles::Updating() + { + return !m_fadingCircles.empty(); + } + + void ExpandingFadingCircles::Display(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + { + const AZ::Vector2 viewportSize = AzToolsFramework::GetCameraState(viewportInfo.m_viewportId).m_viewportSize; + + for (const auto& fadingCircle : m_fadingCircles) + { + const auto position = AzFramework::Vector2FromScreenPoint(fadingCircle.m_position) / viewportSize; + debugDisplay.SetColor(AZ::Color(1.0f, 1.0f, 1.0f, fadingCircle.m_opacity)); + debugDisplay.DrawWireCircle2d(position, fadingCircle.m_radius * 0.005f, 0.0f); + } + } + + void FadingText::Begin(const AzFramework::ScreenPoint& screenPoint) + { + m_opacity = 1.0f; + m_invalidClickPosition = screenPoint; + } + + void FadingText::Update(const float deltaTime) + { + m_opacity -= deltaTime / ed_invalidClickDuration; + } + + bool FadingText::Updating() + { + return m_opacity >= 0.0f; + } + + void FadingText::Display( + [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + { + if (constexpr float MinOpacity = 0.05f; m_opacity >= MinOpacity) + { + debugDisplay.SetColor(AZ::Color(1.0f, 1.0f, 1.0f, m_opacity)); + debugDisplay.Draw2dTextLabel( + aznumeric_cast(m_invalidClickPosition.m_x), + aznumeric_cast(m_invalidClickPosition.m_y) - ed_invalidClickMessageVerticalOffset, ed_invalidClickMessageSize, + m_message.c_str(), true); + } + } + + void InvalidClicks::AddInvalidClick(const AzFramework::ScreenPoint& screenPoint) + { + AZ::TickBus::Handler::BusConnect(); + + for (auto& invalidClickBehavior : m_invalidClickBehaviors) + { + invalidClickBehavior->Begin(screenPoint); + } + } + + void InvalidClicks::OnTick(const float deltaTime, [[maybe_unused]] const AZ::ScriptTimePoint time) + { + for (auto& invalidClickBehavior : m_invalidClickBehaviors) + { + invalidClickBehavior->Update(deltaTime); + } + + const auto updating = AZStd::any_of( + m_invalidClickBehaviors.begin(), m_invalidClickBehaviors.end(), + [](const auto& invalidClickBehavior) + { + return invalidClickBehavior->Updating(); + }); + + if (!updating && AZ::TickBus::Handler::BusIsConnected()) + { + AZ::TickBus::Handler::BusDisconnect(); + } + } + + void InvalidClicks::Display2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + { + debugDisplay.DepthTestOff(); + + for (const auto& invalidClickBehavior : m_invalidClickBehaviors) + { + invalidClickBehavior->Display(viewportInfo, debugDisplay); + } + + debugDisplay.DepthTestOn(); + } +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.h new file mode 100644 index 0000000000..55a6d614ea --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/InvalidClicks.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace AzFramework +{ + class DebugDisplayRequests; + struct ViewportInfo; +} // namespace AzFramework + +namespace AzToolsFramework +{ + namespace ViewportInteraction + { + struct MouseInteractionEvent; + } + + //! An interface to provide invalid click feedback in the editor viewport. + class InvalidClick + { + public: + virtual ~InvalidClick() = default; + + //! Begin the feedback. + //! @param screenPoint The position of the click in screen coordinates. + virtual void Begin(const AzFramework::ScreenPoint& screenPoint) = 0; + //! Update the invalid click feedback + virtual void Update(float deltaTime) = 0; + //! Report if the click feedback is running or not (returning false will signal the TickBus can be disconnected from). + virtual bool Updating() = 0; + //! Display the click feedback in the viewport. + virtual void Display(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) = 0; + }; + + //! Display expanding fading circles for every click of the mouse that is invalid. + class ExpandingFadingCircles : public InvalidClick + { + public: + void Begin(const AzFramework::ScreenPoint& screenPoint) override; + void Update(float deltaTime) override; + bool Updating() override; + void Display(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + + private: + //! Stores a circle representation with a lifetime to grow and fade out over time. + struct FadingCircle + { + AzFramework::ScreenPoint m_position; + float m_radius; + float m_opacity; + }; + + using FadingCircles = AZStd::vector; + FadingCircles m_fadingCircles; //!< Collection of fading circles to draw for clicks that have no effect. + }; + + //! Display fading text where an invalid click happened. + //! @note There is only one fading text, each click will update its position. + class FadingText : public InvalidClick + { + public: + explicit FadingText(AZStd::string message) + : m_message(AZStd::move(message)) + { + } + + void Begin(const AzFramework::ScreenPoint& screenPoint) override; + void Update(float deltaTime) override; + bool Updating() override; + void Display(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + + private: + AZStd::string m_message; //!< Message to display for fading text. + float m_opacity = 1.0f; //!< The opacity of the invalid click message. + AzFramework::ScreenPoint m_invalidClickPosition; //!< The position to display the invalid click message. + }; + + //! Interface to begin invalid click feedback (will run all added InvalidClick behaviors). + class InvalidClicks : private AZ::TickBus::Handler + { + public: + explicit InvalidClicks(AZStd::vector> invalidClickBehaviors) + : m_invalidClickBehaviors(AZStd::move(invalidClickBehaviors)) + { + } + + //! Add an invalid click and activate one or more of the added invalid click behaviors. + void AddInvalidClick(const AzFramework::ScreenPoint& screenPoint); + + //! Handle 2d drawing for EditorHelper functionality. + void Display2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay); + + private: + //! AZ::TickBus overrides ... + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + + AZStd::vector> m_invalidClickBehaviors; //!< Invalid click behaviors to run. + }; +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 8dec7ab611..5db65f89f4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -553,6 +553,8 @@ set(FILES ViewportSelection/EditorTransformComponentSelectionRequestBus.cpp ViewportSelection/EditorVisibleEntityDataCache.h ViewportSelection/EditorVisibleEntityDataCache.cpp + ViewportSelection/InvalidClicks.h + ViewportSelection/InvalidClicks.cpp ViewportSelection/ViewportEditorModeTracker.cpp ViewportSelection/ViewportEditorModeTracker.h ToolsFileUtils/ToolsFileUtils.h diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index b45fbe05f6..39d8933863 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -1353,8 +1353,9 @@ namespace AZ::AtomBridge // if 2d draw need to project pos to screen first AzFramework::TextDrawParameters params; AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + const auto dpiScaleFactor = viewportContext->GetDpiScalingFactor(); params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = AZ::Vector3(x, y, 1.0f); + params.m_position = AZ::Vector3(x * dpiScaleFactor, y * dpiScaleFactor, 1.0f); params.m_color = m_rendState.m_color; params.m_scale = AZ::Vector2(size); params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment From 7651ba621c59fc2efa7b95bb5a837ee66bd20f38 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Fri, 15 Oct 2021 08:53:26 -0700 Subject: [PATCH 50/52] Remove old "Integ" functionality from tests (#4688) * fixes some warnings for newer versions of VS2022 Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * more warning fixes Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * remove integ test filters from AzTest Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * remove integ test handling from AzTestRunner Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * changes integ tests of gridmate to regular tests and disables failing ones Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * removes the Integ from the EMotionFX tests, but leaves them disabled since they are failing Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * removes the Integ from the HttpRequestor tests and disables it since is not passing Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * changing integ tests for DISABLED, these ones are using files that are not there Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * fixes linux build gridmate tests that were Integ are now disabled Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> * fixes linux warnings Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- .../Tests/Asset/AssetManagerLoadingTests.cpp | 3 + .../Tests/Debug/LocalFileEventLoggerTests.cpp | 6 + .../IO/Streamer/StorageDriveTests_Windows.cpp | 18 ++ Code/Framework/AzCore/Tests/StringFunc.cpp | 6 + .../SpawnableEntitiesManagerTests.cpp | 15 +- Code/Framework/AzTest/AzTest/AzTest.cpp | 9 - Code/Framework/AzTest/AzTest/AzTest.h | 2 - Code/Framework/GridMate/Tests/Carrier.cpp | 80 +++--- .../Tests/CarrierStreamSocketDriverTests.cpp | 22 +- Code/Framework/GridMate/Tests/Replica.cpp | 95 ++++--- .../GridMate/Tests/ReplicaBehavior.cpp | 88 +++---- .../GridMate/Tests/ReplicaMedium.cpp | 160 ++++++------ Code/Framework/GridMate/Tests/Session.cpp | 60 ++--- .../Tests/StreamSecureSocketDriverTests.cpp | 30 +-- .../Tests/StreamSocketDriverTests.cpp | 4 +- .../Framework/GridMate/Tests/TestProfiler.cpp | 244 ------------------ Code/Framework/GridMate/Tests/TestProfiler.h | 24 -- .../GridMate/Tests/gridmate_test_files.cmake | 1 + Code/Tools/AzTestRunner/src/main.cpp | 79 +----- .../Tests/Integration/PoseComparisonFixture.h | 6 +- .../Tests/Integration/PoseComparisonTests.cpp | 38 +-- .../Code/Tests/HttpRequestorTest.cpp | 68 +++-- .../Tests/BundlingSystemComponentTests.cpp | 18 +- 23 files changed, 381 insertions(+), 695 deletions(-) delete mode 100644 Code/Framework/GridMate/Tests/TestProfiler.cpp delete mode 100644 Code/Framework/GridMate/Tests/TestProfiler.h diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp index 3e6376323c..e33dbce9c1 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp @@ -736,7 +736,10 @@ namespace UnitTest auto& assetManager = AssetManager::Instance(); AssetBusCallbacks callbacks{}; + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning callbacks.SetOnAssetReadyCallback([&, AssetNoRefB](const Asset&, AssetBusCallbacks&) + AZ_POP_DISABLE_WARNING { // This callback should run inside the "main thread" dispatch events loop auto loadAsset = assetManager.GetAsset(AZ::Uuid(AssetNoRefB), AssetLoadBehavior::Default); diff --git a/Code/Framework/AzCore/Tests/Debug/LocalFileEventLoggerTests.cpp b/Code/Framework/AzCore/Tests/Debug/LocalFileEventLoggerTests.cpp index 242ac0e65d..d4b3351dbe 100644 --- a/Code/Framework/AzCore/Tests/Debug/LocalFileEventLoggerTests.cpp +++ b/Code/Framework/AzCore/Tests/Debug/LocalFileEventLoggerTests.cpp @@ -109,7 +109,10 @@ namespace AZ::Debug AZStd::thread threads[totalThreads]; for (size_t threadIndex = 0; threadIndex < totalThreads; ++threadIndex) { + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning threads[threadIndex] = AZStd::thread([&startLogging, &messages]() + AZ_POP_DISABLE_WARNING { while (!startLogging) { @@ -226,7 +229,10 @@ namespace AZ::Debug AZStd::thread threads[totalThreads]; for (size_t threadIndex = 0; threadIndex < totalThreads; ++threadIndex) { + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning threads[threadIndex] = AZStd::thread([&startLogging, &message, &totalRecordsWritten]() + AZ_POP_DISABLE_WARNING { AZ_UNUSED(message); diff --git a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp index 22fb6379d2..e312e2058d 100644 --- a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp +++ b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp @@ -597,7 +597,10 @@ namespace AZ::IO path.InitFromAbsolutePath(m_dummyFilepath); request->CreateRead(nullptr, buffer.get(), fileSize, path, 0, fileSize); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [&fileSize, this](const FileRequest& request) + AZ_POP_DISABLE_WARNING { EXPECT_EQ(request.GetStatus(), AZ::IO::IStreamerTypes::RequestStatus::Completed); auto& readRequest = AZStd::get(request.GetCommand()); @@ -639,7 +642,10 @@ namespace AZ::IO path.InitFromAbsolutePath(m_dummyFilepath); request->CreateRead(nullptr, buffer, unalignedSize + 4, path, unalignedOffset, unalignedSize); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [unalignedOffset, unalignedSize, this](const FileRequest& request) + AZ_POP_DISABLE_WARNING { EXPECT_EQ(request.GetStatus(), AZ::IO::IStreamerTypes::RequestStatus::Completed); auto& readRequest = AZStd::get(request.GetCommand()); @@ -784,7 +790,10 @@ namespace AZ::IO requests[i] = m_context->GetNewInternalRequest(); requests[i]->CreateRead(nullptr, buffers[i].get(), chunkSize, path, i * chunkSize, chunkSize); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [chunkSize, i](const FileRequest& request) + AZ_POP_DISABLE_WARNING { EXPECT_EQ(request.GetStatus(), AZ::IO::IStreamerTypes::RequestStatus::Completed); auto& readRequest = AZStd::get(request.GetCommand()); @@ -970,7 +979,10 @@ namespace AZ::IO i * chunkSize )); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [numChunks, &numCallbacks, &waitForReads](FileRequestHandle request) + AZ_POP_DISABLE_WARNING { IStreamer* streamer = Interface::Get(); if (streamer) @@ -1038,7 +1050,10 @@ namespace AZ::IO i * chunkSize )); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [numChunks, &waitForReads, &waitForSingleRead, &numReadCallbacks]([[maybe_unused]] FileRequestHandle request) + AZ_POP_DISABLE_WARNING { numReadCallbacks++; if (numReadCallbacks == 1) @@ -1059,7 +1074,10 @@ namespace AZ::IO for (size_t i = 0; i < numChunks; ++i) { cancels.push_back(m_streamer->Cancel(requests[numChunks - i - 1])); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [&numCancelCallbacks, &waitForCancels, numChunks](FileRequestHandle request) + AZ_POP_DISABLE_WARNING { auto result = Interface::Get()->GetRequestStatus(request); EXPECT_EQ(result, IStreamerTypes::RequestStatus::Completed); diff --git a/Code/Framework/AzCore/Tests/StringFunc.cpp b/Code/Framework/AzCore/Tests/StringFunc.cpp index 68821ba3f9..dc4bc40e5b 100644 --- a/Code/Framework/AzCore/Tests/StringFunc.cpp +++ b/Code/Framework/AzCore/Tests/StringFunc.cpp @@ -363,7 +363,10 @@ namespace AZ { constexpr AZStd::array visitTokens = { "Hello", "World", "", "More", "", "", "Tokens" }; size_t visitIndex{}; + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto visitor = [&visitIndex, &visitTokens](AZStd::string_view token) + AZ_POP_DISABLE_WARNING { if (visitIndex > visitTokens.size()) { @@ -389,7 +392,10 @@ namespace AZ { constexpr AZStd::array visitTokens = { "Hello", "World", "", "More", "", "", "Tokens" }; size_t visitIndex = visitTokens.size() - 1; + AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto visitor = [&visitIndex, &visitTokens](AZStd::string_view token) + AZ_POP_DISABLE_WARNING { if (visitIndex > visitTokens.size()) { diff --git a/Code/Framework/AzFramework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp b/Code/Framework/AzFramework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp index 407ab1d21f..2dc32d14d5 100644 --- a/Code/Framework/AzFramework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp +++ b/Code/Framework/AzFramework/Tests/Spawnable/SpawnableEntitiesManagerTests.cpp @@ -569,11 +569,12 @@ namespace UnitTest FillSpawnable(NumEntities); CreateEntityReferences(refScheme); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunused-lambda-capture") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [this, refScheme, NumEntities](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + AZ_POP_DISABLE_WARNING { - AZ_UNUSED(refScheme); - AZ_UNUSED(NumEntities); ValidateEntityReferences(refScheme, NumEntities, entities); }; @@ -591,11 +592,12 @@ namespace UnitTest FillSpawnable(NumEntities); CreateEntityReferences(refScheme); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunused-lambda-capture") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [this, refScheme, NumEntities](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + AZ_POP_DISABLE_WARNING { - AZ_UNUSED(refScheme); - AZ_UNUSED(NumEntities); ValidateEntityReferences(refScheme, NumEntities, entities); }; @@ -720,11 +722,12 @@ namespace UnitTest FillSpawnable(NumEntities); CreateEntityReferences(refScheme); + AZ_PUSH_DISABLE_WARNING(5233, "-Wunused-lambda-capture") // Older versions of MSVC toolchain require to pass constexpr in the + // capture. Newer versions issue unused warning auto callback = [this, refScheme, NumEntities](AzFramework::EntitySpawnTicket::Id, AzFramework::SpawnableConstEntityContainerView entities) + AZ_POP_DISABLE_WARNING { - AZ_UNUSED(refScheme); - AZ_UNUSED(NumEntities); ValidateEntityReferences(refScheme, NumEntities, entities); }; diff --git a/Code/Framework/AzTest/AzTest/AzTest.cpp b/Code/Framework/AzTest/AzTest/AzTest.cpp index 3b809d2c96..eede87b29e 100644 --- a/Code/Framework/AzTest/AzTest/AzTest.cpp +++ b/Code/Framework/AzTest/AzTest/AzTest.cpp @@ -90,13 +90,6 @@ namespace AZ } } - //! Filter out integration tests from the test run - void excludeIntegTests() - { - AddExcludeFilter("INTEG_*"); - AddExcludeFilter("Integ_*"); - } - void ApplyGlobalParameters(int* argc, char** argv) { // this is a hook that can be used to apply any other global non-google parameters @@ -160,7 +153,6 @@ namespace AZ } ::testing::InitGoogleMock(&argc, argv); - AZ::Test::excludeIntegTests(); AZ::Test::ApplyGlobalParameters(&argc, argv); AZ::Test::printUnusedParametersWarning(argc, argv); AZ::Test::addTestEnvironments(m_envs); @@ -281,7 +273,6 @@ namespace AZ } } - AZ::Test::excludeIntegTests(); AZ::Test::printUnusedParametersWarning(argc, argv); return RUN_ALL_TESTS(); diff --git a/Code/Framework/AzTest/AzTest/AzTest.h b/Code/Framework/AzTest/AzTest/AzTest.h index 352db1a0b5..4b038cabd4 100644 --- a/Code/Framework/AzTest/AzTest/AzTest.h +++ b/Code/Framework/AzTest/AzTest/AzTest.h @@ -104,7 +104,6 @@ namespace AZ void addTestEnvironment(ITestEnvironment* env); void addTestEnvironments(std::vector envs); - void excludeIntegTests(); //! A hook that can be used to read any other misc parameters and remove them before google sees them. //! Note that this modifies argc and argv to delete the parameters it consumes. @@ -266,7 +265,6 @@ namespace AZ ::testing::TestEventListeners& listeners = testing::UnitTest::GetInstance()->listeners(); \ listeners.Append(new AZ::Test::OutputEventListener); \ } \ - AZ::Test::excludeIntegTests(); \ AZ::Test::ApplyGlobalParameters(&argc, argv); \ AZ::Test::printUnusedParametersWarning(argc, argv); \ AZ::Test::addTestEnvironments({TEST_ENV}); \ diff --git a/Code/Framework/GridMate/Tests/Carrier.cpp b/Code/Framework/GridMate/Tests/Carrier.cpp index 5b18a80221..29550d8b68 100644 --- a/Code/Framework/GridMate/Tests/Carrier.cpp +++ b/Code/Framework/GridMate/Tests/Carrier.cpp @@ -333,7 +333,7 @@ namespace UnitTest }; template - class Integ_CarrierAsyncHandshakeTestTemplate + class CarrierAsyncHandshakeTestTemplate : public GridMateMPTestFixture , protected SocketProvider { @@ -761,7 +761,7 @@ namespace UnitTest }; template - class Integ_CarrierDisconnectDetectionTestTemplate + class CarrierDisconnectDetectionTestTemplate : public GridMateMPTestFixture , protected SocketProvider { @@ -846,7 +846,7 @@ namespace UnitTest * Sends reliable messages across different channels to each other */ template - class Integ_CarrierMultiChannelTestTemplate + class CarrierMultiChannelTestTemplate : public GridMateMPTestFixture , protected SocketProvider { @@ -950,7 +950,7 @@ namespace UnitTest * Stress tests multiple simultaneous Carriers */ template - class Integ_CarrierMultiStressTestTemplate + class CarrierMultiStressTestTemplate : public GridMateMPTestFixture , protected SocketProvider { @@ -977,7 +977,7 @@ namespace UnitTest public: void run() { - AZ_TracePrintf("GridMate", "Integ_CarrierMultiStressTest\n\n"); + AZ_TracePrintf("GridMate", "CarrierMultiStressTest\n\n"); // initialize transport const int k_numChannels = 1; @@ -1108,7 +1108,7 @@ namespace UnitTest /*** Congestion control back pressure test */ template - class Integ_CarrierBackpressureTestTemplate + class CarrierBackpressureTestTemplate : public GridMateMPTestFixture , protected SocketProvider , public CarrierEventBus::Handler @@ -1380,7 +1380,7 @@ namespace UnitTest }; template - class Integ_CarrierACKTestTemplate + class CarrierACKTestTemplate : public GridMateMPTestFixture , protected SocketProvider { @@ -1544,13 +1544,13 @@ namespace UnitTest //Create specific tests using CarrierBasicTest = CarrierBasicTestTemplate<>; using CarrierTest = CarrierTestTemplate<>; - using Integ_CarrierDisconnectDetectionTest = Integ_CarrierDisconnectDetectionTestTemplate<>; - using Integ_CarrierAsyncHandshakeTest = Integ_CarrierAsyncHandshakeTestTemplate<>; - using Integ_CarrierStressTest = CarrierStressTestTemplate<>; - using Integ_CarrierMultiChannelTest = Integ_CarrierMultiChannelTestTemplate<>; - using Integ_CarrierMultiStressTest = Integ_CarrierMultiStressTestTemplate<>; - using Integ_CarrierBackpressureTest = Integ_CarrierBackpressureTestTemplate<>; - using Integ_CarrierACKTest = Integ_CarrierACKTestTemplate<>; + using DISABLED_CarrierDisconnectDetectionTest = CarrierDisconnectDetectionTestTemplate<>; + using DISABLED_CarrierAsyncHandshakeTest = CarrierAsyncHandshakeTestTemplate<>; + using DISABLED_CarrierStressTest = CarrierStressTestTemplate<>; + using DISABLED_CarrierMultiChannelTest = CarrierMultiChannelTestTemplate<>; + using DISABLED_CarrierMultiStressTest = CarrierMultiStressTestTemplate<>; + using DISABLED_CarrierBackpressureTest = CarrierBackpressureTestTemplate<>; + using DISABLED_CarrierACKTest = CarrierACKTestTemplate<>; #if AZ_TRAIT_GRIDMATE_TEST_WITH_SECURE_SOCKET_DRIVER @@ -1658,20 +1658,20 @@ namespace UnitTest using SecureProviderBadHost = SecureDriverProvider>; using SecureProviderBadBoth = SecureDriverProvider, SecureSocketHandshakeDrop>; - using Integ_CarrierSecureSocketHandshakeTestClient = CarrierBasicTestTemplate; - using Integ_CarrierSecureSocketHandshakeTestHost = CarrierBasicTestTemplate; - using Integ_CarrierSecureSocketHandshakeTestBoth = CarrierBasicTestTemplate; + using DISABLED_CarrierSecureSocketHandshakeTestClient = CarrierBasicTestTemplate; + using DISABLED_CarrierSecureSocketHandshakeTestHost = CarrierBasicTestTemplate; + using DISABLED_CarrierSecureSocketHandshakeTestBoth = CarrierBasicTestTemplate; //Create secure socket variants of tests using CarrierBasicTestSecure = CarrierBasicTestTemplate>; using CarrierTestSecure = CarrierTestTemplate>; - using Integ_CarrierDisconnectDetectionTestSecure = Integ_CarrierDisconnectDetectionTestTemplate>; - using Integ_CarrierAsyncHandshakeTestSecure = Integ_CarrierAsyncHandshakeTestTemplate>; - using Integ_CarrierStressTestSecure = CarrierStressTestTemplate>; - using Integ_CarrierMultiChannelTestSecure = Integ_CarrierMultiChannelTestTemplate>; - using Integ_CarrierMultiStressTestSecure = Integ_CarrierMultiStressTestTemplate>; - using Integ_CarrierBackpressureTestSecure = Integ_CarrierBackpressureTestTemplate>; - using Integ_CarrierACKTestSecure = Integ_CarrierACKTestTemplate>; + using DISABLED_CarrierDisconnectDetectionTestSecure = CarrierDisconnectDetectionTestTemplate>; + using DISABLED_CarrierAsyncHandshakeTestSecure = CarrierAsyncHandshakeTestTemplate>; + using DISABLED_CarrierStressTestSecure = CarrierStressTestTemplate>; + using DISABLED_CarrierMultiChannelTestSecure = CarrierMultiChannelTestTemplate>; + using DISABLED_CarrierMultiStressTestSecure = CarrierMultiStressTestTemplate>; + using DISABLED_CarrierBackpressureTestSecure = CarrierBackpressureTestTemplate>; + using DISABLED_CarrierACKTestSecure = CarrierACKTestTemplate>; #endif } @@ -1720,30 +1720,30 @@ GM_TEST_SUITE(CarrierSuite) GM_TEST(CarrierBasicTest) GM_TEST(CarrierTest) #endif //AZ_TRAIT_GRIDMATE_UNIT_TEST_DISABLE_CARRIER_SESSION_TESTS -GM_TEST(Integ_CarrierAsyncHandshakeTest) +GM_TEST(DISABLED_CarrierAsyncHandshakeTest) #if !defined(AZ_DEBUG_BUILD) // this test is a little slow for debug -GM_TEST(Integ_CarrierStressTest) -GM_TEST(Integ_CarrierMultiStressTest) +GM_TEST(DISABLED_CarrierStressTest) +GM_TEST(DISABLED_CarrierMultiStressTest) #endif -GM_TEST(Integ_CarrierMultiChannelTest) -GM_TEST(Integ_CarrierBackpressureTest) -GM_TEST(Integ_CarrierACKTest) +GM_TEST(DISABLED_CarrierMultiChannelTest) +GM_TEST(DISABLED_CarrierBackpressureTest) +GM_TEST(DISABLED_CarrierACKTest) #if AZ_TRAIT_GRIDMATE_TEST_WITH_SECURE_SOCKET_DRIVER -GM_TEST(CarrierBasicTestSecure) -GM_TEST(Integ_CarrierSecureSocketHandshakeTestClient) -GM_TEST(Integ_CarrierSecureSocketHandshakeTestHost) -GM_TEST(Integ_CarrierSecureSocketHandshakeTestBoth) +GM_TEST(DISABLED_CarrierBasicTestSecure) +GM_TEST(DISABLED_CarrierSecureSocketHandshakeTestClient) +GM_TEST(DISABLED_CarrierSecureSocketHandshakeTestHost) +GM_TEST(DISABLED_CarrierSecureSocketHandshakeTestBoth) GM_TEST(CarrierTestSecure) -GM_TEST(Integ_CarrierAsyncHandshakeTestSecure) +GM_TEST(DISABLED_CarrierAsyncHandshakeTestSecure) #if !defined(AZ_DEBUG_BUILD) // this test is a little slow for debug -GM_TEST(Integ_CarrierStressTestSecure) -GM_TEST(Integ_CarrierMultiStressTestSecure) +GM_TEST(DISABLED_CarrierStressTestSecure) +GM_TEST(DISABLED_CarrierMultiStressTestSecure) #endif -GM_TEST(Integ_CarrierMultiChannelTestSecure) -GM_TEST(Integ_CarrierBackpressureTestSecure) -GM_TEST(Integ_CarrierACKTestSecure) +GM_TEST(DISABLED_CarrierMultiChannelTestSecure) +GM_TEST(DISABLED_CarrierBackpressureTestSecure) +GM_TEST(DISABLED_CarrierACKTestSecure) #endif diff --git a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp index 8ec3ad540f..dd0d6f1b2b 100644 --- a/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp +++ b/Code/Framework/GridMate/Tests/CarrierStreamSocketDriverTests.cpp @@ -172,7 +172,7 @@ public: namespace UnitTest { - class Integ_CarrierStreamBasicTest + class DISABLED_CarrierStreamBasicTest : public GridMateMPTestFixture , protected SocketDriverSupplier { @@ -330,7 +330,7 @@ namespace UnitTest } }; - class Integ_CarrierStreamAsyncHandshakeTest + class DISABLED_CarrierStreamAsyncHandshakeTest : public GridMateMPTestFixture , protected SocketDriverSupplier { @@ -462,7 +462,7 @@ namespace UnitTest } }; - class Integ_CarrierStreamStressTest + class CarrierStreamStressTest : public GridMateMPTestFixture , protected SocketDriverSupplier , public ::testing::Test @@ -470,7 +470,7 @@ namespace UnitTest public: }; - TEST_F(Integ_CarrierStreamStressTest, Stress_Test) + TEST_F(CarrierStreamStressTest, DISABLED_Stress_Test) { CarrierStreamCallbacksHandler clientCB, serverCB; UnitTest::TestCarrierDesc serverCarrierDesc, clientCarrierDesc; @@ -581,7 +581,7 @@ namespace UnitTest ////////////////////////////////////////////////////////////////////////// } - class Integ_CarrierStreamTest + class DISABLED_CarrierStreamTest : public GridMateMPTestFixture , protected SocketDriverSupplier { @@ -783,7 +783,7 @@ namespace UnitTest } }; - class Integ_CarrierStreamDisconnectDetectionTest + class DISABLED_CarrierStreamDisconnectDetectionTest : public GridMateMPTestFixture , protected SocketDriverSupplier { @@ -873,7 +873,7 @@ namespace UnitTest } }; - class Integ_CarrierStreamMultiChannelTest + class DISABLED_CarrierStreamMultiChannelTest : public GridMateMPTestFixture , protected SocketDriverSupplier { @@ -999,8 +999,8 @@ namespace UnitTest } GM_TEST_SUITE(CarrierStreamSuite) - GM_TEST(Integ_CarrierStreamBasicTest) - GM_TEST(Integ_CarrierStreamTest) - GM_TEST(Integ_CarrierStreamAsyncHandshakeTest) - GM_TEST(Integ_CarrierStreamMultiChannelTest) + GM_TEST(DISABLED_CarrierStreamBasicTest) + GM_TEST(DISABLED_CarrierStreamTest) + GM_TEST(DISABLED_CarrierStreamAsyncHandshakeTest) + GM_TEST(DISABLED_CarrierStreamMultiChannelTest) GM_TEST_SUITE_END() diff --git a/Code/Framework/GridMate/Tests/Replica.cpp b/Code/Framework/GridMate/Tests/Replica.cpp index 83a3a1f5a1..5fef135347 100644 --- a/Code/Framework/GridMate/Tests/Replica.cpp +++ b/Code/Framework/GridMate/Tests/Replica.cpp @@ -6,7 +6,6 @@ * */ #include "Tests.h" -#include "TestProfiler.h" #include @@ -1888,12 +1887,12 @@ protected: }; //----------------------------------------------------------------------------- -class Integ_ReplicaGMTest +class ReplicaGMTest : public UnitTest::GridMateMPTestFixture , public ::testing::Test {}; -TEST_F(Integ_ReplicaGMTest, ReplicaTest) +TEST_F(ReplicaGMTest, DISABLED_ReplicaTest) { ReplicaChunkDescriptorTable::Get().RegisterChunkType(); ReplicaChunkDescriptorTable::Get().RegisterChunkType(); @@ -2157,7 +2156,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) } } -class Integ_ForcedReplicaMigrationTest +class ForcedReplicaMigrationTest : public UnitTest::GridMateMPTestFixture , public ReplicaMgrCallbackBus::Handler , public MigratableReplica::MigratableReplicaDebugMsgs::EBus::Handler @@ -2186,8 +2185,8 @@ class Integ_ForcedReplicaMigrationTest } public: - Integ_ForcedReplicaMigrationTest() { ReplicaMgrCallbackBus::Handler::BusConnect(m_gridMate); } - ~Integ_ForcedReplicaMigrationTest() { ReplicaMgrCallbackBus::Handler::BusDisconnect(); } + ForcedReplicaMigrationTest() { ReplicaMgrCallbackBus::Handler::BusConnect(m_gridMate); } + ~ForcedReplicaMigrationTest() { ReplicaMgrCallbackBus::Handler::BusDisconnect(); } enum @@ -2205,11 +2204,11 @@ public: AZStd::unordered_map m_replicaOwnership; }; -const int Integ_ForcedReplicaMigrationTest::k_frameTimePerNodeMs; -const int Integ_ForcedReplicaMigrationTest::k_numFramesToRun; -const int Integ_ForcedReplicaMigrationTest::k_hostSendRateMs; +const int ForcedReplicaMigrationTest::k_frameTimePerNodeMs; +const int ForcedReplicaMigrationTest::k_numFramesToRun; +const int ForcedReplicaMigrationTest::k_hostSendRateMs; -TEST_F(Integ_ForcedReplicaMigrationTest, ForcedReplicaMigrationTest) +TEST_F(ForcedReplicaMigrationTest, DISABLED_ForcedReplicaMigrationTest) { ReplicaChunkDescriptorTable::Get().RegisterChunkType(); ReplicaChunkDescriptorTable::Get().RegisterChunkType(); @@ -2360,7 +2359,7 @@ TEST_F(Integ_ForcedReplicaMigrationTest, ForcedReplicaMigrationTest) MigratableReplica::MigratableReplicaDebugMsgs::EBus::Handler::BusDisconnect(); } -class Integ_ReplicaMigrationRequestTest +class ReplicaMigrationRequestTest : public UnitTest::GridMateMPTestFixture , public ::testing::Test { @@ -2516,7 +2515,7 @@ public: static const int k_hostSendTimeMs = k_frameTimePerNodeMs * TotalNodes * 4; // limiting host send rate to be x4 times slower than tick }; -TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) +TEST_F(ReplicaMigrationRequestTest, DISABLED_ReplicaMigrationRequestTest) { /* Topology: @@ -2837,11 +2836,11 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) } } -const int Integ_ReplicaMigrationRequestTest::k_frameTimePerNodeMs; -const int Integ_ReplicaMigrationRequestTest::k_hostSendTimeMs; +const int ReplicaMigrationRequestTest::k_frameTimePerNodeMs; +const int ReplicaMigrationRequestTest::k_hostSendTimeMs; -class Integ_PeerRejoinTest +class PeerRejoinTest : public UnitTest::GridMateMPTestFixture , public ReplicaMgrCallbackBus::Handler , public ::testing::Test @@ -2860,11 +2859,11 @@ class Integ_PeerRejoinTest } public: - Integ_PeerRejoinTest() { ReplicaMgrCallbackBus::Handler::BusConnect(m_gridMate); } - ~Integ_PeerRejoinTest() { ReplicaMgrCallbackBus::Handler::BusDisconnect(); } + PeerRejoinTest() { ReplicaMgrCallbackBus::Handler::BusConnect(m_gridMate); } + ~PeerRejoinTest() { ReplicaMgrCallbackBus::Handler::BusDisconnect(); } }; -TEST_F(Integ_PeerRejoinTest, PeerRejoinTest) +TEST_F(PeerRejoinTest, DISABLED_PeerRejoinTest) { ReplicaChunkDescriptorTable::Get().RegisterChunkType(); ReplicaChunkDescriptorTable::Get().RegisterChunkType(); @@ -3011,7 +3010,7 @@ TEST_F(Integ_PeerRejoinTest, PeerRejoinTest) } } -class Integ_ReplicationSecurityOptionsTest +class ReplicationSecurityOptionsTest : public UnitTest::GridMateMPTestFixture , public ::testing::Test { @@ -3156,7 +3155,7 @@ public: using TestChunkPtr = AZStd::intrusive_ptr ; }; -TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) +TEST_F(ReplicationSecurityOptionsTest, DISABLED_ReplicationSecurityOptionsTest) { AZ_TracePrintf("GridMate", "\n"); @@ -3356,7 +3355,7 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) Replica update time (msec): avg=4.94, min=1, max=9 (peers=40, replicas=16000, freq=10%, samples=4000) Replica update time (msec): avg=8.05, min=6, max=15 (peers=40, replicas=16000, freq=100%, samples=4000) */ -class Integ_ReplicaStressTest +class DISABLED_ReplicaStressTest : public UnitTest::GridMateMPTestFixture { public: @@ -3388,7 +3387,7 @@ public: static const int BASE_PORT = 44270; // TODO: Reduce the size or disable the test for platforms which can't allocate 2 GiB - Integ_ReplicaStressTest() + DISABLED_ReplicaStressTest() : UnitTest::GridMateMPTestFixture(2000u * 1024u * 1024u) {} @@ -3516,33 +3515,33 @@ public: virtual void RunStressTests(MPSession* sessions, vector >& replicas) { // testing 3 cases & waiting for system to settle in between - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); Wait(sessions, replicas, 50, FRAME_TIME); - TestProfiler::PrintProfilingTotal("GridMate"); + //TestProfiler::PrintProfilingTotal("GridMate"); Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 100, FRAME_TIME, 0.0); // no replicas are dirty - TestProfiler::PrintProfilingTotal("GridMate"); + //TestProfiler::PrintProfilingTotal("GridMate"); Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 1, FRAME_TIME, 1.0); // single burst dirty replicas Wait(sessions, replicas, 2, FRAME_TIME); - TestProfiler::PrintProfilingTotal("GridMate"); + //TestProfiler::PrintProfilingTotal("GridMate"); Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 100, FRAME_TIME, 0.1); // 10% of replicas are marked dirty every frame - TestProfiler::PrintProfilingTotal("GridMate"); + //TestProfiler::PrintProfilingTotal("GridMate"); Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 100, FRAME_TIME, 1.0); // every replica is marked dirty every frame - TestProfiler::PrintProfilingTotal("GridMate"); - TestProfiler::PrintProfilingSelf("GridMate"); + //TestProfiler::PrintProfilingTotal("GridMate"); + //TestProfiler::PrintProfilingSelf("GridMate"); - TestProfiler::StopProfiling(); + //TestProfiler::StopProfiling(); } virtual void MarkChanging(vector >& replicas, double freq) @@ -3623,8 +3622,8 @@ public: Replica update time (msec): avg=2.01, min=1, max=5 (peers=40, replicas=16000, freq=10%, samples=4000) Replica update time (msec): avg=4.61, min=3, max=10 (peers=40, replicas=16000, freq=50%, samples=4000) */ -class Integ_ReplicaStableStressTest - : public Integ_ReplicaStressTest +class DISABLED_ReplicaStableStressTest + : public DISABLED_ReplicaStressTest { public: @@ -3636,21 +3635,21 @@ public: void RunStressTests(MPSession* sessions, vector >& replicas) override { - Integ_ReplicaStressTest::MarkChanging(replicas, 0.1); // picks 10% of replicas + DISABLED_ReplicaStressTest::MarkChanging(replicas, 0.1); // picks 10% of replicas Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 100, FRAME_TIME, 0.1); - TestProfiler::PrintProfilingTotal("GridMate"); - TestProfiler::PrintProfilingSelf("GridMate"); + /*TestProfiler::PrintProfilingTotal("GridMate"); + TestProfiler::PrintProfilingSelf("GridMate");*/ - Integ_ReplicaStressTest::MarkChanging(replicas, 0.5); // picks 50% of replicas + DISABLED_ReplicaStressTest::MarkChanging(replicas, 0.5); // picks 50% of replicas Wait(sessions, replicas, 20, FRAME_TIME); - TestProfiler::StartProfiling(); + //TestProfiler::StartProfiling(); TestReplicas(sessions, replicas, 100, FRAME_TIME, 0.5); - TestProfiler::PrintProfilingTotal("GridMate"); + /*TestProfiler::PrintProfilingTotal("GridMate"); TestProfiler::PrintProfilingSelf("GridMate"); - TestProfiler::StopProfiling(); + TestProfiler::StopProfiling();*/ } }; @@ -3666,7 +3665,7 @@ public: * expected |none |brst | capped |under cap |brst | capped | * */ -class Integ_ReplicaBandiwdthTest +class DISABLED_ReplicaBandiwdthTest : public UnitTest::GridMateMPTestFixture { public: @@ -3944,9 +3943,9 @@ GM_TEST_SUITE(ReplicaSuite) GM_TEST(InterpolatorTest) #if !defined(AZ_DEBUG_BUILD) // these tests are a little slow for debug -GM_TEST(Integ_ReplicaBandiwdthTest) -GM_TEST(Integ_ReplicaStressTest) -GM_TEST(Integ_ReplicaStableStressTest) +GM_TEST(DISABLED_ReplicaBandiwdthTest) +GM_TEST(DISABLED_ReplicaStressTest) +GM_TEST(DISABLED_ReplicaStableStressTest) #endif GM_TEST_SUITE_END() diff --git a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp index f6f88d2dff..86f9f4605b 100644 --- a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp @@ -457,13 +457,13 @@ namespace ReplicaBehavior { Completed, }; - class Integ_SimpleBehaviorTest + class SimpleBehaviorTest : public UnitTest::GridMateMPTestFixture { public: //GM_CLASS_ALLOCATOR(SimpleBehaviorTest); - Integ_SimpleBehaviorTest() + SimpleBehaviorTest() : m_sessionCount(0) { } virtual int GetNumSessions() { return 0; } @@ -654,11 +654,11 @@ namespace ReplicaBehavior { * * This is a simple sanity check to ensure the logic sends the update when it's necessary. */ - class Integ_Replica_DontSendDataSets_WithNoDiffFromCtorData - : public Integ_SimpleBehaviorTest + class Replica_DontSendDataSets_WithNoDiffFromCtorData + : public SimpleBehaviorTest { public: - Integ_Replica_DontSendDataSets_WithNoDiffFromCtorData() + Replica_DontSendDataSets_WithNoDiffFromCtorData() : m_replicaIdDefault(InvalidReplicaId), m_replicaIdModified(InvalidReplicaId) { } @@ -774,9 +774,9 @@ namespace ReplicaBehavior { FilteredHook m_driller; }; - TEST(Integ_Replica_DontSendDataSets_WithNoDiffFromCtorData, Integ_Replica_DontSendDataSets_WithNoDiffFromCtorData) + TEST(Replica_DontSendDataSets_WithNoDiffFromCtorData, DISABLED_Replica_DontSendDataSets_WithNoDiffFromCtorData) { - Integ_Replica_DontSendDataSets_WithNoDiffFromCtorData tester; + Replica_DontSendDataSets_WithNoDiffFromCtorData tester; tester.run(); } @@ -784,11 +784,11 @@ namespace ReplicaBehavior { * This test checks the actual size of the replica as marshalled in the binary payload. * The assessment of the payload size is done using driller EBus. */ - class Integ_ReplicaDefaultDataSetDriller - : public Integ_SimpleBehaviorTest + class ReplicaDefaultDataSetDriller + : public SimpleBehaviorTest { public: - Integ_ReplicaDefaultDataSetDriller() + ReplicaDefaultDataSetDriller() : m_replicaId(InvalidReplicaId) { } @@ -815,7 +815,7 @@ namespace ReplicaBehavior { m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_ReplicaDefaultDataSetDriller() override + ~ReplicaDefaultDataSetDriller() override { m_driller.BusDisconnect(); } @@ -880,11 +880,11 @@ namespace ReplicaBehavior { ReplicaId m_replicaId; }; - const int Integ_ReplicaDefaultDataSetDriller::NonDefaultValue; + const int ReplicaDefaultDataSetDriller::NonDefaultValue; - TEST(Integ_ReplicaDefaultDataSetDriller, Integ_ReplicaDefaultDataSetDriller) + TEST(ReplicaDefaultDataSetDriller, DISABLED_ReplicaDefaultDataSetDriller) { - Integ_ReplicaDefaultDataSetDriller tester; + ReplicaDefaultDataSetDriller tester; tester.run(); } @@ -892,11 +892,11 @@ namespace ReplicaBehavior { * This test checks the actual size of the replica as marshalled in the binary payload. * The assessment of the payload size is done using driller EBus. */ - class Integ_Replica_ComparePackingBoolsVsU8 - : public Integ_SimpleBehaviorTest + class Replica_ComparePackingBoolsVsU8 + : public SimpleBehaviorTest { public: - Integ_Replica_ComparePackingBoolsVsU8() + Replica_ComparePackingBoolsVsU8() : m_replicaBoolsId(InvalidReplicaId) , m_replicaU8Id(InvalidReplicaId) { @@ -928,7 +928,7 @@ namespace ReplicaBehavior { m_replicaU8Id = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica2); } - ~Integ_Replica_ComparePackingBoolsVsU8() override + ~Replica_ComparePackingBoolsVsU8() override { m_driller.BusDisconnect(); } @@ -1020,17 +1020,17 @@ namespace ReplicaBehavior { ReplicaId m_replicaU8Id; }; - TEST(Integ_Replica_ComparePackingBoolsVsU8, Integ_Replica_ComparePackingBoolsVsU8) + TEST(Replica_ComparePackingBoolsVsU8, DISABLED_Replica_ComparePackingBoolsVsU8) { - Integ_Replica_ComparePackingBoolsVsU8 tester; + Replica_ComparePackingBoolsVsU8 tester; tester.run(); } - class Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary - : public Integ_SimpleBehaviorTest + class CheckDataSetStreamIsntWrittenMoreThanNecessary + : public SimpleBehaviorTest { public: - Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary() + CheckDataSetStreamIsntWrittenMoreThanNecessary() : m_replicaId(InvalidReplicaId) { } @@ -1057,7 +1057,7 @@ namespace ReplicaBehavior { m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary() override + ~CheckDataSetStreamIsntWrittenMoreThanNecessary() override { m_driller.BusDisconnect(); } @@ -1117,17 +1117,17 @@ namespace ReplicaBehavior { ReplicaId m_replicaId; }; - TEST(Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary, Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary) + TEST(CheckDataSetStreamIsntWrittenMoreThanNecessary, DISABLED_CheckDataSetStreamIsntWrittenMoreThanNecessary) { - Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary tester; + CheckDataSetStreamIsntWrittenMoreThanNecessary tester; tester.run(); } - class Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty - : public Integ_SimpleBehaviorTest + class CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty + : public SimpleBehaviorTest { public: - Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() + CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() : m_replicaId(InvalidReplicaId) { } @@ -1154,7 +1154,7 @@ namespace ReplicaBehavior { m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() override + ~CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() override { m_driller.BusDisconnect(); } @@ -1213,17 +1213,17 @@ namespace ReplicaBehavior { ReplicaId m_replicaId; }; - TEST(Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty, Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty) + TEST(CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty, DISABLED_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty) { - Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty tester; + CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty tester; tester.run(); } - class Integ_CheckReplicaIsntSentWithNoChanges - : public Integ_SimpleBehaviorTest + class CheckReplicaIsntSentWithNoChanges + : public SimpleBehaviorTest { public: - Integ_CheckReplicaIsntSentWithNoChanges() + CheckReplicaIsntSentWithNoChanges() : m_replicaId(InvalidReplicaId) { } @@ -1248,7 +1248,7 @@ namespace ReplicaBehavior { m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_CheckReplicaIsntSentWithNoChanges() override + ~CheckReplicaIsntSentWithNoChanges() override { m_driller.BusDisconnect(); } @@ -1323,17 +1323,17 @@ namespace ReplicaBehavior { ReplicaId m_replicaId; }; - TEST(Integ_CheckReplicaIsntSentWithNoChanges, Integ_CheckReplicaIsntSentWithNoChanges) + TEST(CheckReplicaIsntSentWithNoChanges, DISABLED_CheckReplicaIsntSentWithNoChanges) { - Integ_CheckReplicaIsntSentWithNoChanges tester; + CheckReplicaIsntSentWithNoChanges tester; tester.run(); } - class Integ_CheckEntityScriptReplicaIsntSentWithNoChanges - : public Integ_SimpleBehaviorTest + class CheckEntityScriptReplicaIsntSentWithNoChanges + : public SimpleBehaviorTest { public: - Integ_CheckEntityScriptReplicaIsntSentWithNoChanges() + CheckEntityScriptReplicaIsntSentWithNoChanges() : m_replicaId(InvalidReplicaId) { } @@ -1359,7 +1359,7 @@ namespace ReplicaBehavior { m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_CheckEntityScriptReplicaIsntSentWithNoChanges() override + ~CheckEntityScriptReplicaIsntSentWithNoChanges() override { m_driller.BusDisconnect(); } @@ -1410,9 +1410,9 @@ namespace ReplicaBehavior { ReplicaId m_replicaId; }; - TEST(Integ_CheckEntityScriptReplicaIsntSentWithNoChanges, Integ_CheckEntityScriptReplicaIsntSentWithNoChanges) + TEST(CheckEntityScriptReplicaIsntSentWithNoChanges, DISABLED_CheckEntityScriptReplicaIsntSentWithNoChanges) { - Integ_CheckEntityScriptReplicaIsntSentWithNoChanges tester; + CheckEntityScriptReplicaIsntSentWithNoChanges tester; tester.run(); } diff --git a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp index 61fe9d65b2..2e8d2a3a73 100644 --- a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp @@ -596,12 +596,12 @@ public: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -class MPSession +class MPSessionMedium : public CarrierEventBus::Handler { public: - ~MPSession() override + ~MPSessionMedium() override { CarrierEventBus::Handler::BusDisconnect(); } @@ -708,14 +708,14 @@ enum class TestStatus Completed, }; -class Integ_SimpleTest +class SimpleTest : public UnitTest::GridMateMPTestFixture , public ::testing::Test { public: - //GM_CLASS_ALLOCATOR(Integ_SimpleTest); + //GM_CLASS_ALLOCATOR(SimpleTest); - Integ_SimpleTest() + SimpleTest() : m_sessionCount(0) { } virtual int GetNumSessions() { return 0; } @@ -858,15 +858,15 @@ public: } int m_sessionCount; - AZStd::array m_sessions; + AZStd::array m_sessions; AZStd::unique_ptr m_defaultSimulator; }; -class Integ_ReplicaChunkRPCExec - : public Integ_SimpleTest +class ReplicaChunkRPCExec + : public SimpleTest { public: - Integ_ReplicaChunkRPCExec() + ReplicaChunkRPCExec() : m_chunk(nullptr) , m_replicaId(0) { } @@ -893,7 +893,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaChunkRPCExec, ReplicaChunkRPCExec) +TEST_F(ReplicaChunkRPCExec, DISABLED_ReplicaChunkRPCExec) { RunTickLoop([this](int tick) -> TestStatus { @@ -1050,8 +1050,8 @@ int DestroyRPCChunk::s_afterDestroyFromPrimaryCalls = 0; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -class Integ_ReplicaDestroyedInRPC - : public Integ_SimpleTest +class ReplicaDestroyedInRPC + : public SimpleTest { public: enum @@ -1080,7 +1080,7 @@ public: ReplicaId m_repId[2]; }; -TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) +TEST_F(ReplicaDestroyedInRPC, DISABLED_ReplicaDestroyedInRPC) { RunTickLoop([this](int tick)->TestStatus { @@ -1129,11 +1129,11 @@ TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) }); } -class Integ_ReplicaChunkAddWhileReplicated - : public Integ_SimpleTest +class ReplicaChunkAddWhileReplicated + : public SimpleTest { public: - Integ_ReplicaChunkAddWhileReplicated() + ReplicaChunkAddWhileReplicated() : m_replica(nullptr) , m_chunk(nullptr) , m_replicaId(0) @@ -1161,7 +1161,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaChunkAddWhileReplicated, ReplicaChunkAddWhileReplicated) +TEST_F(ReplicaChunkAddWhileReplicated, DISABLED_ReplicaChunkAddWhileReplicated) { RunTickLoop([this](int tick)-> TestStatus { @@ -1203,11 +1203,11 @@ TEST_F(Integ_ReplicaChunkAddWhileReplicated, ReplicaChunkAddWhileReplicated) } -class Integ_ReplicaRPCValues - : public Integ_SimpleTest +class ReplicaRPCValues + : public SimpleTest { public: - Integ_ReplicaRPCValues() + ReplicaRPCValues() : m_replica(nullptr) , m_chunk(nullptr) , m_replicaId(0) @@ -1236,7 +1236,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaRPCValues, ReplicaRPCValues) +TEST_F(ReplicaRPCValues, DISABLED_ReplicaRPCValues) { RunTickLoop([this](int tick)-> TestStatus { @@ -1257,11 +1257,11 @@ TEST_F(Integ_ReplicaRPCValues, ReplicaRPCValues) }); } -class Integ_FullRPCValues - : public Integ_SimpleTest +class FullRPCValues + : public SimpleTest { public: - Integ_FullRPCValues() + FullRPCValues() : m_replica(nullptr) , m_chunk(nullptr) , m_replicaId(0) @@ -1290,7 +1290,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_FullRPCValues, FullRPCValues) +TEST_F(FullRPCValues, DISABLED_FullRPCValues) { RunTickLoop([this](int tick)-> TestStatus { @@ -1364,11 +1364,11 @@ TEST_F(Integ_FullRPCValues, FullRPCValues) } -class Integ_ReplicaRemoveProxy - : public Integ_SimpleTest +class ReplicaRemoveProxy + : public SimpleTest { public: - Integ_ReplicaRemoveProxy() + ReplicaRemoveProxy() : m_replica(nullptr) , m_replicaId(0) { @@ -1395,7 +1395,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaRemoveProxy, ReplicaRemoveProxy) +TEST_F(ReplicaRemoveProxy, DISABLED_ReplicaRemoveProxy) { RunTickLoop([this](int tick)-> TestStatus { @@ -1424,11 +1424,11 @@ TEST_F(Integ_ReplicaRemoveProxy, ReplicaRemoveProxy) } -class Integ_ReplicaChunkEvents - : public Integ_SimpleTest +class ReplicaChunkEvents + : public SimpleTest { public: - Integ_ReplicaChunkEvents() + ReplicaChunkEvents() : m_replicaId(InvalidReplicaId) , m_chunk(nullptr) , m_proxyChunk(nullptr) @@ -1463,7 +1463,7 @@ public: AllEventChunk::Ptr m_proxyChunk; }; -TEST_F(Integ_ReplicaChunkEvents, ReplicaChunkEvents) +TEST_F(ReplicaChunkEvents, DISABLED_ReplicaChunkEvents) { RunTickLoop([this](int tick)-> TestStatus { @@ -1501,11 +1501,11 @@ TEST_F(Integ_ReplicaChunkEvents, ReplicaChunkEvents) } -class Integ_ReplicaChunksBeyond32 - : public Integ_SimpleTest +class ReplicaChunksBeyond32 + : public SimpleTest { public: - Integ_ReplicaChunksBeyond32() + ReplicaChunksBeyond32() : m_replicaId(InvalidReplicaId) { } @@ -1537,7 +1537,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaChunksBeyond32, ReplicaChunksBeyond32) +TEST_F(ReplicaChunksBeyond32, DISABLED_ReplicaChunksBeyond32) { RunTickLoop([this](int tick)-> TestStatus { @@ -1565,11 +1565,11 @@ TEST_F(Integ_ReplicaChunksBeyond32, ReplicaChunksBeyond32) } -class Integ_ReplicaChunkEventsDeactivate - : public Integ_SimpleTest +class ReplicaChunkEventsDeactivate + : public SimpleTest { public: - Integ_ReplicaChunkEventsDeactivate() + ReplicaChunkEventsDeactivate() : m_replica(nullptr) , m_replicaId(0) , m_chunk(nullptr) @@ -1604,7 +1604,7 @@ public: AllEventChunk::Ptr m_proxyChunk; }; -TEST_F(Integ_ReplicaChunkEventsDeactivate, ReplicaChunkEventsDeactivate) +TEST_F(ReplicaChunkEventsDeactivate, DISABLED_ReplicaChunkEventsDeactivate) { RunTickLoop([this](int tick)-> TestStatus { @@ -1649,11 +1649,11 @@ TEST_F(Integ_ReplicaChunkEventsDeactivate, ReplicaChunkEventsDeactivate) } -class Integ_ReplicaDriller - : public Integ_SimpleTest +class ReplicaDriller + : public SimpleTest { public: - Integ_ReplicaDriller() + ReplicaDriller() : m_replicaId(InvalidReplicaId) { } @@ -2007,7 +2007,7 @@ public: m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } - ~Integ_ReplicaDriller() override + ~ReplicaDriller() override { m_driller.BusDisconnect(); } @@ -2016,7 +2016,7 @@ public: ReplicaId m_replicaId; }; -TEST_F(Integ_ReplicaDriller, ReplicaDriller) +TEST_F(ReplicaDriller, DISABLED_ReplicaDriller) { RunTickLoop([this](int tick)-> TestStatus { @@ -2082,11 +2082,11 @@ TEST_F(Integ_ReplicaDriller, ReplicaDriller) } -class Integ_DataSetChangedTest - : public Integ_SimpleTest +class DataSetChangedTest + : public SimpleTest { public: - Integ_DataSetChangedTest() + DataSetChangedTest() : m_replica(nullptr) , m_replicaId(0) , m_chunk(nullptr) @@ -2115,7 +2115,7 @@ public: DataSetChunk::Ptr m_chunk; }; -TEST_F(Integ_DataSetChangedTest, DataSetChangedTest) +TEST_F(DataSetChangedTest, DISABLED_DataSetChangedTest) { RunTickLoop([this](int tick)-> TestStatus { @@ -2144,11 +2144,11 @@ TEST_F(Integ_DataSetChangedTest, DataSetChangedTest) } -class Integ_CustomHandlerTest - : public Integ_SimpleTest +class CustomHandlerTest + : public SimpleTest { public: - Integ_CustomHandlerTest() + CustomHandlerTest() : m_replica(nullptr) , m_replicaId(0) , m_chunk(nullptr) @@ -2181,7 +2181,7 @@ public: AZStd::scoped_ptr m_proxyHandler; }; -TEST_F(Integ_CustomHandlerTest, CustomHandlerTest) +TEST_F(CustomHandlerTest, DISABLED_CustomHandlerTest) { RunTickLoop([this](int tick)-> TestStatus { @@ -2234,11 +2234,11 @@ TEST_F(Integ_CustomHandlerTest, CustomHandlerTest) } -class Integ_NonConstMarshalerTest - : public Integ_SimpleTest +class NonConstMarshalerTest + : public SimpleTest { public: - Integ_NonConstMarshalerTest() + NonConstMarshalerTest() : m_replica(nullptr) , m_replicaId(0) , m_chunk(nullptr) @@ -2266,7 +2266,7 @@ public: NonConstMarshalerChunk::Ptr m_chunk; }; -TEST_F(Integ_NonConstMarshalerTest, NonConstMarshalerTest) +TEST_F(NonConstMarshalerTest, DISABLED_NonConstMarshalerTest) { RunTickLoop([this](int tick)-> TestStatus { @@ -2309,11 +2309,11 @@ TEST_F(Integ_NonConstMarshalerTest, NonConstMarshalerTest) } -class Integ_SourcePeerTest - : public Integ_SimpleTest +class SourcePeerTest + : public SimpleTest { public: - Integ_SourcePeerTest() + SourcePeerTest() : m_replica(nullptr) , m_replicaId(0) , m_chunk(nullptr) @@ -2343,7 +2343,7 @@ public: SourcePeerChunk::Ptr m_chunk2; }; -TEST_F(Integ_SourcePeerTest, SourcePeerTest) +TEST_F(SourcePeerTest, DISABLED_SourcePeerTest) { RunTickLoop([this](int tick)-> TestStatus { @@ -2404,8 +2404,8 @@ TEST_F(Integ_SourcePeerTest, SourcePeerTest) } -class Integ_SendWithPriority - : public Integ_SimpleTest +class SendWithPriority + : public SimpleTest { public: enum @@ -2438,8 +2438,8 @@ public: { public: ReplicaDrillerHook() - : m_expectedSendValue(Integ_SendWithPriority::kNumReplicas) - , m_expectedRecvValue(Integ_SendWithPriority::kNumReplicas) + : m_expectedSendValue(SendWithPriority::kNumReplicas) + , m_expectedRecvValue(SendWithPriority::kNumReplicas) { } @@ -2495,7 +2495,7 @@ public: PriorityChunk::Ptr m_chunks[kNumReplicas]; }; -TEST_F(Integ_SendWithPriority, SendWithPriority) +TEST_F(SendWithPriority, DISABLED_SendWithPriority) { RunTickLoop([this](int tick)-> TestStatus { @@ -2511,8 +2511,8 @@ TEST_F(Integ_SendWithPriority, SendWithPriority) } -class Integ_SuspendUpdatesTest - : public Integ_SimpleTest +class SuspendUpdatesTest + : public SimpleTest { public: enum @@ -2597,7 +2597,7 @@ public: unsigned int m_numRpcCalled = 0; }; -TEST_F(Integ_SuspendUpdatesTest, SuspendUpdatesTest) +TEST_F(SuspendUpdatesTest, DISABLED_SuspendUpdatesTest) { RunTickLoop([this](int tick)-> TestStatus { @@ -2657,7 +2657,7 @@ TEST_F(Integ_SuspendUpdatesTest, SuspendUpdatesTest) } -class Integ_BasicHostChunkDescriptorTest +class BasicHostChunkDescriptorTest : public UnitTest::GridMateMPTestFixture , public ::testing::Test { @@ -2694,17 +2694,17 @@ public: static int nProxyActivations; }; }; -int Integ_BasicHostChunkDescriptorTest::HostChunk::nPrimaryActivations = 0; -int Integ_BasicHostChunkDescriptorTest::HostChunk::nProxyActivations = 0; +int BasicHostChunkDescriptorTest::HostChunk::nPrimaryActivations = 0; +int BasicHostChunkDescriptorTest::HostChunk::nProxyActivations = 0; -TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) +TEST_F(BasicHostChunkDescriptorTest, DISABLED_BasicHostChunkDescriptorTest) { AZ_TracePrintf("GridMate", "\n"); // Register test chunks ReplicaChunkDescriptorTable::Get().RegisterChunkType>(); - MPSession nodes[nNodes]; + MPSessionMedium nodes[nNodes]; // initialize transport int basePort = 4427; @@ -2791,8 +2791,8 @@ TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) * Create and immedietly destroy primary replica * Test that it does not result in any network sync */ -class Integ_CreateDestroyPrimary - : public Integ_SimpleTest +class CreateDestroyPrimary + : public SimpleTest , public Debug::ReplicaDrillerBus::Handler { public: @@ -2827,7 +2827,7 @@ public: } }; -TEST_F(Integ_CreateDestroyPrimary, CreateDestroyPrimary) +TEST_F(CreateDestroyPrimary, DISABLED_CreateDestroyPrimary) { RunTickLoop([this](int tick)-> TestStatus { @@ -2861,7 +2861,7 @@ TEST_F(Integ_CreateDestroyPrimary, CreateDestroyPrimary) * The ReplicaTarget will prevent sending more updates. */ class ReplicaACKfeedbackTestFixture - : public Integ_SimpleTest + : public SimpleTest { public: ReplicaACKfeedbackTestFixture() @@ -2900,7 +2900,7 @@ public: size_t m_replicaBytesSentPrev = 0; ReplicaId m_replicaId; - Integ_ReplicaDriller::ReplicaDrillerHook m_driller; + ReplicaDriller::ReplicaDrillerHook m_driller; }; TEST_F(ReplicaACKfeedbackTestFixture, ReplicaACKfeedbackTest) diff --git a/Code/Framework/GridMate/Tests/Session.cpp b/Code/Framework/GridMate/Tests/Session.cpp index d4f56871c5..c793c3d450 100644 --- a/Code/Framework/GridMate/Tests/Session.cpp +++ b/Code/Framework/GridMate/Tests/Session.cpp @@ -40,7 +40,7 @@ namespace UnitTest } } - class Integ_LANSessionMatchmakingParamsTest + class DISABLED_LANSessionMatchmakingParamsTest : public GridMateMPTestFixture , public SessionEventBus::MultiHandler { @@ -52,7 +52,7 @@ namespace UnitTest } public: - Integ_LANSessionMatchmakingParamsTest(bool useIPv6 = false) + DISABLED_LANSessionMatchmakingParamsTest(bool useIPv6 = false) : m_hostSession(nullptr) , m_clientGridMate(nullptr) { @@ -71,7 +71,7 @@ namespace UnitTest AZ_TEST_ASSERT(GridMate::LANSessionServiceBus::FindFirstHandler(m_clientGridMate) != nullptr); ////////////////////////////////////////////////////////////////////////// } - ~Integ_LANSessionMatchmakingParamsTest() override + ~DISABLED_LANSessionMatchmakingParamsTest() override { SessionEventBus::MultiHandler::BusDisconnect(m_gridMate); SessionEventBus::MultiHandler::BusDisconnect(m_clientGridMate); @@ -192,7 +192,7 @@ namespace UnitTest IGridMate* m_clientGridMate; }; - class Integ_LANSessionTest + class DISABLED_LANSessionTest : public GridMateMPTestFixture { class TestPeerInfo @@ -264,7 +264,7 @@ namespace UnitTest }; public: - Integ_LANSessionTest(bool useIPv6 = false) + DISABLED_LANSessionTest(bool useIPv6 = false) { m_driverType = useIPv6 ? Driver::BSD_AF_INET6 : Driver::BSD_AF_INET; m_doSessionParamsTest = k_numMachines > 1; @@ -290,7 +290,7 @@ namespace UnitTest AZ_TEST_ASSERT(LANSessionServiceBus::FindFirstHandler(m_peers[i].m_gridMate) != nullptr); } } - ~Integ_LANSessionTest() override + ~DISABLED_LANSessionTest() override { StopGridMateService(m_peers[0].m_gridMate); @@ -555,15 +555,15 @@ namespace UnitTest bool m_doSessionParamsTest; }; - class Integ_LANSessionTestIPv6 - : public Integ_LANSessionTest + class DISABLED_LANSessionTestIPv6 + : public DISABLED_LANSessionTest { public: - Integ_LANSessionTestIPv6() - : Integ_LANSessionTest(true) {} + DISABLED_LANSessionTestIPv6() + : DISABLED_LANSessionTest(true) {} }; - class Integ_LANMultipleSessionTest + class DISABLED_LANMultipleSessionTest : public GridMateMPTestFixture , public SessionEventBus::Handler { @@ -620,7 +620,7 @@ namespace UnitTest m_sessions[i] = nullptr; } - Integ_LANMultipleSessionTest() + DISABLED_LANMultipleSessionTest() : GridMateMPTestFixture(200 * 1024 * 1024) { ////////////////////////////////////////////////////////////////////////// @@ -645,7 +645,7 @@ namespace UnitTest } } - ~Integ_LANMultipleSessionTest() override + ~DISABLED_LANMultipleSessionTest() override { GridMate::StopGridMateService(m_gridMates[0]); @@ -799,7 +799,7 @@ namespace UnitTest * Testing session with low latency. This is special mode usually used by tools and communication channels * where we try to response instantly on messages. */ - class Integ_LANLatencySessionTest + class DISABLED_LANLatencySessionTest : public GridMateMPTestFixture , public SessionEventBus::Handler { @@ -857,7 +857,7 @@ namespace UnitTest m_sessions[i] = nullptr; } - Integ_LANLatencySessionTest() + DISABLED_LANLatencySessionTest() #ifdef AZ_TEST_LANLATENCY_ENABLE_MONSTER_BUFFER : GridMateMPTestFixture(50 * 1024 * 1024) #endif @@ -884,7 +884,7 @@ namespace UnitTest } } - ~Integ_LANLatencySessionTest() override + ~DISABLED_LANLatencySessionTest() override { StopGridMateService(m_gridMates[0]); @@ -1162,7 +1162,7 @@ namespace UnitTest * 5. After host migration we drop the new host again. (after migration we have 3 members). * Session should be fully operational at the end with 3 members left. */ - class Integ_LANSessionMigarationTestTest + class LANSessionMigarationTestTest : public SessionEventBus::Handler , public GridMateMPTestFixture { @@ -1257,7 +1257,7 @@ namespace UnitTest } } - Integ_LANSessionMigarationTestTest() + LANSessionMigarationTestTest() { ////////////////////////////////////////////////////////////////////////// // Create all grid mates @@ -1283,7 +1283,7 @@ namespace UnitTest //StartDrilling("lanmigration"); } - ~Integ_LANSessionMigarationTestTest() override + ~LANSessionMigarationTestTest() override { StopGridMateService(m_gridMates[0]); @@ -1476,7 +1476,7 @@ namespace UnitTest * 5. We join a 2 new members to the session. * Session should be fully operational at the end with 4 members in it. */ - class Integ_LANSessionMigarationTestTest2 + class LANSessionMigarationTestTest2 : public SessionEventBus::Handler , public GridMateMPTestFixture { @@ -1571,7 +1571,7 @@ namespace UnitTest } } } - Integ_LANSessionMigarationTestTest2() + LANSessionMigarationTestTest2() { ////////////////////////////////////////////////////////////////////////// // Create all grid mates @@ -1597,7 +1597,7 @@ namespace UnitTest //StartDrilling("lanmigration2"); } - ~Integ_LANSessionMigarationTestTest2() override + ~LANSessionMigarationTestTest2() override { StopGridMateService(m_gridMates[0]); @@ -1816,7 +1816,7 @@ namespace UnitTest * 3. Add 2 new joins to the original session. * Original session should remain fully operational with 4 members in it. */ - class Integ_LANSessionMigarationTestTest3 + class LANSessionMigarationTestTest3 : public SessionEventBus::Handler , public GridMateMPTestFixture { @@ -1910,7 +1910,7 @@ namespace UnitTest } } } - Integ_LANSessionMigarationTestTest3() + LANSessionMigarationTestTest3() { ////////////////////////////////////////////////////////////////////////// // Create all grid mates @@ -1936,7 +1936,7 @@ namespace UnitTest //StartDrilling("lanmigration2"); } - ~Integ_LANSessionMigarationTestTest3() override + ~LANSessionMigarationTestTest3() override { StopGridMateService(m_gridMates[0]); @@ -2122,13 +2122,13 @@ namespace UnitTest } GM_TEST_SUITE(SessionSuite) -GM_TEST(Integ_LANSessionMatchmakingParamsTest) -GM_TEST(Integ_LANSessionTest) +GM_TEST(DISABLED_LANSessionMatchmakingParamsTest) +GM_TEST(DISABLED_LANSessionTest) #if (AZ_TRAIT_GRIDMATE_TEST_SOCKET_IPV6_SUPPORT_ENABLED) -GM_TEST(Integ_LANSessionTestIPv6) +GM_TEST(DISABLED_LANSessionTestIPv6) #endif -GM_TEST(Integ_LANMultipleSessionTest) -GM_TEST(Integ_LANLatencySessionTest) +GM_TEST(DISABLED_LANMultipleSessionTest) +GM_TEST(DISABLED_LANLatencySessionTest) // Manually enabled tests (require 2+ machines and online services) //GM_TEST(LANSessionMigarationTestTest) diff --git a/Code/Framework/GridMate/Tests/StreamSecureSocketDriverTests.cpp b/Code/Framework/GridMate/Tests/StreamSecureSocketDriverTests.cpp index a7e9a7ccda..1f05520457 100644 --- a/Code/Framework/GridMate/Tests/StreamSecureSocketDriverTests.cpp +++ b/Code/Framework/GridMate/Tests/StreamSecureSocketDriverTests.cpp @@ -110,7 +110,7 @@ namespace UnitTest std::array m_buffer; }; - class Integ_StreamSecureSocketDriverTestsBindSocketEmpty + class DISABLED_StreamSecureSocketDriverTestsBindSocketEmpty : public GridMateMPTestFixture { public: @@ -134,7 +134,7 @@ namespace UnitTest } }; - class Integ_StreamSecureSocketDriverTestsConnection + class DISABLED_StreamSecureSocketDriverTestsConnection : public GridMateMPTestFixture { public: @@ -146,7 +146,7 @@ namespace UnitTest } }; - class Integ_StreamSecureSocketDriverTestsConnectionAndHelloWorld + class DISABLED_StreamSecureSocketDriverTestsConnectionAndHelloWorld : public GridMateMPTestFixture { public: @@ -190,7 +190,7 @@ namespace UnitTest } }; - class Integ_StreamSecureSocketDriverTestsPingPong + class DISABLED_StreamSecureSocketDriverTestsPingPong : public GridMateMPTestFixture { public: @@ -425,13 +425,13 @@ namespace UnitTest void BuildStateMachine() { - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_TOP), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStateTop), AZ::HSM::InvalidStateId, TS_START); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_START), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStateStart), TS_TOP); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_SERVER_GET_PING), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStateServerGetPing), TS_TOP); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_PING_GET_SERVER), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStatePingGetServer), TS_TOP); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_SERVER_GET_PONG), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStateServerGetPong), TS_TOP); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_PONG_GET_SERVER), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStatePongGetServer), TS_TOP); - m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_IN_ERROR), AZ::HSM::StateHandler(this, &Integ_StreamSecureSocketDriverTestsPingPong::OnStateInError), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_TOP), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStateTop), AZ::HSM::InvalidStateId, TS_START); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_START), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStateStart), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_SERVER_GET_PING), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStateServerGetPing), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_PING_GET_SERVER), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStatePingGetServer), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_SERVER_GET_PONG), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStateServerGetPong), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_PONG_GET_SERVER), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStatePongGetServer), TS_TOP); + m_stateMachine.SetStateHandler(AZ_HSM_STATE_NAME(TS_IN_ERROR), AZ::HSM::StateHandler(this, &DISABLED_StreamSecureSocketDriverTestsPingPong::OnStateInError), TS_TOP); m_stateMachine.Start(); } @@ -486,10 +486,10 @@ namespace UnitTest } GM_TEST_SUITE(StreamSecureSocketDriverTests) - GM_TEST(Integ_StreamSecureSocketDriverTestsBindSocketEmpty); - GM_TEST(Integ_StreamSecureSocketDriverTestsConnection); - GM_TEST(Integ_StreamSecureSocketDriverTestsConnectionAndHelloWorld); - GM_TEST(Integ_StreamSecureSocketDriverTestsPingPong); + GM_TEST(DISABLED_StreamSecureSocketDriverTestsBindSocketEmpty); + GM_TEST(DISABLED_StreamSecureSocketDriverTestsConnection); + GM_TEST(DISABLED_StreamSecureSocketDriverTestsConnectionAndHelloWorld); + GM_TEST(DISABLED_StreamSecureSocketDriverTestsPingPong); GM_TEST_SUITE_END() #endif // AZ_TRAIT_GRIDMATE_ENABLE_OPENSSL diff --git a/Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp b/Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp index f9e9395fbf..9dd22bedc7 100644 --- a/Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp +++ b/Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp @@ -308,7 +308,7 @@ namespace UnitTest } }; - class Integ_StreamSocketDriverTestsTooManyConnections + class DISABLED_StreamSocketDriverTestsTooManyConnections : public GridMateMPTestFixture { public: @@ -529,7 +529,7 @@ GM_TEST_SUITE(StreamSocketDriverTests) GM_TEST(StreamSocketDriverTestsSimpleLockStepConnection); GM_TEST(StreamSocketDriverTestsEstablishConnectAndSend); GM_TEST(StreamSocketDriverTestsManyRandomPackets); - GM_TEST(Integ_StreamSocketDriverTestsTooManyConnections); + GM_TEST(DISABLED_StreamSocketDriverTestsTooManyConnections); GM_TEST(StreamSocketDriverTestsClientToInvalidServer); GM_TEST(StreamSocketDriverTestsManySends); diff --git a/Code/Framework/GridMate/Tests/TestProfiler.cpp b/Code/Framework/GridMate/Tests/TestProfiler.cpp deleted file mode 100644 index 26e9312ecf..0000000000 --- a/Code/Framework/GridMate/Tests/TestProfiler.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#include "Tests.h" -#include "TestProfiler.h" - -#include -#include - -#include -#include - -using namespace GridMate; - -typedef set ProfilerSet; - -static bool CollectPerformanceCounters(const AZ::Debug::ProfilerRegister& reg, const AZStd::thread_id&, ProfilerSet& profilers, const char* systemId) -{ - if (reg.m_type != AZ::Debug::ProfilerRegister::PRT_TIME) - { - return true; - } - if (reg.m_systemId != AZ::Crc32(systemId)) - { - return true; - } - - const AZ::Debug::ProfilerRegister* profReg = ® - profilers.insert(profReg); - return true; -} - -static AZStd::string FormatString(const AZStd::string& pre, const AZStd::string& name, const AZStd::string& post, AZ::u64 time, AZ::u64 calls) -{ - AZStd::string units = "us"; - if (AZ::u64 divtime = time / 1000) - { - time = divtime; - units = "ms"; - } - return AZStd::string::format("%s%s %s %10llu%s (%llu calls)\n", pre.c_str(), name.c_str(), post.c_str(), time, units.c_str(), calls); -} - -struct TotalSortContainer -{ - TotalSortContainer(const AZ::Debug::ProfilerRegister* self = nullptr) - { - m_self = self; - } - - void Print(AZ::s32 level, const char* systemId) - { - if (m_self && level >= 0) - { - AZStd::string levelIndent; - for (AZ::s32 i = 0; i < level; i++) - { - levelIndent += (i == level - 1) ? "+---" : "| "; - } - AZStd::string name = m_self->m_name ? m_self->m_name : m_self->m_function; - AZStd::string outputTotal = FormatString(levelIndent, name, " Total:", m_self->m_timeData.m_time, m_self->m_timeData.m_calls); - AZ_Printf(systemId, outputTotal.c_str()); - - if (m_self->m_timeData.m_childrenTime || m_self->m_timeData.m_childrenCalls) - { - AZStd::string childIndent = levelIndent; - for (auto i = name.begin(); i != name.end(); ++i) - { - childIndent += " "; - } - childIndent[level * 4] = '|'; - - AZStd::string outputChild = FormatString(childIndent, "", "Child:", m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_childrenCalls); - AZ_Printf(systemId, outputChild.c_str()); - - AZStd::string outputSelf = FormatString(childIndent, "", "Self :", m_self->m_timeData.m_time - m_self->m_timeData.m_childrenTime, m_self->m_timeData.m_calls); - AZ_Printf(systemId, outputSelf.c_str()); - } - } - - for (auto i = m_children.begin(); i != m_children.end(); ++i) - { - i->Print(level + 1, systemId); - } - } - - TotalSortContainer* Find(const AZ::Debug::ProfilerRegister* obj) - { - if (m_self == obj) - { - return this; - } - - for (TotalSortContainer& child : m_children) - { - TotalSortContainer* found = child.Find(obj); - if (found) - { - return found; - } - } - - return nullptr; - } - - struct TotalSorter - { - bool operator()(const TotalSortContainer& a, const TotalSortContainer& b) const - { - if (a.m_self->m_timeData.m_time == b.m_self->m_timeData.m_time) - { - return a.m_self > b.m_self; - } - return a.m_self->m_timeData.m_time > b.m_self->m_timeData.m_time; - } - }; - set m_children; - const AZ::Debug::ProfilerRegister* m_self; -}; - -void TestProfiler::StartProfiling() -{ - StopProfiling(); - - AZ::Debug::Profiler::Create(); -} - -void TestProfiler::StopProfiling() -{ - if (AZ::Debug::Profiler::IsReady()) - { - AZ::Debug::Profiler::Destroy(); - } -} - -void TestProfiler::PrintProfilingTotal(const char* systemId) -{ - if (!AZ::Debug::Profiler::IsReady()) - { - return; - } - - ProfilerSet profilers; - AZ::Debug::Profiler::Instance().ReadRegisterValues(AZStd::bind(&CollectPerformanceCounters, AZStd::placeholders::_1, AZStd::placeholders::_2, AZStd::ref(profilers), systemId)); - - // Validate we wont get stuck in an infinite loop - TotalSortContainer root; - for (auto i = profilers.begin(); i != profilers.end(); ) - { - const AZ::Debug::ProfilerRegister* profile = *i; - if (profile->m_timeData.m_lastParent) - { - auto parent = profilers.find(profile->m_timeData.m_lastParent); - if (parent == profilers.end()) - { - // Error, just ignore this entry - i = profilers.erase(i); - continue; - } - } - ++i; - } - - // Put all root nodes into the final list - for (auto i = profilers.begin(); i != profilers.end(); ) - { - const AZ::Debug::ProfilerRegister* profile = *i; - if (!profile->m_timeData.m_lastParent) - { - root.m_children.insert(profile); - i = profilers.erase(i); - } - else - { - ++i; - } - } - - // Put all non-root nodes into the final list - while (!profilers.empty()) - { - for (auto i = profilers.begin(); i != profilers.end(); ) - { - const AZ::Debug::ProfilerRegister* profile = *i; - TotalSortContainer* found = root.Find(profile->m_timeData.m_lastParent); - if (found) - { - found->m_children.insert(profile); - i = profilers.erase(i); - } - else - { - ++i; - } - } - } - - AZ_Printf(systemId, "Profiling timers by total execution time:\n"); - root.Print(-1, systemId); -} - -void TestProfiler::PrintProfilingSelf(const char* systemId) -{ - if (!AZ::Debug::Profiler::IsReady()) - { - return; - } - - ProfilerSet profilers; - AZ::Debug::Profiler::Instance().ReadRegisterValues(AZStd::bind(&CollectPerformanceCounters, AZStd::placeholders::_1, AZStd::placeholders::_2, AZStd::ref(profilers), systemId)); - - struct SelfSorter - { - bool operator()(const AZ::Debug::ProfilerRegister* a, const AZ::Debug::ProfilerRegister* b) const - { - auto aTime = a->m_timeData.m_time - a->m_timeData.m_childrenTime; - auto bTime = b->m_timeData.m_time - b->m_timeData.m_childrenTime; - - if (aTime == bTime) - { - return a > b; - } - return aTime > bTime; - } - }; - - set selfSorted; - for (auto& profiler : profilers) - { - selfSorted.insert(profiler); - } - - AZ_Printf(systemId, "Profiling timers by exclusive execution time:\n"); - for (auto profiler : selfSorted) - { - AZStd::string str = FormatString("", profiler->m_name ? profiler->m_name : profiler->m_function, "Self Time:", - profiler->m_timeData.m_time - profiler->m_timeData.m_childrenTime, profiler->m_timeData.m_calls); - AZ_Printf(systemId, str.c_str()); - } -} diff --git a/Code/Framework/GridMate/Tests/TestProfiler.h b/Code/Framework/GridMate/Tests/TestProfiler.h deleted file mode 100644 index 816c001645..0000000000 --- a/Code/Framework/GridMate/Tests/TestProfiler.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#ifndef GM_TEST_PROFILER_H -#define GM_TEST_PROFILER_H - -namespace GridMate -{ - class TestProfiler - { - public: - static void StartProfiling(); - static void StopProfiling(); - - static void PrintProfilingTotal(const char* systemId); - static void PrintProfilingSelf(const char* systemId); - }; -} - -#endif diff --git a/Code/Framework/GridMate/Tests/gridmate_test_files.cmake b/Code/Framework/GridMate/Tests/gridmate_test_files.cmake index 3ff67f8eda..cf1cd087ee 100644 --- a/Code/Framework/GridMate/Tests/gridmate_test_files.cmake +++ b/Code/Framework/GridMate/Tests/gridmate_test_files.cmake @@ -12,6 +12,7 @@ set(FILES Session.cpp Serialize.cpp Certificates.cpp + Replica.cpp ReplicaSmall.cpp ReplicaMedium.cpp ReplicaBehavior.cpp diff --git a/Code/Tools/AzTestRunner/src/main.cpp b/Code/Tools/AzTestRunner/src/main.cpp index 0874efeff2..346b4e3b53 100644 --- a/Code/Tools/AzTestRunner/src/main.cpp +++ b/Code/Tools/AzTestRunner/src/main.cpp @@ -18,45 +18,35 @@ namespace AzTestRunner const int LIB_NOT_FOUND = 102; const int SYMBOL_NOT_FOUND = 103; - // note that MODULE_SKIPPED is not an error condition, but not 0 to indicate its not the - // same as successfully running tests and finding them. - const int MODULE_SKIPPED = 104; - const char* INTEG_BOOTSTRAP = "AzTestIntegBootstrap"; - //! display proper usage of the application void usage([[maybe_unused]] AZ::Test::Platform& platform) { std::stringstream ss; ss << "AzTestRunner\n" - "Runs AZ unit and integration tests. Exit code is the result from GoogleTest.\n" + "Runs AZ tests. Exit code is the result from GoogleTest.\n" "\n" "Usage:\n" - " AzTestRunner.exe (AzRunUnitTests|AzRunIntegTests) [--integ] [--wait-for-debugger] [--pause-on-completion] [google-test-args]\n" + " AzTestRunner.exe (AzRunUnitTests|AzRunBenchmarks) [--wait-for-debugger] [--pause-on-completion] [google-test-args]\n" "\n" "Options:\n" " : the module to test\n" " : the name of the aztest hook function to run in the \n" " 'AzRunUnitTests' will hook into unit tests\n" - " 'AzRunIntegTests' will hook into integration tests\n" - " --integ: tells runner to bootstrap the engine, needed for integration tests\n" - " Note: you can run unit tests with a bootstrapped engine (AzRunUnitTests --integ),\n" - " but running integration tests without a bootstrapped engine (AzRunIntegTests w/ no --integ) might not work.\n" + " 'AzRunBenchmarks' will hook into benchmark tests\n" " --wait-for-debugger: tells runner to wait for debugger to attach to process (on supported platforms)\n" " --pause-on-completion: tells the runner to pause after running the tests\n" " --quiet: disables stdout for minimal output while running tests\n" "\n" "Example:\n" - " AzTestRunner.exe CrySystem.dll AzRunUnitTests --pause-on-completion\n" - " AzTestRunner.exe CrySystem.dll AzRunIntegTests --integ\n" + " AzTestRunner.exe AzCore.Tests.dll AzRunUnitTests --pause-on-completion\n" "\n" "Exit Codes:\n" " 0 - all tests pass\n" " 1 - test failure\n" << " " << INCORRECT_USAGE << " - incorrect usage (see above)\n" << " " << LIB_NOT_FOUND << " - library/dll could not be loaded\n" - << " " << SYMBOL_NOT_FOUND << " - export symbol not found\n" - << " " << MODULE_SKIPPED << " - non-integ module was skipped (not an error)\n"; + << " " << SYMBOL_NOT_FOUND << " - export symbol not found\n"; std::cerr << ss.str() << std::endl; } @@ -82,7 +72,6 @@ namespace AzTestRunner // capture optional arguments bool waitForDebugger = false; - bool isInteg = false; bool pauseOnCompletion = false; bool quiet = false; for (int i = 0; i < argc; i++) @@ -93,12 +82,6 @@ namespace AzTestRunner AZ::Test::RemoveParameters(argc, argv, i, i); i--; } - else if (strcmp(argv[i], "--integ") == 0) - { - isInteg = true; - AZ::Test::RemoveParameters(argc, argv, i, i); - i--; - } else if (strcmp(argv[i], "--pause-on-completion") == 0) { pauseOnCompletion = true; @@ -172,47 +155,11 @@ namespace AzTestRunner if (result != 0) { module.reset(); - - if ((isInteg) && (result == SYMBOL_NOT_FOUND)) - { - // special case: It is not required to put an INTEG test inside every DLL - so if - // we failed to find the INTEG entry point in this DLL, its not an error. - // its only an error if we find it and there are no tests, or we find it and tests actually - // fail. - std::cerr << "INTEG module has no entry point and will be skipped: " << lib << std::endl; - return MODULE_SKIPPED; - } - return result; } platform.SuppressPopupWindows(); - // Grab a bootstrapper library if requested - std::shared_ptr bootstrap; - if (isInteg) - { - bootstrap = platform.GetModule(INTEG_BOOTSTRAP); - if (!bootstrap->IsValid()) - { - std::cerr << "FAILED to load bootstrapper" << std::endl; - return LIB_NOT_FOUND; - } - - // Initialize the bootstrapper - auto init = bootstrap->GetFunction("Initialize"); - if (init->IsValid()) - { - int initResult = (*init)(); - if (initResult != 0) - { - std::cerr << "Bootstrapper Initialize failed with code " << initResult << ", exiting" << std::endl; - return initResult; - } - } - } - - // run the test main function. if (testMainFunction->IsValid()) { @@ -231,22 +178,6 @@ namespace AzTestRunner // system allocator / etc. module.reset(); - // Shutdown the bootstrapper - if (bootstrap) - { - auto shutdown = bootstrap->GetFunction("Shutdown"); - if (shutdown->IsValid()) - { - int shutdownResult = (*shutdown)(); - if (shutdownResult != 0) - { - std::cerr << "Bootstrapper shutdown failed with code " << shutdownResult << ", exiting" << std::endl; - return shutdownResult; - } - } - bootstrap.reset(); - } - if (pauseOnCompletion) { AzTestRunner::pause_on_completion(); diff --git a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h index d354153f9b..0006b79628 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h +++ b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h @@ -27,7 +27,7 @@ namespace EMotionFX {} }; - class INTEG_PoseComparisonFixture + class PoseComparisonFixture : public SystemComponentFixture , public ::testing::WithParamInterface { @@ -47,8 +47,8 @@ namespace EMotionFX // This fixture exists to separate the tests that test the pose comparsion // functionality from the tests that use the pose comparison functionality // (even though it doesn't use the recording) - class INTEG_TestPoseComparisonFixture - : public INTEG_PoseComparisonFixture + class TestPoseComparisonFixture + : public PoseComparisonFixture { }; }; // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp index 27692a90ff..c704a5b114 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp @@ -154,14 +154,14 @@ namespace EMotionFX return MakeMatcher(new KeyTrackMatcher(expected, nodeName)); } - void INTEG_PoseComparisonFixture::SetUp() + void PoseComparisonFixture::SetUp() { SystemComponentFixture::SetUp(); LoadAssets(); } - void INTEG_PoseComparisonFixture::TearDown() + void PoseComparisonFixture::TearDown() { m_actorInstance->Destroy(); @@ -176,7 +176,7 @@ namespace EMotionFX SystemComponentFixture::TearDown(); } - void INTEG_PoseComparisonFixture::LoadAssets() + void PoseComparisonFixture::LoadAssets() { const AZStd::string actorPath = ResolvePath(GetParam().m_actorFile); m_actor = EMotionFX::GetImporter().LoadActor(actorPath); @@ -195,7 +195,7 @@ namespace EMotionFX m_actorInstance->SetAnimGraphInstance(AnimGraphInstance::Create(m_animGraph, m_actorInstance, m_motionSet)); } - TEST_P(INTEG_PoseComparisonFixture, Integ_TestPoses) + TEST_P(PoseComparisonFixture, TestPoses) { const AZStd::string recordingPath = ResolvePath(GetParam().m_recordingFile); Recorder* recording = EMotionFX::Recorder::LoadFromFile(recordingPath.c_str()); @@ -231,7 +231,7 @@ namespace EMotionFX recording->Destroy(); } - TEST_P(INTEG_TestPoseComparisonFixture, Integ_TestRecording) + TEST_P(TestPoseComparisonFixture, TestRecording) { // Make one recording, 10 seconds at 60 fps Recorder::RecordSettings settings; @@ -294,30 +294,30 @@ namespace EMotionFX recording->Destroy(); } - INSTANTIATE_TEST_CASE_P(Integ_TestPoses, INTEG_PoseComparisonFixture, + INSTANTIATE_TEST_CASE_P(DISABLED_TestPoses, PoseComparisonFixture, ::testing::Values( PoseComparisonFixtureParams ( - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.animgraph", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.motionset", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.emfxrecording" + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.animgraph", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.motionset", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.emfxrecording" ), PoseComparisonFixtureParams ( - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.actor", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.animgraph", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.motionset", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.emfxrecording" + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.actor", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.animgraph", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.motionset", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Pendulum/pendulum.emfxrecording" ) ) ); - INSTANTIATE_TEST_CASE_P(Integ_TestPoseComparison, INTEG_TestPoseComparisonFixture, + INSTANTIATE_TEST_CASE_P(DISABLED_TestPoseComparison, TestPoseComparisonFixture, ::testing::Values( PoseComparisonFixtureParams ( - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.animgraph", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.motionset", - "@products@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.emfxrecording" + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.animgraph", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.motionset", + "@exefolder@/Test.Assets/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.emfxrecording" ) ) ); diff --git a/Gems/HttpRequestor/Code/Tests/HttpRequestorTest.cpp b/Gems/HttpRequestor/Code/Tests/HttpRequestorTest.cpp index c7540d091f..48826fcf10 100644 --- a/Gems/HttpRequestor/Code/Tests/HttpRequestorTest.cpp +++ b/Gems/HttpRequestor/Code/Tests/HttpRequestorTest.cpp @@ -7,52 +7,50 @@ */ #include +#include #include #include #include #include "HttpRequestManager.h" -class Integ_HttpTest - : public ::testing::Test +class HttpTest + : public UnitTest::ScopedAllocatorSetupFixture { -public: - HttpRequestor::ManagerPtr m_httpRequestManager; - - // to wait for test to complete - AZStd::mutex m_requestMutex; - AZStd::condition_variable m_requestConditionVar; - - AZStd::string resultData; - AZStd::atomic resultCode; - - Integ_HttpTest() - { - m_httpRequestManager = AZStd::make_shared(); - resultCode = Aws::Http::HttpResponseCode::REQUEST_NOT_MADE; - resultData = "{}"; - - AZStd::unique_lock lock(m_requestMutex); - m_requestConditionVar.wait_for(lock, AZStd::chrono::milliseconds(10)); - } - - virtual ~Integ_HttpTest() - { - m_httpRequestManager.reset(); - } }; -TEST_F(Integ_HttpTest, HttpRequesterTest) +TEST_F(HttpTest, DISABLED_HttpRequesterTest) { - m_httpRequestManager->AddTextRequest(HttpRequestor::TextParameters("https://httpbin.org/ip", Aws::Http::HttpMethod::HTTP_GET, [this](const AZStd::string & data, Aws::Http::HttpResponseCode code) - { - resultData = data; - resultCode = code; - m_requestConditionVar.notify_all(); - })); + HttpRequestor::Manager httpRequestManager; - AZStd::unique_lock lock(m_requestMutex); - m_requestConditionVar.wait_for(lock, AZStd::chrono::milliseconds(5000)); + // to wait for test to complete + AZStd::mutex requestMutex; + AZStd::condition_variable requestConditionVar; + + AZStd::string resultData = {}; + AZStd::atomic resultCode = Aws::Http::HttpResponseCode::REQUEST_NOT_MADE; + + { + AZStd::unique_lock lock(requestMutex); + requestConditionVar.wait_for(lock, AZStd::chrono::milliseconds(10)); + } + + httpRequestManager.AddTextRequest( + HttpRequestor::TextParameters("https://httpbin.org/ip", + Aws::Http::HttpMethod::HTTP_GET, + [&resultData, &resultCode, &requestConditionVar](const AZStd::string& data, Aws::Http::HttpResponseCode code) + { + resultData = data; + resultCode = code; + requestConditionVar.notify_all(); + } + ) + ); + + { + AZStd::unique_lock lock(requestMutex); + requestConditionVar.wait_for(lock, AZStd::chrono::milliseconds(5000)); + } EXPECT_NE(Aws::Http::HttpResponseCode::REQUEST_NOT_MADE, resultCode); } diff --git a/Gems/LmbrCentral/Code/Tests/BundlingSystemComponentTests.cpp b/Gems/LmbrCentral/Code/Tests/BundlingSystemComponentTests.cpp index 7275909908..2d3f67c112 100644 --- a/Gems/LmbrCentral/Code/Tests/BundlingSystemComponentTests.cpp +++ b/Gems/LmbrCentral/Code/Tests/BundlingSystemComponentTests.cpp @@ -26,12 +26,12 @@ namespace UnitTest { - class Integ_BundlingSystemComponentFixture : + class BundlingSystemComponentFixture : public ::testing::Test { public: - Integ_BundlingSystemComponentFixture() = default; + BundlingSystemComponentFixture() = default; bool TestAsset(const char* assetPath) { @@ -59,7 +59,7 @@ namespace UnitTest } }; - TEST_F(Integ_BundlingSystemComponentFixture, HasBundle_LoadBundles_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_HasBundle_LoadBundles_Success) { // This asset lives only within LmbrCentral/Assets/Test/Bundle/staticdata.pak which is copied to our // cache as test/bundle/staticdata.pak and should be loaded below @@ -72,7 +72,7 @@ namespace UnitTest EXPECT_FALSE(TestAsset(testAssetPath)); } - TEST_F(Integ_BundlingSystemComponentFixture, HasBundle_LoadBundlesCatalogChecks_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_HasBundle_LoadBundlesCatalogChecks_Success) { // This asset lives only within LmbrCentral/Assets/Test/Bundle/staticdata.pak which is copied to our // cache as test/bundle/staticdata.pak and should be loaded below @@ -92,7 +92,7 @@ namespace UnitTest EXPECT_FALSE(TestAsset(noCatalogAsset)); } - TEST_F(Integ_BundlingSystemComponentFixture, BundleSystemComponent_SingleUnloadCheckCatalog_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_BundleSystemComponent_SingleUnloadCheckCatalog_Success) { // This asset lives only within LmbrCentral/Assets/Test/Bundle/staticdata.pak which is copied to our // cache as test/bundle/staticdata.pak and should be loaded below @@ -132,7 +132,7 @@ namespace UnitTest EXPECT_FALSE(TestAssetId(testDDSAsset)); } - TEST_F(Integ_BundlingSystemComponentFixture, BundleSystemComponent_SingleLoadAndBundleMode_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_BundleSystemComponent_SingleLoadAndBundleMode_Success) { // This asset lives only within LmbrCentral/Assets/Test/Bundle/staticdata.pak which is copied to our // cache as test/bundle/staticdata.pak and should be loaded below @@ -157,7 +157,7 @@ namespace UnitTest EXPECT_FALSE(TestAssetId(testMTLAsset)); } - TEST_F(Integ_BundlingSystemComponentFixture, BundleSystemComponent_OpenClosePackCount_Match) + TEST_F(BundlingSystemComponentFixture, DISABLED_BundleSystemComponent_OpenClosePackCount_Match) { // This asset lives only within LmbrCentral/Assets/Test/Bundle/staticdata.pak which is copied to our // cache as test/bundle/staticdata.pak and should be loaded below @@ -198,7 +198,7 @@ namespace UnitTest EXPECT_EQ(bundleCount, 0); } - TEST_F(Integ_BundlingSystemComponentFixture, BundleSystemComponent_SplitPakTestWithAsset_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_BundleSystemComponent_SplitPakTestWithAsset_Success) { // This asset lives only within LmbrCentral/Assets/Test/SplitBundleTest/splitbundle__1.pak which is a dependent bundle of splitbundle.pak const char testDDSAsset_split[] = "textures/milestone2/am_floor_tile_ddna_test.dds.7"; @@ -228,7 +228,7 @@ namespace UnitTest } // Verify that our bundles using catalogs of the same name work properly - TEST_F(Integ_BundlingSystemComponentFixture, BundleSystemComponent_SharedCatalogName_Success) + TEST_F(BundlingSystemComponentFixture, DISABLED_BundleSystemComponent_SharedCatalogName_Success) { // This bundle was built for PC but is generic and the test should work fine on other platforms // gamepropertioessmall_pc.pak has a smaller version of the gameproperties csv From d1d4bf812ef72b4e3b509d925b4e174be31678fe Mon Sep 17 00:00:00 2001 From: smurly Date: Fri, 15 Oct 2021 09:18:46 -0700 Subject: [PATCH 51/52] P0 PostFX Gradient Weight Modifier component parallel test automation (#4709) * PostFX Gradient Weight Modifiere component P0 parallel test Signed-off-by: Scott Murray * fixing some comment step numbering Signed-off-by: Scott Murray * fixing PostFX casing and method camel casing of the test function Signed-off-by: Scott Murray * changing the casing of the file name Signed-off-by: Scott Murray --- .../Atom/TestSuite_Main_Optimized.py | 4 + ...nents_PostFXGradientWeightModifierAdded.py | 179 ++++++++++++++++++ 2 files changed, 183 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXGradientWeightModifierAdded.py diff --git a/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py index 447a4ebac9..c29a391be4 100644 --- a/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Main_Optimized.py @@ -71,5 +71,9 @@ class TestAutomation(EditorTestSuite): class AtomEditorComponents_PostFXShapeWeightModifierAdded(EditorSharedTest): from Atom.tests import hydra_AtomEditorComponents_PostFxShapeWeightModifierAdded as test_module + @pytest.mark.test_case_id("C36525664") + class AtomEditorComponents_PostFXGradientWeightModifierAdded(EditorSharedTest): + from Atom.tests import hydra_AtomEditorComponents_PostFXGradientWeightModifierAdded as test_module + class ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(EditorSharedTest): from Atom.tests import hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges as test_module diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXGradientWeightModifierAdded.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXGradientWeightModifierAdded.py new file mode 100644 index 0000000000..d38e96739d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomEditorComponents_PostFXGradientWeightModifierAdded.py @@ -0,0 +1,179 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +class Tests: + creation_undo = ( + "UNDO Entity creation success", + "UNDO Entity creation failed") + creation_redo = ( + "REDO Entity creation success", + "REDO Entity creation failed") + postfx_gradient_weight_creation = ( + "PostFX Gradient Weight Modifier Entity successfully created", + "PostFX Gradient Weight Modifier Entity failed to be created") + postfx_gradient_weight_component = ( + "Entity has a PostFX Gradient Weight Modifier component", + "Entity failed to find PostFX Gradient Weight Modifier component") + postfx_gradient_weight_disabled = ( + "PostFX Gradient Weight Modifier component disabled", + "PostFX Gradient Weight Modifier component was not disabled.") + postfx_layer_component = ( + "Entity has a PostFX Layer component", + "Entity did not have an PostFX Layer component") + postfx_gradient_weight_enabled = ( + "PostFX Gradient Weight Modifier component enabled", + "PostFX Gradient Weight Modifier component was not enabled.") + enter_game_mode = ( + "Entered game mode", + "Failed to enter game mode") + exit_game_mode = ( + "Exited game mode", + "Couldn't exit game mode") + is_visible = ( + "Entity is visible", + "Entity was not visible") + is_hidden = ( + "Entity is hidden", + "Entity was not hidden") + entity_deleted = ( + "Entity deleted", + "Entity was not deleted") + deletion_undo = ( + "UNDO deletion success", + "UNDO deletion failed") + deletion_redo = ( + "REDO deletion success", + "REDO deletion failed") + + +def AtomEditorComponents_PostFXGradientWeightModifier_AddedToEntity(): + """ + Summary: + Tests the PostFX Gradient Weight Modifier component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a PostFX Gradient Weight Modifier entity with no components. + 2) Add a PostFX Gradient Weight Modifier component to PostFX Gradient Weight Modifier entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Verify PostFX Gradient Weight Modifier component not enabled. + 6) Add PostFX Layer component since it is required by the PostFX Gradient Weight Modifier component. + 7) Verify PostFX Gradient Weight Modifier component is enabled. + 8) Enter/Exit game mode. + 9) Test IsHidden. + 10) Test IsVisible. + 11) Delete PostFX Gradient Weight Modifier entity. + 12) UNDO deletion. + 13) REDO deletion. + 14) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + TestHelper.init_idle() + TestHelper.open_level("", "Base") + + # Test steps begin. + # 1. Create a PostFX Gradient Weight Modifier entity with no components. + postfx_gradient_weight_name = "PostFX Gradient Weight Modifier" + postfx_gradient_weight_entity = EditorEntity.create_editor_entity(postfx_gradient_weight_name) + Report.critical_result(Tests.postfx_gradient_weight_creation, postfx_gradient_weight_entity.exists()) + + # 2. Add a PostFX Gradient Weight Modifier component to PostFX Gradient Weight Modifier entity. + postfx_gradient_weight_component = postfx_gradient_weight_entity.add_component(postfx_gradient_weight_name) + Report.critical_result( + Tests.postfx_gradient_weight_component, + postfx_gradient_weight_entity.has_component(postfx_gradient_weight_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not postfx_gradient_weight_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, postfx_gradient_weight_entity.exists()) + + # 5. Verify PostFX Gradient Weight Modifier component not enabled. + Report.result(Tests.postfx_gradient_weight_disabled, not postfx_gradient_weight_component.is_enabled()) + + # 6. Add PostFX Layer component since it is required by the PostFX Gradient Weight Modifier component. + postfx_layer_name = "PostFX Layer" + postfx_gradient_weight_entity.add_component(postfx_layer_name) + Report.result(Tests.postfx_layer_component, postfx_gradient_weight_entity.has_component(postfx_layer_name)) + + # 7. Verify PostFX Gradient Weight Modifier component is enabled. + Report.result(Tests.postfx_gradient_weight_enabled, postfx_gradient_weight_component.is_enabled()) + + # 8. Enter/Exit game mode. + TestHelper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + TestHelper.exit_game_mode(Tests.exit_game_mode) + + # 9. Test IsHidden. + postfx_gradient_weight_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, postfx_gradient_weight_entity.is_hidden() is True) + + # 10. Test IsVisible. + postfx_gradient_weight_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, postfx_gradient_weight_entity.is_visible() is True) + + # 11. Delete PostFX Gradient Weight Modifier entity. + postfx_gradient_weight_entity.delete() + Report.result(Tests.entity_deleted, not postfx_gradient_weight_entity.exists()) + + # 12. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, postfx_gradient_weight_entity.exists()) + + # 13. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not postfx_gradient_weight_entity.exists()) + + # 14. Look for errors or asserts. + TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0) + for error_info in error_tracer.errors: + Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}") + for assert_info in error_tracer.asserts: + Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}") + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_PostFXGradientWeightModifier_AddedToEntity) From 49f339364697cba9a3c8b5a3853c34b1cdc1948f Mon Sep 17 00:00:00 2001 From: mrieggeramzn <61609885+mrieggeramzn@users.noreply.github.com> Date: Fri, 15 Oct 2021 11:26:19 -0700 Subject: [PATCH 52/52] Removing unused softening boundary width controls (#4647) Signed-off-by: mrieggeramzn --- .../Shadow/DirectionalLightShadow.azsli | 76 ------- .../Atom/Features/Shadow/JitterTablePcf.azsli | 185 ------------------ .../Features/Shadow/ProjectedShadow.azsli | 35 ---- .../Atom/Features/Shadow/Shadow.azsli | 3 - .../CoreLights/ViewSrg.azsli | 3 - .../atom_feature_common_asset_files.cmake | 1 - ...irectionalLightFeatureProcessorInterface.h | 6 - .../DiskLightFeatureProcessorInterface.h | 2 - .../PointLightFeatureProcessorInterface.h | 3 - .../Atom/Feature/CoreLights/ShadowConstants.h | 1 - ...ProjectedShadowFeatureProcessorInterface.h | 2 - .../DirectionalLightFeatureProcessor.cpp | 70 +------ .../DirectionalLightFeatureProcessor.h | 7 +- .../CoreLights/DiskLightFeatureProcessor.cpp | 5 - .../CoreLights/DiskLightFeatureProcessor.h | 1 - .../Source/CoreLights/EsmShadowmapsPass.cpp | 22 --- .../Source/CoreLights/EsmShadowmapsPass.h | 10 - .../CoreLights/PointLightFeatureProcessor.cpp | 5 - .../CoreLights/PointLightFeatureProcessor.h | 1 - .../ProjectedShadowFeatureProcessor.cpp | 79 +------- .../Shadows/ProjectedShadowFeatureProcessor.h | 4 +- .../CommonFeatures/CoreLights/AreaLightBus.h | 7 - .../CoreLights/AreaLightComponentConfig.h | 1 - .../CoreLights/DirectionalLightBus.h | 9 - .../DirectionalLightComponentConfig.h | 4 - .../CoreLights/AreaLightComponentConfig.cpp | 1 - .../AreaLightComponentController.cpp | 18 -- .../CoreLights/AreaLightComponentController.h | 2 - .../DirectionalLightComponentConfig.cpp | 1 - .../DirectionalLightComponentController.cpp | 19 -- .../DirectionalLightComponentController.h | 2 - .../Source/CoreLights/DiskLightDelegate.cpp | 8 - .../Source/CoreLights/DiskLightDelegate.h | 1 - .../CoreLights/EditorAreaLightComponent.cpp | 9 - .../EditorDirectionalLightComponent.cpp | 9 - .../Source/CoreLights/LightDelegateBase.h | 1 - .../CoreLights/LightDelegateInterface.h | 2 - .../Source/CoreLights/SphereLightDelegate.cpp | 8 - .../Source/CoreLights/SphereLightDelegate.h | 1 - 39 files changed, 8 insertions(+), 616 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/JitterTablePcf.azsli diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli index dd235fcd3a..633ea85387 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli @@ -10,7 +10,6 @@ #include #include -#include "JitterTablePcf.azsli" #include "Shadow.azsli" #include "ShadowmapAtlasLib.azsli" #include "BicubicPcfFilters.azsli" @@ -82,12 +81,6 @@ class DirectionalLightShadow // result.y == true if the given coordinate is in shadow. bool2 IsShadowed(float3 shadowCoord, uint indexOfCascade); - // This checks if the point is shadowed or not for the given center coordinate and jitter. - bool IsShadowedWithJitter( - float3 jitterUnit, - float jitterDepthDiffBase, - uint jitterIndex); - // This outputs visibility ratio (from 0.0 to 1.0) of the given coordinate // from the light origin without filtering. float GetVisibilityFromLightNoFilter(); @@ -189,75 +182,6 @@ bool2 DirectionalLightShadow::IsShadowed(float3 shadowCoord, uint indexOfCascade return bool2(false, false); } -bool DirectionalLightShadow::IsShadowedWithJitter( - float3 jitterUnit, - float jitterDepthDiffBase, - uint jitterIndex) -{ - const uint cascadeCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_cascadeCount; - const float4x4 worldToLightViewMatrices[ViewSrg::MaxCascadeCount] = - ViewSrg::m_directionalLightShadows[m_lightIndex].m_worldToLightViewMatrices; - const float4x4 lightViewToShadowmapMatrices[ViewSrg::MaxCascadeCount] = - ViewSrg::m_directionalLightShadows[m_lightIndex].m_lightViewToShadowmapMatrices; - const float boundaryScale = - ViewSrg::m_directionalLightShadows[m_lightIndex].m_boundaryScale; - - const float2 jitterXY = g_jitterTablePcf[jitterIndex]; - - // jitterLightView is the jittering diff vector from the lighted point on the surface - // in the light view space. It is remarked as "v_J" in the comment - // named "Calculate depth adjusting diff for jittered samples" - // just before the function GetJitterUnitVectorDepthDiffBase. - const float4 jitterLightView = float4(jitterXY, 0., 0.) * boundaryScale; - - // It checks the jittered point is lit or shadowed from the detailed cascade - // to the less detailed one. - for (uint indexOfCascade = 0; indexOfCascade < cascadeCount; ++indexOfCascade) - { - // jitterShadowmap is the jittering diff vector in the shadowmap space. - const float4 jitterShadowmap = mul(lightViewToShadowmapMatrices[indexOfCascade], jitterLightView); - - // Calculation of the jittering for Z-coordinate (light direction) is required - // to check lit/shadowed for the jittered point. - // jitterDepthDiff is the Z-coordinate of the jittering diff vector - // in the shadowmap space. - float jitterDepthDiff = 0.; - - // jitterDepthDiffBase is "1/tan(theta)" in the comment. - if (jitterDepthDiffBase != 0.) - { - // jitterUnitLightView is the unit vector in the light view space - // noted as "v_M" in the comment. - const float3 jitterUnitLightView = - normalize(mul(worldToLightViewMatrices[indexOfCascade], float4(jitterUnit, 0.)).xyz); - const float lightViewToShadowmapZScale = -lightViewToShadowmapMatrices[indexOfCascade]._m22; - // jitterDepthDiff is the "d" in the note, and it is calculated by - // d = (v_J . v_M) / tan(theta) - // in the light view space. Furthermore it have to be converted - // to the light clip space, which can be done by lightViewToShadowmapZScale. - jitterDepthDiff = - dot(jitterLightView.xyz, jitterUnitLightView) * jitterDepthDiffBase * - lightViewToShadowmapZScale; - } - // jitteredCoord is the coordinate of the jittered point in the shadowmap space. - const float3 jitteredCoord = - m_shadowCoords[indexOfCascade] + float3(jitterShadowmap.xy, jitterDepthDiff); - // Check for the jittered point is lit or shadowed. - const bool2 checkedShadowed = IsShadowed( - jitteredCoord, - indexOfCascade); - // If check is done, return the lit/shadowed flag. - // Otherwise make it pend to the next cascade. - if (checkedShadowed.x) - { - m_debugInfo.m_cascadeIndex = indexOfCascade; - return checkedShadowed.y; - } - } - m_debugInfo.m_cascadeIndex = cascadeCount; - return false; -} - float DirectionalLightShadow::GetVisibilityFromLightNoFilter() { const uint cascadeCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_cascadeCount; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/JitterTablePcf.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/JitterTablePcf.azsli deleted file mode 100644 index 9082286758..0000000000 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/JitterTablePcf.azsli +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - /* - The following is the output of - $ python3 pcf_jitter_table.py 6 g_jitterTablePcf 0 - where pcf_jitter_table.py has the following contents. - -@code -#!/usr/bin/env python3 - -import random -import sys -import math - - -""" Returns if a point in the range -[radius_min, radius_sup)*[angle_min, angle_sup) -is contained in the tuple polar coordinates. -""" -def is_point_include(radius_min, radius_sup, angle_min, angle_sup, polars): - for polar in polars: - if (radius_min <= polar[0] and polar[0] < radius_sup and - angle_min <= polar[1] and polar[1] < angle_sup): - return True - return False - - -""" Insert a randomly generated polar coordianted point in each -range [r0, r1)*[a0, a1) if there has not been such a point -in tuple coords yet, where [0, 1)*[0, 2pi) is divided -into the rad_count*agl_count ranges. -""" -def add_jitter_coords(radius_count, angle_count, polars): - radius_base = 1.0 / math.sqrt(radius_count) - for radius_index in range(radius_count): - # range of radius - radius_min = math.sqrt(radius_index) * radius_base - radius_sup = math.sqrt(radius_index + 1) * radius_base - - # randomize angle order - random_state = random.getstate() - angle_indices = list(range(angle_count)) - random.shuffle(angle_indices) - random.setstate(random_state) - - for angle_index in angle_indices: - # range of angle - angle_min = 2 * math.pi * angle_index / angle_count - angle_sup = 2 * math.pi * (angle_index + 1) / angle_count - - # if no point in the radius/angle range, add a new point - if not is_point_include(radius_min, radius_sup, - angle_min, angle_sup, - polars): - radius = radius_min + (radius_sup - radius_min) * random.random() - angle = angle_min + (angle_sup - angle_min) * random.random() - polars += [[radius, angle]] - - -""" Return a formatted string readable as an array of -orthogonal coordinated points which are in inside of the unit disk. -""" -def conv_array_string(polars): - result = "{\n" - for [radius, angle] in polars: - x = radius * math.cos(angle) - y = radius * math.sin(angle) - result += str.format(" float2({: 1.20e}, {: 1.20e}),\n", x, y) - result = result.rstrip(",\n") + "\n};\n" - return result - - -if __name__ == "__main__": - rad_size = 1 - ang_size = 1 - - if len(sys.argv) > 3: - random_seed = int(sys.argv[3]) - else: - random_seed = 0 - - if len(sys.argv) > 2: - array_name = sys.argv[2] - else: - array_name = False - - if len(sys.argv) > 1: - len_log = int(sys.argv[1]) - else: - print(" usage: {} array_len_log2 [array_file_name] [random_seed]".format(__file__)) - print(" array_len_log2 = 2 -> array length = 4") - print(" array_len_log2 = 6 -> array length = 64") - sys.exit() - - random.seed(random_seed) - coords = [] - add_jitter_coords(rad_size, ang_size, coords) - for index in range(len_log): - if index % 2 == 0: - rad_size *= 2 - else: - ang_size *= 2 - add_jitter_coords(rad_size, ang_size, coords) - - if array_name: - print(str.format("static const float2 {}[{}] =", array_name, len(coords))) - print(conv_array_string(coords)) - - @endcode - */ -#pragma once - -static const float2 g_jitterTablePcf[64] = -{ - float2( 4.21857815578105532772e-02, -8.43367430701083664601e-01), - float2(-1.66526814909220763350e-02, 2.96922406531470617352e-01), - float2(-1.06374665780382349212e-01, -3.45521852905696924552e-01), - float2( 5.42648241814168375008e-01, 7.63475573328278533936e-01), - float2(-1.55045122122251910479e-01, 5.78282315712970729216e-01), - float2( 1.01310018770242576264e-02, -6.88001749851880561870e-01), - float2(-5.41276603451248283783e-01, 5.21888233660957712168e-01), - float2(-6.69885071867917680777e-01, -6.72019666097878665134e-01), - float2( 1.22985029409499718039e-02, 4.54706838949524849713e-01), - float2( 4.00334354168925599105e-01, -6.20112671104014120949e-02), - float2( 2.32326155804074424571e-01, 5.14183027524470093184e-01), - float2(-3.26788693165450228051e-01, -6.03339478694129849323e-01), - float2( 7.72374386126136736053e-01, 1.23204314299169448432e-01), - float2(-4.45379212004159807936e-01, -6.35591042627205338178e-01), - float2( 9.86986293787213919693e-01, -5.18195017297516449806e-02), - float2(-9.09197225477999193544e-01, 1.95281945570711268356e-01), - float2( 8.78123785413316704229e-02, -2.77671865082058690055e-02), - float2( 1.93947312440399088906e-01, 4.27852204081567363825e-03), - float2(-2.06133675819526185347e-01, -1.49183652412411493771e-01), - float2(-4.11351098583102647854e-01, 2.36214692717993696158e-01), - float2( 3.50058750095615767162e-01, -3.57193658067260721989e-01), - float2(-5.54174780014121681759e-01, -2.23361040823672196698e-01), - float2(-6.29913348094886860196e-01, 1.29962593232600148729e-01), - float2( 3.96119563669521335125e-01, 4.90495219155295036906e-01), - float2( 7.26077464944819728210e-01, -3.70531027878536270426e-02), - float2(-5.50726266551596621568e-01, 6.48997654184258587762e-01), - float2(-6.98067624269093189859e-01, -3.83843898992943299842e-01), - float2( 8.72900706885875177221e-02, 8.24287559846993866941e-01), - float2( 6.65413234189638491678e-01, -5.66029707430476647367e-01), - float2(-5.97071574457786802270e-01, -6.93417220711863180327e-01), - float2( 6.09778569514949131403e-01, 6.92279483269558570946e-01), - float2(-8.10051800827623957879e-01, 5.82366304247235455627e-01), - float2(-8.77200948157437071506e-02, -1.88326609190753474499e-01), - float2( 9.79306884403889771340e-02, 1.86693151785678163046e-01), - float2( 4.60071424048798319206e-02, -1.98255149016034859510e-01), - float2(-5.37585860722621794450e-02, 3.99205315590760584366e-02), - float2( 2.18621803321778829243e-01, -3.85632280444686503795e-01), - float2(-2.98409571230789372187e-02, 4.22286693608096730390e-01), - float2( 3.58654757584850270025e-01, 2.95175871390239985548e-01), - float2(-3.85631921979480485341e-01, -3.00322047091407640096e-01), - float2( 4.49800763439369810648e-01, 3.98492182500493397068e-01), - float2(-4.97878650048238891035e-01, 2.57984038389083569776e-01), - float2(-3.12055242602567339816e-01, -4.88013525550807125697e-01), - float2( 5.87078632117718268724e-01, -6.97256834327608099322e-02), - float2( 6.23692403999373534695e-01, 3.11519734097943645779e-01), - float2( 6.64426445690903810792e-01, -2.27661844509491811950e-01), - float2(-3.24662942872471160793e-01, 5.68939932480760024447e-01), - float2(-5.31263995010459511015e-01, -4.66108719959298256619e-01), - float2( 5.10323549430644951563e-01, 5.81027848262460677731e-01), - float2( 2.82695533021593392586e-01, -7.03582425015577883620e-01), - float2(-5.98419541732174709026e-01, -4.68015982003612274198e-01), - float2(-3.95281650646674975746e-01, 6.10614720709622194050e-01), - float2( 7.87454411900813555647e-01, 1.37726315874787758053e-01), - float2(-7.36310249594224086600e-01, 4.25723821775386646049e-01), - float2( 6.48232481978769037312e-01, -5.53108138515975955585e-01), - float2(-1.88558544306507869237e-01, -7.79120748356531223067e-01), - float2(-3.78614630625567993860e-01, 7.82366459873827913007e-01), - float2(-8.48582606942172357201e-01, -3.78504015913022351381e-01), - float2( 1.91472859899175090748e-02, -9.13050020447597532325e-01), - float2( 8.08826910050883585157e-01, 4.17202663034078935489e-01), - float2(-9.27062588380768493046e-01, -2.94160352051227980130e-01), - float2( 6.67882607007592055126e-01, -6.88642020601400450808e-01), - float2(-1.59349274307943010454e-02, 9.37629353656756814317e-01), - float2( 9.86975590293644233775e-01, 1.44401793964158337014e-01) -}; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli index b91d0ce915..daed3a2921 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli @@ -13,7 +13,6 @@ #include #include #include "BicubicPcfFilters.azsli" -#include "JitterTablePcf.azsli" #include "Shadow.azsli" // ProjectedShadow calculates shadowed area projected from a light. @@ -44,11 +43,6 @@ class ProjectedShadow float GetThickness(); bool IsShadowed(float3 shadowPosition); - bool IsShadowedWithJitter( - float3 jitterUnitX, - float3 jitterUnitY, - float jitterDepthDiffBase, - uint jitterIndex); void SetShadowPosition(); float3 GetAtlasPosition(float2 texturePosition); static float UnprojectDepth(uint shadowIndex, float depthBufferValue); @@ -321,35 +315,6 @@ bool ProjectedShadow::IsShadowed(float3 shadowPosition) return false; } -bool ProjectedShadow::IsShadowedWithJitter( - float3 jitterUnitX, - float3 jitterUnitY, - float jitterDepthDiffBase, - uint jitterIndex) -{ - ViewSrg::ProjectedShadow shadow = ViewSrg::m_projectedShadows[m_shadowIndex]; - const float4x4 depthBiasMatrix = shadow.m_depthBiasMatrix; - const float boundaryScale = shadow.m_boundaryScale; - - const float2 jitterXY = g_jitterTablePcf[jitterIndex]; - - const float dist = distance(m_worldPosition, m_viewPosition); - const float boundaryRadius = dist * tan(boundaryScale); - // jitterWorldXY is the jittering diff vector from the lighted point on the surface - // in the world space. It is remarked as "v_J" in the comment - // named "Calculate depth adjusting diff for jittered samples" - // just before the function GetJitterUnitVectorDepthDiffBase. - const float3 jitterWorldXY = jitterUnitX * (jitterXY.x * boundaryRadius) + jitterUnitY * (jitterXY.y * boundaryRadius); - // The adjusting diff of depth ("d" in the comment) is calculated by - // jitterXY.y * boundaryRadius * jitterDepthDiffBase. - const float3 jitterWorldZ = m_lightDirection * (jitterXY.y * boundaryRadius * jitterDepthDiffBase); - - const float3 jitteredWorldPosition = m_worldPosition + jitterWorldXY + jitterWorldZ; - const float4 jitteredShadowmapHomogeneous = mul(depthBiasMatrix, float4(jitteredWorldPosition, 1)); - - return IsShadowed(jitteredShadowmapHomogeneous.xyz / jitteredShadowmapHomogeneous.w); -} - void ProjectedShadow::SetShadowPosition() { const float4x4 depthBiasMatrix = ViewSrg::m_projectedShadows[m_shadowIndex].m_depthBiasMatrix; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/Shadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/Shadow.azsli index e05ff076cb..1fe81016cf 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/Shadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/Shadow.azsli @@ -23,14 +23,11 @@ struct FilterParameter uint m_isEnabled; uint2 m_shadowmapOriginInSlice; uint m_shadowmapSize; - uint m_parameterOffset; - uint m_parameterCount; float m_lightDistanceOfCameraViewFrustum; float m_n_f_n; // n / (f - n) float m_n_f; // n - f float m_f; // f // where n: nearDepth, f: farDepth. - float2 m_padding; // explicit padding }; class Shadow diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli index 2065e28703..94d6f20da3 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli @@ -22,14 +22,11 @@ partial ShaderResourceGroup ViewSrg uint m_isEnabled; uint2 m_shadowmapOriginInSlice; uint m_shadowmapSize; - uint m_parameterOffset; - uint m_parameterCount; float m_lightDistanceOfCameraViewFrustum; float m_n_f_n; // n / (f - n) float m_n_f; // n - f float m_f; // f // where n: nearDepth, f: farDepth. - float2 m_padding; // explicit padding }; // Simple Point Lights diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index 60614993b5..cf456b2e41 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -286,7 +286,6 @@ set(FILES ShaderLib/Atom/Features/ScreenSpace/ScreenSpaceUtil.azsli ShaderLib/Atom/Features/Shadow/BicubicPcfFilters.azsli ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli - ShaderLib/Atom/Features/Shadow/JitterTablePcf.azsli ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli ShaderLib/Atom/Features/Shadow/Shadow.azsli ShaderLib/Atom/Features/Shadow/ShadowmapAtlasLib.azsli diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h index 75d266cc52..769c7b95a6 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h @@ -154,12 +154,6 @@ namespace AZ //! @param count Sample Count for filtering (up to 64) virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; - //! This specifies the width of boundary between shadowed area and lit area. - //! @param handle the light handle. - //! @param width Boundary width. The shadow is gradually changed the degree of shadowed. - //! If width == 0, softening edge is disabled. Units are in meters. - virtual void SetShadowBoundaryWidth(LightHandle handle, float boundaryWidth) = 0; - //! Sets whether the directional shadowmap should use receiver plane bias. //! This attempts to reduce shadow acne when using large pcf filters. virtual void SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) = 0; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h index 3ab83200ae..5aa2dfb800 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h @@ -90,8 +90,6 @@ namespace AZ virtual void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) = 0; //! Specifies filter method of shadows. virtual void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) = 0; - //! Specifies the width of boundary between shadowed area and lit area in radians. The degree ofshadowed gradually changes on the boundary. 0 disables softening. - virtual void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) = 0; //! Sets sample count for filtering of shadow boundary (up to 64) virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff in the border areas between light and shadow. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h index 6752ac4c52..1a5a776cdf 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h @@ -70,9 +70,6 @@ namespace AZ virtual void SetShadowBias(LightHandle handle, float bias) = 0; //! Specifies filter method of shadows. virtual void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) = 0; - //! Specifies the width of boundary between shadowed area and lit area in radians. The degree ofshadowed gradually changes on - //! the boundary. 0 disables softening. - virtual void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) = 0; //! Sets sample count for filtering of shadow boundary (up to 64) virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff in the border areas between light and shadow. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h index dbad3af21f..309331dcf5 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h @@ -42,7 +42,6 @@ namespace AZ // [GFX TODO][ATOM-2408] Make the max number of cascade modifiable at runtime. static constexpr uint16_t MaxNumberOfCascades = 4; static constexpr uint16_t MaxPcfSamplingCount = 64; - static constexpr float MaxSofteningBoundaryWidth = 0.1f; } // namespace Shadow } // namespace Render diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h index 3d6c0c3015..46560f435d 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h @@ -54,8 +54,6 @@ namespace AZ::Render virtual void SetShadowBias(ShadowId id, float bias) = 0; //! Sets the shadow filter method virtual void SetShadowFilterMethod(ShadowId id, ShadowFilterMethod method) = 0; - //! Sets the width of boundary between shadowed area and lit area. - virtual void SetSofteningBoundaryWidthAngle(ShadowId id, float boundaryWidthRadians) = 0; //! Sets the sample count for filtering of the shadow boundary, max 64. virtual void SetFilteringSampleCount(ShadowId id, uint16_t count) = 0; //! Sets all of the shadow properites in one call diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index 42cca0e57c..0a9f3480ad 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -584,15 +584,6 @@ namespace AZ m_shadowBufferNeedsUpdate = true; } - void DirectionalLightFeatureProcessor::SetShadowBoundaryWidth(LightHandle handle, float boundaryWidth) - { - for (auto& it : m_shadowData) - { - it.second.GetData(handle.GetIndex()).m_boundaryScale = boundaryWidth / 2.f; - } - m_shadowBufferNeedsUpdate = true; - } - void DirectionalLightFeatureProcessor::SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) { m_shadowProperties.GetData(handle.GetIndex()).m_isReceiverPlaneBiasEnabled = enable; @@ -1116,50 +1107,13 @@ namespace AZ for (const auto& passIt : m_esmShadowmapsPasses) { const RPI::View* cameraView = passIt.second.front()->GetRenderPipeline()->GetDefaultView().get(); - UpdateStandardDeviations(handle, cameraView); - UpdateFilterOffsetsCounts(handle, cameraView); + UpdateFilterEnabled(handle, cameraView); UpdateShadowmapPositionInAtlas(handle, cameraView); SetFilterParameterToPass(handle, cameraView); } } - void DirectionalLightFeatureProcessor::UpdateStandardDeviations(LightHandle handle, const RPI::View* cameraView) - { - if (handle != m_shadowingLightHandle) - { - return; - } - - const DirectionalLightShadowData& data = m_shadowData.at(cameraView).GetData(handle.GetIndex()); - const ShadowProperty& property = m_shadowProperties.GetData(handle.GetIndex()); - AZStd::fixed_vector standardDeviations; - for (size_t cascadeIndex = 0; cascadeIndex < property.m_segments.at(cameraView).size(); ++cascadeIndex) - { - const Aabb& aabb = property.m_segments.at(cameraView)[cascadeIndex].m_aabb; - const float aabbDiameter = AZStd::GetMax( - aabb.GetMax().GetX() - aabb.GetMin().GetX(), - aabb.GetMax().GetZ() - aabb.GetMin().GetZ()); - float standardDeviation = 0.f; - if (aabbDiameter > 0.f) - { - const float boundaryWidth = data.m_boundaryScale * 2.f; - const float ratioToAabbWidth = boundaryWidth / aabbDiameter; - const float widthInPixels = ratioToAabbWidth * data.m_shadowmapSize; - standardDeviation = widthInPixels / (2 * GaussianMathFilter::ReliableSectionFactor); - } - standardDeviations.push_back(standardDeviation); - } - - for (const RPI::RenderPipelineId& pipelineId : m_renderPipelineIdsForPersistentView.at(cameraView)) - { - for (EsmShadowmapsPass* esmPass : m_esmShadowmapsPasses.at(pipelineId)) - { - esmPass->SetFilterParameters(standardDeviations); - } - } - } - - void DirectionalLightFeatureProcessor::UpdateFilterOffsetsCounts(LightHandle handle, const RPI::View* cameraView) + void DirectionalLightFeatureProcessor::UpdateFilterEnabled(LightHandle handle, const RPI::View* cameraView) { if (handle != m_shadowingLightHandle) { @@ -1170,29 +1124,11 @@ namespace AZ if (shadowData.m_shadowFilterMethod == aznumeric_cast(ShadowFilterMethod::Esm) || (shadowData.m_shadowFilterMethod == aznumeric_cast(ShadowFilterMethod::EsmPcf))) { - // Get array of filter counts for the camera view. - const RPI::RenderPipelineId& pipelineId = m_renderPipelineIdsForPersistentView.at(cameraView).front(); - AZ_Assert(!m_esmShadowmapsPasses.at(pipelineId).empty(), "Cannot find a EsmShadowmapsPass."); - const AZStd::array_view filterCounts = m_esmShadowmapsPasses.at(pipelineId).front()->GetFilterCounts(); - AZ_Assert(filterCounts.size() == GetCascadeCount(handle), "FilterCounts differs with cascade count."); - - // Create array of filter offsets - AZStd::vector filterOffsets; - filterOffsets.reserve(filterCounts.size()); - uint32_t filterOffset = 0; - for (const uint32_t count : filterCounts) - { - filterOffsets.push_back(filterOffset); - filterOffset += count; - } - // Write filter offsets and filter counts to ESM data for (uint16_t index = 0; index < GetCascadeCount(handle); ++index) { EsmShadowmapsPass::FilterParameter& filterParameter = m_esmParameterData.at(cameraView).GetData(index); filterParameter.m_isEnabled = true; - filterParameter.m_parameterOffset = filterOffsets[index]; - filterParameter.m_parameterCount = filterCounts[index]; } } else @@ -1202,8 +1138,6 @@ namespace AZ { EsmShadowmapsPass::FilterParameter& filterParameter = m_esmParameterData.at(cameraView).GetData(index); filterParameter.m_isEnabled = false; - filterParameter.m_parameterOffset = 0; - filterParameter.m_parameterCount = 0; } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h index 039f51d549..3c1ff8eabd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h @@ -217,7 +217,6 @@ namespace AZ void SetDebugFlags(LightHandle handle, DebugDrawFlags flags) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; - void SetShadowBoundaryWidth(LightHandle handle, float boundaryWidth) override; void SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) override; const Data::Instance GetLightBuffer() const; @@ -278,10 +277,8 @@ namespace AZ //! This updates the parameter of Gaussian filter used in ESM. void UpdateFilterParameters(LightHandle handle); - //! This updates standard deviations for each cascade. - void UpdateStandardDeviations(LightHandle handle, const RPI::View* cameraView); - //! This updates filter offset and size for each cascade. - void UpdateFilterOffsetsCounts(LightHandle handle, const RPI::View* cameraView); + //! This updates if the filter is enabled. + void UpdateFilterEnabled(LightHandle handle, const RPI::View* cameraView); //! This updates shadowmap position(origin and size) in the atlas for each cascade. void UpdateShadowmapPositionInAtlas(LightHandle handle, const RPI::View* cameraView); //! This set filter parameters to passes which execute filtering. diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp index 26e1757a5a..acf81ede32 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp @@ -322,11 +322,6 @@ namespace AZ { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowFilterMethod, method); } - - void DiskLightFeatureProcessor::SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle, boundaryWidthRadians); - } void DiskLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h index d65f587718..275712f84f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h @@ -53,7 +53,6 @@ namespace AZ void SetShadowBias(LightHandle handle, float bias) override; void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; - void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp index 99eaa8a919..b92d538fb5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp @@ -42,28 +42,6 @@ namespace AZ return m_lightTypeName; } - void EsmShadowmapsPass::SetFilterParameters(const AZStd::array_view& standardDeviations) - { - // Set descriptor for Gaussian filters for given set of standard deviations. - MathFilterDescriptor descriptor; - descriptor.m_kind = MathFilterKind::Gaussian; - descriptor.m_gaussians.reserve(standardDeviations.size()); - for (const float standardDeviation : standardDeviations) - { - descriptor.m_gaussians.emplace_back(GaussianFilterDescriptor{ standardDeviation }); - } - - // Set filter paramter buffer along with element counts for each filter. - MathFilter::BufferWithElementCounts bufferCounts = MathFilter::FindOrCreateFilterBuffer(descriptor); - m_filterTableBuffer = bufferCounts.first; - m_filterCounts = AZStd::move(bufferCounts.second); - } - - AZStd::array_view EsmShadowmapsPass::GetFilterCounts() const - { - return m_filterCounts; - } - void EsmShadowmapsPass::SetShadowmapIndexTableBuffer(const Data::Instance& tableBuffer) { m_shadowmapIndexTableBuffer = tableBuffer; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h index 6e5e1aa311..5a9898d507 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h @@ -50,14 +50,11 @@ namespace AZ uint32_t m_isEnabled = false; AZStd::array m_shadowmapOriginInSlice = { {0, 0 } }; // shadowmap origin in the slice of the atlas. uint32_t m_shadowmapSize = static_cast(ShadowmapSize::None); // width and height of shadowmap. - uint32_t m_parameterOffset; // offset of the filter parameter. - uint32_t m_parameterCount; // element count of the filter parameter. float m_lightDistanceOfCameraViewFrustum = 0.f; float m_n_f_n = 0.f; // n / (f - n) float m_n_f = 0.f; // n - f float m_f = 0.f; // f // where n: nearDepth, f: farDepth. - AZStd::array m_padding = {{0.f, 0.f}}; // explicit padding }; virtual ~EsmShadowmapsPass() = default; @@ -65,13 +62,6 @@ namespace AZ const Name& GetLightTypeName() const; - //! This sets the standard deviations of the Gaussian filter - //! for each cascade. - void SetFilterParameters(const AZStd::array_view& standardDeviations); - - //! This returns element count of filters. - AZStd::array_view GetFilterCounts() const; - //! This sets the buffer of the table which enable to get shadowmap index //! from the coordinate in the atlas. //! Note that shadowmpa index is shader light index for a spot light diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp index d3b5646e0b..dcf412c35d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp @@ -292,11 +292,6 @@ namespace AZ SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetShadowFilterMethod, method); } - void PointLightFeatureProcessor::SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle, boundaryWidthRadians); - } - void PointLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetFilteringSampleCount, count); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h index b784eb1bb5..54cb0303cc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h @@ -50,7 +50,6 @@ namespace AZ void SetShadowBias(LightHandle handle, float bias) override; void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; - void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; void SetPointData(LightHandle handle, const PointLightData& data) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 6452b312c8..da92cc04e7 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -186,17 +186,6 @@ namespace AZ::Render m_filterParameterNeedsUpdate = true; } - void ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle(ShadowId id, float boundaryWidthRadians) - { - AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetShadowBoundaryWidthAngle()."); - - ShadowData& shadowData = m_shadowData.GetElement(id.GetIndex()); - shadowData.m_boundaryScale = boundaryWidthRadians / 2.0f; - - m_shadowmapPassNeedsUpdate = true; - m_filterParameterNeedsUpdate = true; - } - void ProjectedShadowFeatureProcessor::SetFilteringSampleCount(ShadowId id, uint16_t count) { AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetFilteringSampleCount()."); @@ -368,14 +357,13 @@ namespace AZ::Render { if (m_filterParameterNeedsUpdate) { - UpdateStandardDeviations(); - UpdateFilterOffsetsCounts(); + UpdateEsmPassEnabled(); SetFilterParameterToPass(); m_filterParameterNeedsUpdate = false; } } - void ProjectedShadowFeatureProcessor::UpdateStandardDeviations() + void ProjectedShadowFeatureProcessor::UpdateEsmPassEnabled() { if (m_esmShadowmapsPasses.empty()) { @@ -383,24 +371,7 @@ namespace AZ::Render return; } - AZStd::vector standardDeviations(m_shadowProperties.GetDataCount()); - - for (uint32_t i = 0; i < m_shadowProperties.GetDataCount(); ++i) - { - ShadowProperty& shadowProperty = m_shadowProperties.GetDataVector().at(i); - const ShadowData& shadow = m_shadowData.GetElement(shadowProperty.m_shadowId.GetIndex()); - if (!FilterMethodIsEsm(shadow)) - { - continue; - } - const FilterParameter& filter = m_shadowData.GetElement(shadowProperty.m_shadowId.GetIndex()); - const float boundaryWidthAngle = shadow.m_boundaryScale * 2.0f; - const float fieldOfView = GetMax(shadowProperty.m_desc.m_fieldOfViewYRadians, MinimumFieldOfView); - const float ratioToEntireWidth = boundaryWidthAngle / fieldOfView; - const float widthInPixels = ratioToEntireWidth * filter.m_shadowmapSize; - standardDeviations.at(i) = widthInPixels / (2.0f * GaussianMathFilter::ReliableSectionFactor); - } - if (standardDeviations.empty()) + if (m_shadowProperties.GetDataCount() == 0) { for (EsmShadowmapsPass* esmPass : m_esmShadowmapsPasses) { @@ -411,50 +382,6 @@ namespace AZ::Render for (EsmShadowmapsPass* esmPass : m_esmShadowmapsPasses) { esmPass->SetEnabledComputation(true); - esmPass->SetFilterParameters(standardDeviations); - } - } - - void ProjectedShadowFeatureProcessor::UpdateFilterOffsetsCounts() - { - if (m_esmShadowmapsPasses.empty()) - { - AZ_Error("ProjectedShadowFeatureProcessor", false, "Cannot find a required pass."); - return; - } - - // Get array of filter counts for the camera view. - const AZStd::array_view filterCounts = m_esmShadowmapsPasses.front()->GetFilterCounts(); - - // Create array of filter offsets. - AZStd::vector filterOffsets; - filterOffsets.reserve(filterCounts.size()); - uint32_t filterOffset = 0; - for (const uint32_t count : filterCounts) - { - filterOffsets.push_back(filterOffset); - filterOffset += count; - } - - auto& shadowProperties = m_shadowProperties.GetDataVector(); - for (uint32_t i = 0; i < shadowProperties.size(); ++i) - { - ShadowProperty& shadowProperty = shadowProperties.at(i); - const ShadowId shadowId = shadowProperty.m_shadowId; - ShadowData& shadowData = m_shadowData.GetElement(shadowId.GetIndex()); - FilterParameter& filterData = m_shadowData.GetElement(shadowId.GetIndex()); - - if (FilterMethodIsEsm(shadowData)) - { - filterData.m_parameterOffset = filterOffsets[i]; - filterData.m_parameterCount = filterCounts[i]; - } - else - { - // If filter is not required, reset offsets and counts of filter in ESM data. - filterData.m_parameterOffset = 0; - filterData.m_parameterCount = 0; - } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h index 0b266b9a40..6269166827 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h @@ -49,7 +49,6 @@ namespace AZ::Render void SetShadowmapMaxResolution(ShadowId id, ShadowmapSize size) override; void SetShadowBias(ShadowId id, float bias) override; void SetShadowFilterMethod(ShadowId id, ShadowFilterMethod method) override; - void SetSofteningBoundaryWidthAngle(ShadowId id, float boundaryWidthRadians) override; void SetFilteringSampleCount(ShadowId id, uint16_t count) override; void SetShadowProperties(ShadowId id, const ProjectedShadowDescriptor& descriptor) override; const ProjectedShadowDescriptor& GetShadowProperties(ShadowId id) override; @@ -101,8 +100,7 @@ namespace AZ::Render //! Functions to update the parameter of Gaussian filter used in ESM. void UpdateFilterParameters(); - void UpdateStandardDeviations(); - void UpdateFilterOffsetsCounts(); + void UpdateEsmPassEnabled(); void SetFilterParameterToPass(); bool FilterMethodIsEsm(const ShadowData& shadowData) const; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h index 557e6b3dd2..72c4ef97a8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h @@ -120,13 +120,6 @@ namespace AZ //! Sets the filter method of shadows. virtual void SetShadowFilterMethod(ShadowFilterMethod method) = 0; - //! Gets the width of softening boundary between shadowed area and lit area in degrees. - virtual float GetSofteningBoundaryWidthAngle() const = 0; - - //! Sets the width of softening boundary between shadowed area and lit area in degrees. - //! 0 disables softening. - virtual void SetSofteningBoundaryWidthAngle(float degrees) = 0; - //! Gets the sample count for filtering of the shadow boundary. virtual uint32_t GetFilteringSampleCount() const = 0; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h index a6d3c6fbed..c76c922385 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h @@ -59,7 +59,6 @@ namespace AZ float m_bias = 0.1f; ShadowmapSize m_shadowmapMaxSize = ShadowmapSize::Size256; ShadowFilterMethod m_shadowFilterMethod = ShadowFilterMethod::None; - float m_boundaryWidthInDegrees = 0.25f; uint16_t m_filteringSampleCount = 12; float m_esmExponent = 87.0f; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h index 644856e768..a8088c63ac 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h @@ -153,15 +153,6 @@ namespace AZ //! @param method filter method. virtual void SetShadowFilterMethod(ShadowFilterMethod method) = 0; - //! This gets the width of boundary between shadowed area and lit area. - //! @return Boundary width. The shadow is gradually changed the degree of shadowed. - virtual float GetSofteningBoundaryWidth() const = 0; - - //! This specifies the width of boundary between shadowed area and lit area. - //! @param width Boundary width. The shadow is gradually changed the degree of shadowed. - //! If width == 0, softening edge is disabled. Units are in meters. - virtual void SetSofteningBoundaryWidth(float width) = 0; - //! This gets the sample count for filtering of the shadow boundary. //! @return Sample Count for filtering (up to 64) virtual uint32_t GetFilteringSampleCount() const = 0; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h index 0123d06275..a58acc0114 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h @@ -101,10 +101,6 @@ namespace AZ //! Method of shadow's filtering. ShadowFilterMethod m_shadowFilterMethod = ShadowFilterMethod::None; - //! Width of the boundary between shadowed area and lit one. - //! If this is 0, edge softening is disabled. Units are in meters. - float m_boundaryWidth = 0.03f; // 3cm - //! Sample Count for filtering (from 4 to 64) //! It is used only when the pixel is predicted as on the boundary. uint16_t m_filteringSampleCount = 32; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp index c7af44a28e..f0418a5024 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp @@ -36,7 +36,6 @@ namespace AZ ->Field("Shadow Bias", &AreaLightComponentConfig::m_bias) ->Field("Shadowmap Max Size", &AreaLightComponentConfig::m_shadowmapMaxSize) ->Field("Shadow Filter Method", &AreaLightComponentConfig::m_shadowFilterMethod) - ->Field("Softening Boundary Width", &AreaLightComponentConfig::m_boundaryWidthInDegrees) ->Field("Filtering Sample Count", &AreaLightComponentConfig::m_filteringSampleCount) ->Field("Esm Exponent", &AreaLightComponentConfig::m_esmExponent) ; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp index c0204ecac5..36cb2a7f5a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp @@ -74,8 +74,6 @@ namespace AZ::Render ->Event("SetShadowmapMaxSize", &AreaLightRequestBus::Events::SetShadowmapMaxSize) ->Event("GetShadowFilterMethod", &AreaLightRequestBus::Events::GetShadowFilterMethod) ->Event("SetShadowFilterMethod", &AreaLightRequestBus::Events::SetShadowFilterMethod) - ->Event("GetSofteningBoundaryWidthAngle", &AreaLightRequestBus::Events::GetSofteningBoundaryWidthAngle) - ->Event("SetSofteningBoundaryWidthAngle", &AreaLightRequestBus::Events::SetSofteningBoundaryWidthAngle) ->Event("GetFilteringSampleCount", &AreaLightRequestBus::Events::GetFilteringSampleCount) ->Event("SetFilteringSampleCount", &AreaLightRequestBus::Events::SetFilteringSampleCount) ->Event("GetEsmExponent", &AreaLightRequestBus::Events::GetEsmExponent) @@ -95,7 +93,6 @@ namespace AZ::Render ->VirtualProperty("ShadowBias", "GetShadowBias", "SetShadowBias") ->VirtualProperty("ShadowmapMaxSize", "GetShadowmapMaxSize", "SetShadowmapMaxSize") ->VirtualProperty("ShadowFilterMethod", "GetShadowFilterMethod", "SetShadowFilterMethod") - ->VirtualProperty("SofteningBoundaryWidthAngle", "GetSofteningBoundaryWidthAngle", "SetSofteningBoundaryWidthAngle") ->VirtualProperty("FilteringSampleCount", "GetFilteringSampleCount", "SetFilteringSampleCount") ->VirtualProperty("EsmExponent", "GetEsmExponent", "SetEsmExponent"); ; @@ -307,7 +304,6 @@ namespace AZ::Render m_lightShapeDelegate->SetShadowBias(m_configuration.m_bias); m_lightShapeDelegate->SetShadowmapMaxSize(m_configuration.m_shadowmapMaxSize); m_lightShapeDelegate->SetShadowFilterMethod(m_configuration.m_shadowFilterMethod); - m_lightShapeDelegate->SetSofteningBoundaryWidthAngle(m_configuration.m_boundaryWidthInDegrees); m_lightShapeDelegate->SetFilteringSampleCount(m_configuration.m_filteringSampleCount); m_lightShapeDelegate->SetEsmExponent(m_configuration.m_esmExponent); } @@ -506,20 +502,6 @@ namespace AZ::Render } } - float AreaLightComponentController::GetSofteningBoundaryWidthAngle() const - { - return m_configuration.m_boundaryWidthInDegrees; - } - - void AreaLightComponentController::SetSofteningBoundaryWidthAngle(float width) - { - m_configuration.m_boundaryWidthInDegrees = width; - if (m_lightShapeDelegate) - { - m_lightShapeDelegate->SetSofteningBoundaryWidthAngle(width); - } - } - uint32_t AreaLightComponentController::GetFilteringSampleCount() const { return m_configuration.m_filteringSampleCount; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h index 3bec61551f..cc6223e7e5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h @@ -82,8 +82,6 @@ namespace AZ void SetShadowmapMaxSize(ShadowmapSize size) override; ShadowFilterMethod GetShadowFilterMethod() const override; void SetShadowFilterMethod(ShadowFilterMethod method) override; - float GetSofteningBoundaryWidthAngle() const override; - void SetSofteningBoundaryWidthAngle(float width) override; uint32_t GetFilteringSampleCount() const override; void SetFilteringSampleCount(uint32_t count) override; float GetEsmExponent() const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp index 37d94f5ed1..9d384c2e24 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp @@ -37,7 +37,6 @@ namespace AZ ->Field("IsCascadeCorrectionEnabled", &DirectionalLightComponentConfig::m_isCascadeCorrectionEnabled) ->Field("IsDebugColoringEnabled", &DirectionalLightComponentConfig::m_isDebugColoringEnabled) ->Field("ShadowFilterMethod", &DirectionalLightComponentConfig::m_shadowFilterMethod) - ->Field("SofteningBoundaryWidth", &DirectionalLightComponentConfig::m_boundaryWidth) ->Field("PcfFilteringSampleCount", &DirectionalLightComponentConfig::m_filteringSampleCount) ->Field("ShadowReceiverPlaneBiasEnabled", &DirectionalLightComponentConfig::m_receiverPlaneBiasEnabled); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index fbc1ccc35d..78558cfc85 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -80,8 +80,6 @@ namespace AZ ->Event("SetDebugColoringEnabled", &DirectionalLightRequestBus::Events::SetDebugColoringEnabled) ->Event("GetShadowFilterMethod", &DirectionalLightRequestBus::Events::GetShadowFilterMethod) ->Event("SetShadowFilterMethod", &DirectionalLightRequestBus::Events::SetShadowFilterMethod) - ->Event("GetSofteningBoundaryWidth", &DirectionalLightRequestBus::Events::GetSofteningBoundaryWidth) - ->Event("SetSofteningBoundaryWidth", &DirectionalLightRequestBus::Events::SetSofteningBoundaryWidth) ->Event("GetFilteringSampleCount", &DirectionalLightRequestBus::Events::GetFilteringSampleCount) ->Event("SetFilteringSampleCount", &DirectionalLightRequestBus::Events::SetFilteringSampleCount) ->Event("GetShadowReceiverPlaneBiasEnabled", &DirectionalLightRequestBus::Events::GetShadowReceiverPlaneBiasEnabled) @@ -99,7 +97,6 @@ namespace AZ ->VirtualProperty("ViewFrustumCorrectionEnabled", "GetViewFrustumCorrectionEnabled", "SetViewFrustumCorrectionEnabled") ->VirtualProperty("DebugColoringEnabled", "GetDebugColoringEnabled", "SetDebugColoringEnabled") ->VirtualProperty("ShadowFilterMethod", "GetShadowFilterMethod", "SetShadowFilterMethod") - ->VirtualProperty("SofteningBoundaryWidth", "GetSofteningBoundaryWidth", "SetSofteningBoundaryWidth") ->VirtualProperty("FilteringSampleCount", "GetFilteringSampleCount", "SetFilteringSampleCount") ->VirtualProperty("ShadowReceiverPlaneBiasEnabled", "GetShadowReceiverPlaneBiasEnabled", "SetShadowReceiverPlaneBiasEnabled"); ; @@ -404,21 +401,6 @@ namespace AZ } } - float DirectionalLightComponentController::GetSofteningBoundaryWidth() const - { - return m_configuration.m_boundaryWidth; - } - - void DirectionalLightComponentController::SetSofteningBoundaryWidth(float width) - { - width = GetMin(Shadow::MaxSofteningBoundaryWidth, GetMax(0.f, width)); - m_configuration.m_boundaryWidth = width; - if (m_featureProcessor) - { - m_featureProcessor->SetShadowBoundaryWidth(m_lightHandle, width); - } - } - uint32_t DirectionalLightComponentController::GetFilteringSampleCount() const { return aznumeric_cast(m_configuration.m_filteringSampleCount); @@ -517,7 +499,6 @@ namespace AZ SetViewFrustumCorrectionEnabled(m_configuration.m_isCascadeCorrectionEnabled); SetDebugColoringEnabled(m_configuration.m_isDebugColoringEnabled); SetShadowFilterMethod(m_configuration.m_shadowFilterMethod); - SetSofteningBoundaryWidth(m_configuration.m_boundaryWidth); SetFilteringSampleCount(m_configuration.m_filteringSampleCount); SetShadowReceiverPlaneBiasEnabled(m_configuration.m_receiverPlaneBiasEnabled); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h index b8052bfc36..933f2705e7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h @@ -76,8 +76,6 @@ namespace AZ void SetDebugColoringEnabled(bool enabled) override; ShadowFilterMethod GetShadowFilterMethod() const override; void SetShadowFilterMethod(ShadowFilterMethod method) override; - float GetSofteningBoundaryWidth() const override; - void SetSofteningBoundaryWidth(float width) override; uint32_t GetFilteringSampleCount() const override; void SetFilteringSampleCount(uint32_t count) override; bool GetShadowReceiverPlaneBiasEnabled() const override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp index baf0cdced1..ebc79abca5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp @@ -147,14 +147,6 @@ namespace AZ::Render } } - void DiskLightDelegate::SetSofteningBoundaryWidthAngle(float widthInDegrees) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetSofteningBoundaryWidthAngle(GetLightHandle(), DegToRad(widthInDegrees)); - } - } - void DiskLightDelegate::SetFilteringSampleCount(uint32_t count) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h index e0fd16f6be..2be782c69c 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h @@ -44,7 +44,6 @@ namespace AZ void SetShadowBias(float bias) override; void SetShadowmapMaxSize(ShadowmapSize size) override; void SetShadowFilterMethod(ShadowFilterMethod method) override; - void SetSofteningBoundaryWidthAngle(float widthInDegrees) override; void SetFilteringSampleCount(uint32_t count) override; void SetEsmExponent(float exponent) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index 954ec4cad8..1e5b2580f7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -154,15 +154,6 @@ namespace AZ ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::AttributesAndValues) ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::ShadowsDisabled) - ->DataElement(Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_boundaryWidthInDegrees, "Softening boundary width", - "Width of the boundary between shadowed area and lit one. " - "Units are in degrees. " - "If this is 0, softening edge is disabled.") - ->Attribute(Edit::Attributes::Min, 0.f) - ->Attribute(Edit::Attributes::Max, 1.f) - ->Attribute(Edit::Attributes::Suffix, " deg") - ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) - ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsEsmDisabled) ->DataElement(Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_filteringSampleCount, "Filtering sample count", "This is only used when the pixel is predicted to be on the boundary. Specific to PCF and ESM+PCF.") ->Attribute(Edit::Attributes::Min, 4) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp index 2854244f6b..69ba295e9b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp @@ -133,15 +133,6 @@ namespace AZ ->EnumAttribute(ShadowFilterMethod::Esm, "ESM") ->EnumAttribute(ShadowFilterMethod::EsmPcf, "ESM+PCF") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->DataElement(Edit::UIHandlers::Slider, &DirectionalLightComponentConfig::m_boundaryWidth, "Softening boundary width", - "Width of the boundary between shadowed area and lit one. " - "Units are in meters. " - "If this is 0, softening edge is disabled.") - ->Attribute(Edit::Attributes::Min, 0.f) - ->Attribute(Edit::Attributes::Max, 0.1f) - ->Attribute(Edit::Attributes::Suffix, " m") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsEsmDisabled) ->DataElement(Edit::UIHandlers::Slider, &DirectionalLightComponentConfig::m_filteringSampleCount, "Filtering sample count", "This is used only when the pixel is predicted as on the boundary. " "Specific to PCF and ESM+PCF.") diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h index 2bd25b76a3..336c67f55d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h @@ -56,7 +56,6 @@ namespace AZ void SetShadowBias([[maybe_unused]] float bias) override {}; void SetShadowmapMaxSize([[maybe_unused]] ShadowmapSize size) override {}; void SetShadowFilterMethod([[maybe_unused]] ShadowFilterMethod method) override {}; - void SetSofteningBoundaryWidthAngle([[maybe_unused]] float widthInDegrees) override {}; void SetFilteringSampleCount([[maybe_unused]] uint32_t count) override {}; void SetEsmExponent([[maybe_unused]] float esmExponent) override{}; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h index 6d08971542..9bb8188898 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h @@ -75,8 +75,6 @@ namespace AZ virtual void SetShadowmapMaxSize(ShadowmapSize size) = 0; //! Sets the filter method for the shadow virtual void SetShadowFilterMethod(ShadowFilterMethod method) = 0; - //! Sets the width of boundary between shadowed area and lit area in degrees. - virtual void SetSofteningBoundaryWidthAngle(float widthInDegrees) = 0; //! Sets the sample count for filtering of the shadow boundary, max 64. virtual void SetFilteringSampleCount(uint32_t count) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff between light and shadow. diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp index 8853db5751..661b0c6b25 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp @@ -92,14 +92,6 @@ namespace AZ::Render } } - void SphereLightDelegate::SetSofteningBoundaryWidthAngle(float widthInDegrees) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetSofteningBoundaryWidthAngle(GetLightHandle(), DegToRad(widthInDegrees)); - } - } - void SphereLightDelegate::SetFilteringSampleCount(uint32_t count) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h index e2903b2d72..8bdee2442a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h @@ -34,7 +34,6 @@ namespace AZ void SetShadowBias(float bias) override; void SetShadowmapMaxSize(ShadowmapSize size) override; void SetShadowFilterMethod(ShadowFilterMethod method) override; - void SetSofteningBoundaryWidthAngle(float widthInDegrees) override; void SetFilteringSampleCount(uint32_t count) override; void SetEsmExponent(float esmExponent) override;