From 6b3abe3c56d5e267fc61c8341b9dcbf05051d876 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Sat, 24 Apr 2021 10:10:02 -0700 Subject: [PATCH 001/112] Cherrypick from 1.0 branch of... 6c2a243cdc3dbe8cf5cb2ec9063585255607f8e5 LYN-2905 Script Canvas: Saving a graph that contains an Item Variable crashes the Editor Added a check for m_shaderAsset.IsReady() before trying to use the asset data. Also added a check before calling BlockUntilLoadComplete() to prevent reporting an error message unnecessarily. --- .../RPI.Reflect/Material/ShaderCollection.cpp | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp index 4cae8af48e..933eccbd44 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp @@ -40,13 +40,22 @@ namespace AZ // Dependent asset references aren't guaranteed to finish loading by the time this asset is serialized, only by // the time this asset load is completed. But since the data is needed here, we will deliberately block until the // shader asset has finished loading. - shaderVariantReference->m_shaderAsset.QueueLoad(); - shaderVariantReference->m_shaderAsset.BlockUntilLoadComplete(); + if (shaderVariantReference->m_shaderAsset.QueueLoad()) + { + shaderVariantReference->m_shaderAsset.BlockUntilLoadComplete(); + } - shaderVariantReference->m_shaderOptionGroup = ShaderOptionGroup{ - shaderVariantReference->m_shaderAsset->GetShaderOptionGroupLayout(), - shaderVariantReference->m_shaderVariantId - }; + if (shaderVariantReference->m_shaderAsset.IsReady()) + { + shaderVariantReference->m_shaderOptionGroup = ShaderOptionGroup{ + shaderVariantReference->m_shaderAsset->GetShaderOptionGroupLayout(), + shaderVariantReference->m_shaderVariantId + }; + } + else + { + shaderVariantReference->m_shaderOptionGroup = {}; + } } }; From 9db65478ee773d9b350b3c03a76598c3caf55ecc Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Sat, 24 Apr 2021 11:14:40 -0700 Subject: [PATCH 002/112] LYN-2905 Script Canvas: Saving a graph that contains an Item Variable crashes the Editor Set the reflection name for ShaderCollection::Item to "ShaderCollectionItem" so it doesn't show up as just "Item" in Script Canvas. Note that this change was made in main only, not in the 1.0 branch, to de-risk the beta branch. Testing: Ran the repro steps for the bug, and ran the ShaderManagementConsole's GenerateShaderVariantListForMaterials.py script successfully. --- .../RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp index 933eccbd44..7fc75f67fe 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp @@ -91,7 +91,7 @@ namespace AZ if (BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->Class() + behaviorContext->Class("ShaderCollectionItem") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Category, "Shader") ->Attribute(AZ::Script::Attributes::Module, "shader") From f2ce91fb44d53c25a5191c8fc587cc5f6a0bba1a Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 27 Apr 2021 14:57:51 -0500 Subject: [PATCH 003/112] AtomDebugDisplayViewportInterface - Fix Crash if FontQueryInterface in null --- .../AtomDebugDisplayViewportInterface.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 77f15284f1..690963e26b 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -1234,8 +1234,15 @@ namespace AZ::AtomBridge int srcOffsetX [[maybe_unused]], int srcOffsetY [[maybe_unused]]) { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) + // abort draw if font draw interface is missing + if (!fontDrawInterface) { return; } @@ -1263,8 +1270,15 @@ namespace AZ::AtomBridge const char* text, bool center) { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) + // abort draw if font draw interface is missing + if (!fontDrawInterface) { return; } From d35adce246cc8a817d36271dbce2a7e27bbf84e9 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 11:46:08 +0100 Subject: [PATCH 004/112] adding support for non-uniform scale for decals --- .../Decals/DecalFeatureProcessorInterface.h | 3 ++- .../Source/Decals/DecalFeatureProcessor.cpp | 4 +-- .../Source/Decals/DecalFeatureProcessor.h | 3 ++- .../DecalTextureArrayFeatureProcessor.cpp | 5 ++-- .../DecalTextureArrayFeatureProcessor.h | 3 ++- .../Decals/DecalComponentController.cpp | 25 ++++++++++++++++++- .../Source/Decals/DecalComponentController.h | 9 +++++++ 7 files changed, 44 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h index 214feb2040..2ec7b535d0 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h @@ -88,7 +88,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - virtual void SetDecalTransform(DecalHandle handle, const AZ::Transform& world) = 0; + virtual void SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) = 0; //! Sets the material information for this decal virtual void SetDecalMaterial(DecalHandle handle, const AZ::Data::AssetId) = 0; diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index 7abc6698fa..b4ce2e6cc9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -262,7 +262,7 @@ namespace AZ } } - void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world) + void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, const AZ::Vector3& nonUniformScale) { // https://jira.agscollab.com/browse/ATOM-4330 // Original Open 3D Engine uploads a 4x4 matrix rather than quaternion, rotation, scale. @@ -274,7 +274,7 @@ namespace AZ if (handle.IsValid()) { Quaternion orientation = world.GetRotation(); - Vector3 scale = world.GetScale(); + Vector3 scale = world.GetScale() * nonUniformScale; SetDecalHalfSize(handle, scale); SetDecalPosition(handle, world.GetTranslation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h index 9c4acf6322..5a37a5cf11 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h @@ -73,7 +73,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - void SetDecalTransform(DecalHandle handle, const AZ::Transform& world) override; + void SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) override; //! Sets the material information for this decal void SetDecalMaterial(DecalHandle handle, const AZ::Data::AssetId) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 9d1ea4e680..1f1bcc21b2 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -269,11 +269,12 @@ namespace AZ } } - void DecalTextureArrayFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world) + void DecalTextureArrayFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale) { if (handle.IsValid()) { - SetDecalHalfSize(handle, world.GetScale()); + SetDecalHalfSize(handle, nonUniformScale * world.GetScale()); SetDecalPosition(handle, world.GetTranslation()); SetDecalOrientation(handle, world.GetRotation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 7ab073c7f9..50d51fbe7f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -82,7 +82,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - void SetDecalTransform(const DecalHandle handle, const AZ::Transform& world) override; + void SetDecalTransform(const DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) override; //! Sets the material information for this decal void SetDecalMaterial(const DecalHandle handle, const AZ::Data::AssetId id) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp index 22a7e1c6c0..3c748e352e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp @@ -75,6 +75,12 @@ namespace AZ incompatible.push_back(AZ_CRC_CE("DecalService")); } + void DecalComponentController::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + dependent.push_back(AZ_CRC_CE("TransformService")); + dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + DecalComponentController::DecalComponentController(const DecalComponentConfig& config) : m_configuration(config) { @@ -90,6 +96,11 @@ namespace AZ m_handle = m_featureProcessor->AcquireDecal(); } + m_cachedNonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(m_cachedNonUniformScale, m_entityId, &AZ::NonUniformScaleRequests::GetScale); + AZ::NonUniformScaleRequestBus::Event(m_entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent, + m_nonUniformScaleChangedHandler); + AZ::Transform local, world; AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::GetLocalAndWorld, local, world); OnTransformChanged(local, world); @@ -103,6 +114,7 @@ namespace AZ { DecalRequestBus::Handler::BusDisconnect(m_entityId); TransformNotificationBus::Handler::BusDisconnect(m_entityId); + m_nonUniformScaleChangedHandler.Disconnect(); if (m_featureProcessor) { m_featureProcessor->ReleaseDecal(m_handle); @@ -125,7 +137,18 @@ namespace AZ { if (m_featureProcessor) { - m_featureProcessor->SetDecalTransform(m_handle, world); + m_featureProcessor->SetDecalTransform(m_handle, world, m_cachedNonUniformScale); + } + } + + void DecalComponentController::HandleNonUniformScaleChange(const AZ::Vector3& nonUniformScale) + { + m_cachedNonUniformScale = nonUniformScale; + if (m_featureProcessor) + { + AZ::Transform world = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(world, m_entityId, &AZ::TransformBus::Events::GetWorldTM); + m_featureProcessor->SetDecalTransform(m_handle, world, nonUniformScale); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h index dc6b6e70ea..14204c43dc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,7 @@ namespace AZ static void Reflect(AZ::ReflectContext* context); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); DecalComponentController() = default; DecalComponentController(const DecalComponentConfig& config); @@ -64,11 +66,18 @@ namespace AZ void OpacityChanged(); void SortKeyChanged(); void MaterialChanged(); + void HandleNonUniformScaleChange(const AZ::Vector3& nonUniformScale); DecalComponentConfig m_configuration; DecalFeatureProcessorInterface* m_featureProcessor = nullptr; DecalFeatureProcessorInterface::DecalHandle m_handle; EntityId m_entityId; + AZ::Vector3 m_cachedNonUniformScale = AZ::Vector3::CreateOne(); + + AZ::NonUniformScaleChangedEvent::Handler m_nonUniformScaleChangedHandler + { + [&](const AZ::Vector3& nonUniformScale) { HandleNonUniformScaleChange(nonUniformScale); } + }; }; } // namespace Render } // AZ namespace From 64738c0fc1576b4e9beb0f4333182f318d03a09c Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 11:47:20 +0100 Subject: [PATCH 005/112] adding non-uniform scale service as dependency for mesh component controller --- .../CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index 9d2196de2b..0957abee65 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -131,6 +131,7 @@ namespace AZ void MeshComponentController::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { dependent.push_back(AZ_CRC("TransformService", 0x8ee22c50)); + dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); } void MeshComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) From 1222286e307d24064a823699c703507451285778 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 14:36:47 +0100 Subject: [PATCH 006/112] removing URL --- .../Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index b4ce2e6cc9..817897dd62 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -264,7 +264,7 @@ namespace AZ void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, const AZ::Vector3& nonUniformScale) { - // https://jira.agscollab.com/browse/ATOM-4330 + // ATOM-4330 // Original Open 3D Engine uploads a 4x4 matrix rather than quaternion, rotation, scale. // That is more memory but less calculation because it is doing a matrix inverse rather than a polar decomposition // I've done some experiments and uploading a 3x4 transform matrix with 3x3 matrix inverse should be possible From d433cd623becb2606ff764bb67a4f11b86ea280c Mon Sep 17 00:00:00 2001 From: srikappa Date: Thu, 29 Apr 2021 17:02:44 -0700 Subject: [PATCH 007/112] Fix undo for nested prefab creation by providing link patches to the undo node --- .../Prefab/PrefabPublicHandler.cpp | 52 +++++++++++++++++-- .../Prefab/PrefabPublicHandler.h | 11 ++++ .../Prefab/PrefabSystemComponent.cpp | 5 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 10 ++-- .../AzToolsFramework/Prefab/PrefabUndo.h | 4 +- .../Prefab/PrefabUndoHelpers.cpp | 8 ++- .../Prefab/PrefabUndoHelpers.h | 4 +- 7 files changed, 75 insertions(+), 19 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1e9cc35230..1b4bf9f50c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -96,9 +96,12 @@ namespace AzToolsFramework // target templates of the other instances. for (auto& nestedInstance : instances) { - PrefabUndoHelpers::RemoveLink( - nestedInstance->GetTemplateId(), commonRootEntityOwningInstance->get().GetTemplateId(), - nestedInstance->GetInstanceAlias(), nestedInstance->GetLinkId(), undoBatch.GetUndoBatch()); + PrefabOperationResult removeLinkResult = RemoveLink( + nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); + if (!removeLinkResult.IsSuccess()) + { + return removeLinkResult; + } } PrefabUndoHelpers::UpdatePrefabInstance( @@ -287,6 +290,49 @@ namespace AzToolsFramework m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); } + PrefabOperationResult PrefabPublicHandler::RemoveLink( + AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch) + { + LinkReference nestedInstanceLink = m_prefabSystemComponentInterface->FindLink(sourceInstance->GetLinkId()); + if (!nestedInstanceLink.has_value()) + { + AZ_Assert(false, "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); + return AZ::Failure( + AZStd::string("A valid link was not found for one of the instances provided as input for the CreatePrefab operation.")); + } + + PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom(); + if (!nestedInstanceLinkDom.has_value()) + { + AZ_Assert( + false, + "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); + return AZ::Failure(AZStd::string("A valid DOM was not found for the link corresponding to one of the instances " + "provided as input for the CreatePrefab operation.")); + } + + PrefabDomValueReference nestedInstanceLinkPatches = + PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName); + if (!nestedInstanceLinkPatches.has_value()) + { + AZ_Assert( + false, + "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); + return AZ::Failure(AZStd::string("A valid DOM for patcheswas not found for the link corresponding to one of the instances " + "provided as input for the CreatePrefab operation.")); + } + + PrefabDom patchesCopyForUndoSupport; + patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); + PrefabUndoHelpers::RemoveLink( + sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), + patchesCopyForUndoSupport, undoBatch); + + return AZ::Success(); + } + PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) { auto templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(filePath.c_str()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index e83513dbff..8d27603e8d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -82,6 +82,17 @@ namespace AzToolsFramework const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId); + /** + * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. + * + * \param sourceInstance The instance corresponding to the source template of the link to be removed. + * \param targetTemplateId The id of the target template of the link to be removed. + * \param undoBatch The undo batch to set as parent for this remove link action. + * \return PrefabOperationResult Indicates whether the removal of link was successful. + */ + PrefabOperationResult RemoveLink( + AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch); + /** * Given a list of entityIds, finds the prefab instance that owns the common root entity of the entityIds. * diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 3f660bb73b..c6a95b01fe 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -663,8 +663,9 @@ namespace AzToolsFramework newLink.SetSourceTemplateId(linkSourceId); newLink.SetInstanceName(instanceAlias.c_str()); newLink.GetLinkDom().SetObject(); - newLink.GetLinkDom().AddMember(rapidjson::StringRef(PrefabDomUtils::SourceName), - rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); + newLink.GetLinkDom().AddMember( + rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), + newLink.GetLinkDom().GetAllocator()); if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty())) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index ea3fa5d84d..ad0cdc166a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -113,7 +113,7 @@ namespace AzToolsFramework , m_sourceId(InvalidTemplateId) , m_instanceAlias("") , m_linkId(InvalidLinkId) - , m_linkDom(PrefabDom()) + , m_linkPatches(PrefabDom()) , m_linkStatus(LinkStatus::LINKSTATUS) { m_prefabSystemComponentInterface = AZ::Interface::Get(); @@ -124,7 +124,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkDom, + PrefabDomReference linkPatches, const LinkId linkId) { m_targetId = targetId; @@ -132,9 +132,9 @@ namespace AzToolsFramework m_instanceAlias = instanceAlias; m_linkId = linkId; - if (linkDom.has_value()) + if (linkPatches.has_value()) { - m_linkDom = AZStd::move(linkDom->get()); + m_linkPatches = AZStd::move(linkPatches->get()); } //if linkId is invalid, set as ADD @@ -193,7 +193,7 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkDom, m_linkId); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); } void PrefabUndoInstanceLink::RemoveLink() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 0d15d707d2..49bae4eda0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -101,7 +101,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkDom = PrefabDomReference(), + PrefabDomReference linkPatches = PrefabDomReference(), const LinkId linkId = InvalidLinkId); void Undo() override; @@ -120,7 +120,7 @@ namespace AzToolsFramework InstanceAlias m_instanceAlias; LinkId m_linkId; - PrefabDom m_linkDom; //data for delete/update + PrefabDom m_linkPatches; //data for delete/update LinkStatus m_linkStatus; PrefabSystemComponentInterface* m_prefabSystemComponentInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 2062e8b12c..24eb71e055 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -46,13 +46,11 @@ namespace AzToolsFramework } void RemoveLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, - LinkId linkId, UndoSystem::URSequencePoint* undoBatch) + TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, + PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch) { auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link"); - PrefabDom emptyLinkDom; - linkRemoveUndo->Capture( - targetTemplateId, sourceTemplateId, instanceAlias, emptyLinkDom, linkId); + linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, linkPatches, linkId); linkRemoveUndo->SetParent(undoBatch); linkRemoveUndo->Redo(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h index 74532b87a2..6429df3b04 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h @@ -25,8 +25,8 @@ namespace AzToolsFramework TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch); void RemoveLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, - LinkId linkId, UndoSystem::URSequencePoint* undoBatch); + TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, + PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch); } } // namespace Prefab } // namespace AzToolsFramework From d1801bbe47dc4fc827b9d5e0eaf55e271b7cd897 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Fri, 30 Apr 2021 00:39:48 -0700 Subject: [PATCH 008/112] ATOM-14495 POM Height Bias Added parallax "Height Offset" properties to StandardPBR and EnhancedPBR. - Refactored depth pass and shadow pass shaders to use the GetParallaxInput utility. - Updated EnhancedPBR.materialtype to match the parallax controls and functors of StandardPBR.materialtype. - Updated EnhancedPBR's shadow pass shader to apply a ShadowMapDepthBias because I noticed StandardPBR is doing this, so I made them match. - Updated StandardPBR and EnhancedPBR to both use the depth offset property, as well as heightmap clipping debug view. - Note that depth offset is not supported in StandardMultilayerPBR yet, it's hard-coded to 0 for now. - Note that I plan to rename a lot of the "depth" terms to "heightmap" or "displacement" in an upcoming commit. --- .../Materials/Types/EnhancedPBR.materialtype | 100 +++++++-------- .../Types/EnhancedPBR_DepthPass_WithPS.azsl | 26 +--- .../Types/EnhancedPBR_ForwardPass.azsl | 11 +- .../Types/EnhancedPBR_Shadowmap_WithPS.azsl | 26 +--- .../Types/MaterialInputs/ParallaxInput.azsli | 38 ++++-- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 3 +- .../StandardMultilayerPBR_ForwardPass.azsl | 5 +- ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 5 +- .../Materials/Types/StandardPBR.materialtype | 28 +++- .../Types/StandardPBR_DepthPass_WithPS.azsl | 30 +---- .../Types/StandardPBR_ForwardPass.azsl | 12 +- .../Types/StandardPBR_ParallaxState.lua | 4 +- .../Types/StandardPBR_Shadowmap_WithPS.azsl | 25 +--- .../Atom/Features/ParallaxMapping.azsli | 121 ++++++++++++++---- .../Types/AutoBrick_ForwardPass.azsl | 19 +-- 15 files changed, 253 insertions(+), 200 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index cb66a987ae..954e01c592 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -946,19 +946,6 @@ "type": "Bool", "defaultValue": false }, - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", - "type": "Float", - "defaultValue": 0.0, - "min": 0.0, - "softMax": 0.1, - "connection": { - "type": "ShaderInput", - "id": "m_depthFactor" - } - }, { "id": "textureMap", "displayName": "Texture Map", @@ -981,6 +968,32 @@ "id": "m_parallaxUvIndex" } }, + { + "id": "factor", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", + "type": "Float", + "defaultValue": 0.0, + "min": 0.0, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthFactor" + } + }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -1026,6 +1039,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "subsurfaceScattering": [ @@ -1714,22 +1738,6 @@ "shaderOption": "o_emissive_useTexture" } }, - { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "parallax.textureMap", - "dependentProperties": ["parallax.textureMapUv"], - "useTextureProperty": "parallax.enable", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS", - "Shadowmap_WithPS", - "DepthPass_WithPS" - ], - "shaderOption": "o_parallax_feature_enabled" - } - }, { // See the comment above for details. "type": "UseTexture", @@ -1813,34 +1821,6 @@ ] } }, - { - // Controls visibility for properties in the editor. - // @param actions - a list of actions that are executed in order. visibility will be set when triggerProperty hits the triggerValue. - // @param affectedProperties - the properties that are affected by actions. - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "parallax.enable", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "parallax.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "parallax.factor", - "parallax.textureMap", - "parallax.invert", - "parallax.algorithm", - "parallax.quality", - "parallax.pdo" - ] - } - }, { "type": "UpdatePropertyVisibility", "args": { @@ -2076,6 +2056,12 @@ ] } }, + { + "type": "Lua", + "args": { + "file": "StandardPBR_ParallaxState.lua" + } + }, { "type": "Lua", "args": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl index 81601860ed..5d6c0fafd8 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl @@ -90,30 +90,12 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 27d7d7f65c..7d50cbf69b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -115,6 +115,8 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- depth = IN.m_position.z; + + bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) @@ -126,9 +128,9 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Apply second part of the offset to the detail UV (see comment above) IN.m_detailUv[MaterialSrg::m_parallaxUvIndex] -= IN.m_uv[MaterialSrg::m_parallaxUvIndex]; @@ -186,6 +188,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 baseColor = GetDetailedBaseColorInput( MaterialSrg::m_baseColorMap, MaterialSrg::m_sampler, baseColorUv, o_baseColor_useTexture, MaterialSrg::m_baseColor, MaterialSrg::m_baseColorFactor, o_baseColorTextureBlendMode, MaterialSrg::m_detail_baseColor_texture, MaterialSrg::m_sampler, detailUv, o_detail_baseColor_useTexture, detailLayerBaseColorFactor); + + if(o_parallax_highlightClipping && displacementIsClipped) + { + baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl index f1021e354b..e344886c4b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl @@ -98,35 +98,21 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) { + static const float ShadowMapDepthBias = 0.000001; + // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - dirToCamera, - tangent, - bitangent, - IN.m_normal, - uvMatrix); + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + OUT.m_depth += ShadowMapDepthBias; } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli index edee4c3c07..ab601429e8 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli @@ -24,16 +24,15 @@ #define COMMON_SRG_INPUTS_PARALLAX(prefix) \ Texture2D prefix##m_depthMap; \ float prefix##m_depthFactor; \ +float prefix##m_depthOffset; \ bool prefix##m_depthInverted; #define COMMON_OPTIONS_PARALLAX(prefix) \ option bool prefix##o_useDepthMap; -option bool o_parallax_feature_enabled; - -void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, - inout float2 uv, inout float3 worldPosition, inout float depth) + inout float2 uv, inout float3 worldPosition, inout float depth, out bool isClipped) { if(o_parallax_feature_enabled) { @@ -49,20 +48,22 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep dirToCamera = ViewSrg::m_worldPosition.xyz - worldPosition; } - float3 tangentOffset = GetParallaxOffset( depthFactor, - uv, - dirToCamera, - tangent, - bitangent, - normal, - uvMatrix); + ParallaxOffset tangentOffset = GetParallaxOffset( depthFactor, + depthOffset, + uv, + dirToCamera, + tangent, + bitangent, + normal, + uvMatrix); - uv += tangentOffset.xy; + uv += tangentOffset.m_offsetTS.xy; + isClipped = tangentOffset.m_isClipped; if(o_parallax_enablePixelDepthOffset) { PixelDepthOffset pdo = CalcPixelDepthOffset(depthFactor, - tangentOffset, + tangentOffset.m_offsetTS, worldPosition, tangent, bitangent, @@ -70,9 +71,20 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep uvMatrixInverse, objectWorldMatrix, ViewSrg::m_viewProjectionMatrix); + depth = pdo.m_depth; + worldPosition = pdo.m_worldPosition; } + } } +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, + float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, + inout float2 uv, inout float3 worldPosition, inout float depth) +{ + bool isClipped; + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depth, isClipped); +} + diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index 074b9dce26..8e25292e9c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -126,7 +126,8 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index a7338188a2..05a40d0f9d 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -163,8 +163,9 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 1274e07f7d..0c9c186a11 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -124,8 +124,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index e071a793a5..a74ceb1783 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -910,8 +910,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -921,6 +921,19 @@ "id": "m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -966,6 +979,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "subsurfaceScattering": [ diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl index 2e64f5102a..3c04e9b391 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl @@ -91,31 +91,15 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - + float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 4c3da2b7d0..d55b865a27 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -106,15 +106,18 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- depth = IN.m_position.z; + + bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) { + float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -150,6 +153,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 sampledColor = GetBaseColorInput(MaterialSrg::m_baseColorMap, MaterialSrg::m_sampler, baseColorUv, MaterialSrg::m_baseColor.rgb, o_baseColor_useTexture); float3 baseColor = BlendBaseColor(sampledColor, MaterialSrg::m_baseColor.rgb, MaterialSrg::m_baseColorFactor, o_baseColorTextureBlendMode, o_baseColor_useTexture); + if(o_parallax_highlightClipping && displacementIsClipped) + { + baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + } + // ------- Metallic ------- float metallic = 0; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua index bf1b59616a..0287e1105e 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua @@ -41,8 +41,10 @@ function ProcessEditor(context) if(not enable or textureMap == nil) then visibility = MaterialPropertyVisibility_Hidden end - + context:SetMaterialPropertyVisibility("parallax.factor", visibility) + context:SetMaterialPropertyVisibility("parallax.offset", visibility) + context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) context:SetMaterialPropertyVisibility("parallax.invert", visibility) context:SetMaterialPropertyVisibility("parallax.algorithm", visibility) context:SetMaterialPropertyVisibility("parallax.quality", visibility) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl index 4decbcd0df..8f33b4cec6 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl @@ -107,31 +107,14 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - dirToCamera, - tangent, - bitangent, - IN.m_normal, - uvMatrix); + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - - OUT.m_depth = pdo.m_depth + ShadowMapDepthBias; + OUT.m_depth += ShadowMapDepthBias; } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 8a6b5c479a..8027443f9a 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -18,6 +18,9 @@ option bool o_parallax_enablePixelDepthOffset; option enum class ParallaxAlgorithm {Basic, Steep, POM, Relief, Contact} o_parallax_algorithm; option enum class ParallaxQuality {Low, Medium, High, Ultra} o_parallax_quality; + +option bool o_parallax_feature_enabled; +option bool o_parallax_highlightClipping; option bool o_parallax_shadow; //! The client shader must define this function. @@ -34,23 +37,49 @@ float SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler return abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); } +float GetClampedDepth(float minSampledDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +{ + float sampledDepthValue = GetDepth(uv, uv_ddx, uv_ddy); + sampledDepthValue = max(sampledDepthValue, minSampledDepth); + return sampledDepthValue; +} + +struct ParallaxOffset +{ + float3 m_offsetTS; //!< represents the intersection point relative to the geometry surface, in tangent space. + bool m_isClipped; //!< Indicates whether the result is being clipped by the geometry surface, mainly for debug rendering. Only set when o_parallax_highlightClipping is true. +}; + // dirToCameraTS should be in tangent space and normalized // From Reat-Time Rendering 3rd edition, p.192 -float3 BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) +ParallaxOffset BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) { // the amount to shift float2 delta = dirToCameraTS.xy * GetDepth(uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; - float3 offset = float3(0,0,0); - offset.xy -= delta; - return offset; + ParallaxOffset result; + + result.m_offsetTS = float3(0,0,0); + result.m_offsetTS.xy -= delta; + result.m_isClipped = false; + return result; } -// dirToCameraTS and dirToLightTS should be in tangent space and normalized -// Adapt from CryEngine shader shadelib.cfi and POM function in https://github.com/a-riccardi/shader-toy +// Performs ray intersection against a surface with a heightmap. +// Adapted from CryEngine shader shadelib.cfi and POM function in https://github.com/a-riccardi/shader-toy // check https://github.com/UPBGE/blender/issues/1009 for more details. -float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, int numSteps, inout float parallaxShadowAttenuation) +// @param depthFactor - scales the heightmap in tangent space units (which normally ends up being world units). +// @param depthOffset - offsets the heighmap up or down in tangent space units (which normally ends up being world units). +// @param uv - the UV coordinates on the surface, where the search will begin, used to sample the heightmap. +// @param dirToCameraTS - normalized direction to the camera, in tangent space. +// @param dirToLightTS - normalized direction to a light source, in tangent space, for self-shadowing (if enabled via o_parallax_shadow). +// @param numSteps - the number of steps to take when marching along the ray searching for intersection. +// @param parallaxShadowAttenuation - returns a factor for attenuating a light source, for self-shadowing (if enabled via o_parallax_shadow). +ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, int numSteps, inout float parallaxShadowAttenuation) { + ParallaxOffset result; + result.m_isClipped = false; + float dirToCameraZInverse = 1.0 / dirToCameraTS.z; float step = 1.0 / numSteps; float currentStep = 0.0; @@ -60,22 +89,41 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT float2 ddx_uv = ddx_fine(uv); float2 ddy_uv = ddy_fine(uv); + + // This is the relative position at which we begin searching for intersection. + // It is adjusted according to the depthOffset, raising or lowering the whole surface by depthOffset units. + float3 parallaxOffset = dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; + + // Note that depthOffset can raise the heightmap toward (and potentially above) the surface of the mesh. + // We will clamp the heightmap samples to prevent displacements that lie above the surface, which would cause various + // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax + // surfaces disappearing at low angles. + float minSampledDepth = depthOffset / depthFactor; + minSampledDepth = clamp(minSampledDepth, 0, 1); - float currentSample = GetDepth(uv, ddx_uv, ddy_uv); + // Get an initial heightmap sample to start the intersection search, starting at our initial parallaxOffset position. + float currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); float prevSample; - float3 parallaxOffset = float3(0,0,0); + + // Note that when depthOffset > 0, we could actually narrow the search so that instead of going through the entire [0,1] range + // of the heightmap, we could go through the range [minSampledDepth,1]. This would give more accurate results and fewer artifacts + // in case where depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. - // find the intersect step + // Do a basic search for the intersect step while(currentSample > currentStep) { currentStep += step; parallaxOffset += delta; + prevSample = currentSample; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } + // Depending on the algorithm, we refine the result of the above search switch(o_parallax_algorithm) { + case ParallaxAlgorithm::Steep: + break; // This algorithm just relies on the course intersection test loop above case ParallaxAlgorithm::POM: { if(currentStep > 0.0) @@ -108,7 +156,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxOffset += reliefDelta * depthSign; currentStep += reliefStep * depthSign; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -136,7 +184,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxOffset += adjustedDelta; prevSample = currentSample; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -144,6 +192,23 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT default: break; } + + // Even though we do a bunch of clamping above when calling GetClampedDepth(), there are still cases where the parallax offset + // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset>1. + if(parallaxOffset.z > 0.0) + { + result.m_isClipped = o_parallax_highlightClipping; + parallaxOffset = float3(0,0,0); + } + // Extra check to report whether the heightmap is clipped. Inaccuracies in the intersection search make it difficult to rely on + // parallaxOffset.z to determine whether clipping has occurred. The most accurate way to report clipping is to sample the + // heightmap one last time at the final adjusted UV. Since that's expensive, we only do it when the o_parallax_highlightClipping + // option is set. + else if (o_parallax_highlightClipping) + { + float sampledDepthValue = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + result.m_isClipped = sampledDepthValue < minSampledDepth; + } if(o_parallax_shadow && any(dirToLightTS)) { @@ -168,7 +233,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT } shadowUV += shadowDelta; - currentSample = GetDepth(shadowUV, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, shadowUV, ddx_uv, ddy_uv); currentStep -= step; } @@ -181,12 +246,13 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxShadowAttenuation = 1; } } - - return parallaxOffset; + + result.m_offsetTS = parallaxOffset; + return result; } // return offset in tangent space -float3 CalculateParallaxOffset(float depthFactor, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, inout float parallaxShadowAttenuation) +ParallaxOffset CalculateParallaxOffset(float depthFactor, float depthOffset, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, inout float parallaxShadowAttenuation) { if(o_parallax_algorithm == ParallaxAlgorithm::Basic) { @@ -194,27 +260,34 @@ float3 CalculateParallaxOffset(float depthFactor, float2 uv, float3 dirToCameraT } else { - float3 parallaxOffset; + ParallaxOffset parallaxOffset; switch(o_parallax_quality) { case ParallaxQuality::Low: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 16, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 16, parallaxShadowAttenuation); break; case ParallaxQuality::Medium: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 32, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 32, parallaxShadowAttenuation); break; case ParallaxQuality::High: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 64, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 64, parallaxShadowAttenuation); break; case ParallaxQuality::Ultra: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 128, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 128, parallaxShadowAttenuation); break; } return parallaxOffset; } } -float3 GetParallaxOffset( float depthFactor, +// Performs ray intersection against a surface with a heightmap, to determine an offset amount required for a parallax effect. +// @param depthFactor - scales the heightmap in tangent space units (which normally ends up being world units). +// @param depthOffset - offsets the heighmap up or down in tangent space units (which normally ends up being world units). +// @param uv - the UV coordinates on the surface, where the search will begin, used to sample the heightmap. +// @param dirToCameraTS - normalized direction to the camera, in tangent space. +// @param dirToLightTS - normalized direction to a light source, in tangent space, for self-shadowing (if enabled via o_parallax_shadow). +ParallaxOffset GetParallaxOffset( float depthFactor, + float depthOffset, float2 uv, float3 dirToCameraWS, float3 tangentWS, @@ -236,7 +309,7 @@ float3 GetParallaxOffset( float depthFactor, float4 dirToCameraTransformed = mul(uv3DTransform, float4(dirToCameraTS, 0.0)); float dummy = 1; - return CalculateParallaxOffset(depthFactor, uv, normalize(dirToCameraTransformed.xyz), float3(0,0,0), dummy); + return CalculateParallaxOffset(depthFactor, depthOffset, uv, normalize(dirToCameraTransformed.xyz), float3(0,0,0), dummy); } struct PixelDepthOffset diff --git a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl index 770da549d0..fd11d0d8cd 100644 --- a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl +++ b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl @@ -136,15 +136,18 @@ ForwardPassOutput AutoBrick_ForwardPassPS(VSOutput IN) 0,1,0, 0,0,1 }; - float3 tangentOffset = GetParallaxOffset( AutoBrickSrg::m_lineDepth, - IN.m_uv, - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - IN.m_tangent, - IN.m_bitangent, - IN.m_normal, - identityUvMatrix); + float depthOffset = 0.0; + + ParallaxOffset tangentOffset = GetParallaxOffset( AutoBrickSrg::m_lineDepth, + depthOffset, + IN.m_uv, + ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, + IN.m_tangent, + IN.m_bitangent, + IN.m_normal, + identityUvMatrix); - IN.m_uv += tangentOffset.xy; + IN.m_uv += tangentOffset.m_offsetTS.xy; float3 baseColor = float3(1,1,1); const float noise = AutoBrickSrg::m_noise.Sample(AutoBrickSrg::m_sampler, IN.m_uv).r; From 7e678e15e86c1a1dda6dd9559ec23bfa6b4e2b29 Mon Sep 17 00:00:00 2001 From: Pip Potter Date: Fri, 30 Apr 2021 15:10:57 -0700 Subject: [PATCH 009/112] lyn2919: Update all references to O3DE - Also fix issue where invalid SIDs could be generated - Make default project name consistent across Gems --- Gems/AWSClientAuth/cdk/README.md | 6 +++--- Gems/AWSClientAuth/cdk/app.py | 6 +++--- Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py | 2 +- Gems/AWSClientAuth/cdk/utils/name_utils.py | 6 ++++-- Gems/AWSCore/cdk/README.md | 6 +++--- Gems/AWSCore/cdk/app.py | 6 +++--- Gems/AWSCore/cdk/core/core_stack.py | 2 +- Gems/AWSMetrics/cdk/README.md | 6 +++--- Gems/AWSMetrics/cdk/app.py | 6 +++--- Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py | 4 ++-- 10 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Gems/AWSClientAuth/cdk/README.md b/Gems/AWSClientAuth/cdk/README.md index d604057a65..4fe668cb9d 100644 --- a/Gems/AWSClientAuth/cdk/README.md +++ b/Gems/AWSClientAuth/cdk/README.md @@ -26,9 +26,9 @@ Once the python and pip are set up, you can install the required dependencies. Set variables ``` -set O3D_AWS_DEPLOY_REGION="us-west-2" -set O3D_AWS_DEPLOY_ACCOUNT="" -set O3D_AWS_PROJECT_NAME="AWSIProject" +set O3DE_AWS_DEPLOY_REGION="us-west-2" +set O3DE_AWS_DEPLOY_ACCOUNT="" +set O3DE_AWS_PROJECT_NAME="AWSIProject" If you want to add 3rd party providers fill values in utils/constant.py ``` diff --git a/Gems/AWSClientAuth/cdk/app.py b/Gems/AWSClientAuth/cdk/app.py index d6bba06f39..3b57eea07f 100755 --- a/Gems/AWSClientAuth/cdk/app.py +++ b/Gems/AWSClientAuth/cdk/app.py @@ -16,11 +16,11 @@ from aws_client_auth.client_auth_stack import AWSClientAuthStack import os """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) # Set the common prefix to group stacks in a project together. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'O3D-AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() env = core.Environment(account=ACCOUNT, region=REGION) app = core.App() diff --git a/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py b/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py index b09269bf3e..d030f8573c 100755 --- a/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py +++ b/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py @@ -58,7 +58,7 @@ class CognitoIdentityPool: self._identity_pool.add_depends_on(cognito_user_pool.get_user_pool()) self._identity_pool.add_depends_on(cognito_user_pool.get_user_pool_client()) - # Create roles to associate with Cognito Idenity pool + # Create roles to associate with Cognito Identity pool self._auth_role = CognitoIdentityPoolRole(scope, feature_name, project_name, env, self._identity_pool, authenticated=True) self._unauth_role = CognitoIdentityPoolRole(scope, feature_name, project_name, env, diff --git a/Gems/AWSClientAuth/cdk/utils/name_utils.py b/Gems/AWSClientAuth/cdk/utils/name_utils.py index 8c8f6a7e82..bab4cd0389 100755 --- a/Gems/AWSClientAuth/cdk/utils/name_utils.py +++ b/Gems/AWSClientAuth/cdk/utils/name_utils.py @@ -8,7 +8,7 @@ remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - +import re from aws_cdk import core @@ -21,7 +21,9 @@ def format_aws_resource_id(feature_name: str, project_name: str, env: core.Envir def format_aws_resource_sid(feature_name: str, project_name: str, resource_type: str): - return f'{project_name}{feature_name}{resource_type}SId' + sid = f'{project_name}{feature_name}{resource_type}SId' + # Strip out all chars not valid in a sid + return re.sub(r'[^a-zA-Z0-9]', '', sid) def format_aws_resource_authenticated_id(feature_name: str, project_name: str, env: core.Environment, diff --git a/Gems/AWSCore/cdk/README.md b/Gems/AWSCore/cdk/README.md index c49155a422..e4c0335c9c 100644 --- a/Gems/AWSCore/cdk/README.md +++ b/Gems/AWSCore/cdk/README.md @@ -44,9 +44,9 @@ $ pip install -r requirements.txt ## Set environment variables or accept defaults -* O3D_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION -* O3D_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT -* O3D_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT +* O3DE_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION +* O3DE_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT +* O3DE_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more information including how to pass parameters to use for environment variables. diff --git a/Gems/AWSCore/cdk/app.py b/Gems/AWSCore/cdk/app.py index 2e5b196e02..2d8bfa4181 100755 --- a/Gems/AWSCore/cdk/app.py +++ b/Gems/AWSCore/cdk/app.py @@ -22,11 +22,11 @@ from core.aws_core import AWSCore from example.example_resources_stack import ExampleResources """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ.get('CDK_DEFAULT_REGION')) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ.get('CDK_DEFAULT_ACCOUNT')) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ.get('CDK_DEFAULT_REGION')) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ.get('CDK_DEFAULT_ACCOUNT')) # Set the common prefix to group stacks in a project together. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() # The name of this feature FEATURE_NAME = 'Core' diff --git a/Gems/AWSCore/cdk/core/core_stack.py b/Gems/AWSCore/cdk/core/core_stack.py index 7bf8676987..997d15ef6b 100755 --- a/Gems/AWSCore/cdk/core/core_stack.py +++ b/Gems/AWSCore/cdk/core/core_stack.py @@ -27,7 +27,7 @@ class CoreStack(core.Stack): """ # Resource groups cannot start with 'AWS' or 'aws' so add this prefix - RESOURCE_GROUP_PREFIX = 'O3D' + RESOURCE_GROUP_PREFIX = 'O3DE' def __init__(self, scope: core.Construct, id_: str, project_name: str, feature_name: str, **kwargs) -> None: super().__init__(scope, id_, **kwargs) diff --git a/Gems/AWSMetrics/cdk/README.md b/Gems/AWSMetrics/cdk/README.md index 3f0544a9ce..6f2c774bc3 100644 --- a/Gems/AWSMetrics/cdk/README.md +++ b/Gems/AWSMetrics/cdk/README.md @@ -42,9 +42,9 @@ $ pip install -r requirements.txt ## Set environment variables or accept defaults -* O3D_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION -* O3D_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT -* O3D_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT +* O3DE_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION +* O3DE_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT +* O3DE_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more information including how to pass parameters to use for environment variables. diff --git a/Gems/AWSMetrics/cdk/app.py b/Gems/AWSMetrics/cdk/app.py index 21f8c8f802..469925e533 100755 --- a/Gems/AWSMetrics/cdk/app.py +++ b/Gems/AWSMetrics/cdk/app.py @@ -17,11 +17,11 @@ from aws_metrics.aws_metrics_construct import AWSMetrics import os """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) # Set the common prefix to group stacks in a project together. Defaults to LY-AWS. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() # The name of this feature FEATURE_NAME = 'AWSMetrics' diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py index f1a356addf..fe85615d8d 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py @@ -259,7 +259,7 @@ class BatchProcessing: ) policy_statements.append(input_stream_policy_statement) - log_policy_statetement = iam.PolicyStatement( + log_policy_statement = iam.PolicyStatement( actions=[ 'logs:PutLogEvents', ], @@ -268,7 +268,7 @@ class BatchProcessing: self._firehose_delivery_stream_log_group.log_group_arn ] ) - policy_statements.append(log_policy_statetement) + policy_statements.append(log_policy_statement) data_catalog_policy_statement = iam.PolicyStatement( actions=[ From 896738ccff9cd94526fb66bf6ee8968b1accd951 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Fri, 30 Apr 2021 16:08:43 -0700 Subject: [PATCH 010/112] Update Qt 3rdParty packages to fix a minor CMake issue --- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 7ccd118413..620995a85b 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -43,6 +43,6 @@ ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-linux TARGETS mikk ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-linux TARGETS googletest PACKAGE_HASH 7b7ad330f369450c316a4c4592d17fbb4c14c731c95bd8f37757203e8c2bbc1b) ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-linux TARGETS GoogleBenchmark PACKAGE_HASH 4038878f337fc7e0274f0230f71851b385b2e0327c495fc3dd3d1c18a807928d) ly_associate_package(PACKAGE_NAME unwind-1.2.1-linux TARGETS unwind PACKAGE_HASH 3453265fb056e25432f611a61546a25f60388e315515ad39007b5925dd054a77) -ly_associate_package(PACKAGE_NAME qt-5.15.2-linux TARGETS Qt PACKAGE_HASH 3857fbb2fc5581cdb71d80a7f9298c83ef06073d4e1ccd86a32b4f88782b6f14) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-linux TARGETS Qt PACKAGE_HASH b7d9932647f4b138b3f0b124d70debd250d2a8a6dca52b04dcbe82c6369d48ca) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-linux TARGETS libsamplerate PACKAGE_HASH 41643c31bc6b7d037f895f89d8d8d6369e906b92eff42b0fe05ee6a100f06261) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux TARGETS OpenSSL PACKAGE_HASH b779426d1e9c5ddf71160d5ae2e639c3b956e0fb5e9fcaf9ce97c4526024e3bc) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index fb6b17fb72..290508b348 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -47,5 +47,5 @@ ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-mac TARGETS mik ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-mac TARGETS googletest PACKAGE_HASH cbf020d5ef976c5db8b6e894c6c63151ade85ed98e7c502729dd20172acae5a8) ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac TARGETS GoogleBenchmark PACKAGE_HASH ad25de0146769c91e179953d845de2bec8ed4a691f973f47e3eb37639381f665) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-mac TARGETS OpenSSL PACKAGE_HASH 28adc1c0616ac0482b2a9d7b4a3a3635a1020e87b163f8aba687c501cf35f96c) -ly_associate_package(PACKAGE_NAME qt-5.15.2-mac TARGETS Qt PACKAGE_HASH ac248833d65838e4bcef50f30c9ff02ba9464ff64b9ada52de2ad6045d38baec) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index e8c1361b3f..bdc93d9a0e 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -51,7 +51,7 @@ ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-windows TARGETS Goo ly_associate_package(PACKAGE_NAME d3dx12-headers-rev1-windows TARGETS d3dx12 PACKAGE_HASH 088c637159fba4a3e4c0cf08fb4921906fd4cca498939bd239db7c54b5b2f804) ly_associate_package(PACKAGE_NAME pyside2-qt-5.15.1-rev2-windows TARGETS pyside2 PACKAGE_HASH c90f3efcc7c10e79b22a33467855ad861f9dbd2e909df27a5cba9db9fa3edd0f) ly_associate_package(PACKAGE_NAME openimageio-2.1.16.0-rev2-windows TARGETS OpenImageIO PACKAGE_HASH 85a2a6cf35cbc4c967c56ca8074babf0955c5b490c90c6e6fd23c78db99fc282) -ly_associate_package(PACKAGE_NAME qt-5.15.2-windows TARGETS Qt PACKAGE_HASH edaf954c647c99727bfd313dab2959803d2df0873914bb96368c3d8286eed6d9) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev2-windows TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-windows TARGETS libsamplerate PACKAGE_HASH dcf3c11a96f212a52e2c9241abde5c364ee90b0f32fe6eeb6dcdca01d491829f) ly_associate_package(PACKAGE_NAME OpenMesh-8.1-rev1-windows TARGETS OpenMesh PACKAGE_HASH 1c1df639358526c368e790dfce40c45cbdfcfb1c9a041b9d7054a8949d88ee77) ly_associate_package(PACKAGE_NAME civetweb-1.8-rev1-windows TARGETS civetweb PACKAGE_HASH 36d0e58a59bcdb4dd70493fb1b177aa0354c945b06c30416348fd326cf323dd4) From 009ecbc152c9a4c52ada55d821e0576c6824a34e Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 1 May 2021 15:53:24 -0700 Subject: [PATCH 011/112] Relocated RayTracingSceneSrg and converted to .azsli --- .../RayTracing}/RayTracingSceneSrg.azsli | 10 +++------ .../RayTracingSceneSrgAll.azsli | 19 ------------------ .../diffuseprobegridraytracing.azshader | Bin 79309 -> 79334 bytes ...probegridraytracing_dx12_0.azshadervariant | Bin 34086 -> 34086 bytes ...probegridraytracing_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...obegridraytracing_vulkan_0.azshadervariant | Bin 36232 -> 36232 bytes ...fuseprobegridraytracingclosesthit.azshader | Bin 79319 -> 79344 bytes ...aytracingclosesthit_dx12_0.azshadervariant | Bin 16754 -> 16754 bytes ...aytracingclosesthit_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...tracingclosesthit_vulkan_0.azshadervariant | Bin 9172 -> 9172 bytes ...raytracingcommon_raytracingglobalsrg.azsrg | 2 +- .../diffuseprobegridraytracingmiss.azshader | Bin 79313 -> 79338 bytes ...egridraytracingmiss_dx12_0.azshadervariant | Bin 16838 -> 16838 bytes ...egridraytracingmiss_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...ridraytracingmiss_vulkan_0.azshadervariant | Bin 10364 -> 10364 bytes .../RayTracing/RayTracingFeatureProcessor.cpp | 2 +- 16 files changed, 5 insertions(+), 28 deletions(-) rename Gems/Atom/Feature/Common/Assets/{ShaderResourceGroups => ShaderLib/Atom/Features/RayTracing}/RayTracingSceneSrg.azsli (96%) delete mode 100644 Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli similarity index 96% rename from Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli rename to Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli index 0aeb43bcf2..a7bb6cd3b1 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli @@ -10,11 +10,9 @@ * */ -#ifndef AZ_COLLECTING_PARTIAL_SRGS -#error Do not include this file directly. Include the main .srgi file instead. -#endif +#include -partial ShaderResourceGroup RayTracingSceneSrg +ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene { RaytracingAccelerationStructure m_scene; @@ -150,6 +148,4 @@ partial ShaderResourceGroup RayTracingSceneSrg #define MESH_NORMAL_BUFFER_OFFSET 2 ByteAddressBuffer m_meshBuffers[]; -} - - +} \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli deleted file mode 100644 index b1b2bea750..0000000000 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -// Please review README.md to understand how this file is used in RayTracingSceneSrg.azsrg generation - -#ifdef AZ_COLLECTING_PARTIAL_SRGS -#include -#endif diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader index a781a598bae5e1cecbbe1d75fa6d90a3b625f6ce..804b534277c99e83211f6276d08f434bc053295d 100644 GIT binary patch delta 125 zcmV-@0D}L`>jdWO1dxpphff>3WJVrRv6JCxT_9;^1(BX7BTjQ@VPs`;Y-wUIVRUb8 zFJ@(7bairNb1!mXd317NV`*+@vCqF~2zSz`Y9fzo=ChV*{$&V{6-YSnF#i;jacV2G f$Is$q2nD?nk0;y*aJR8E0TclUu}v(?sQ>@~POCJK delta 103 zcmV-t0GR*g>jcf~1dxppZj^>{MAC&^Q=NV7f!;tKZjqiR3N>?RVPs`;Y-wV#=)Y(P z2a02B-!#&`v#)9XWeEHZH0KJDPn?sAYAdtg&*EeV&N|Iem4rH>lZ$F9m-I9N>If$U J>T8_<001a)Fd+Z{ diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_dx12_0.azshadervariant index e9f841047e633f729f147731f9e8b3ed5dc1383b..b3bee56bfde29b0db4ae1ee8da02c26ea4a4ef98 100644 GIT binary patch delta 18 ZcmZ41#k8!8X@guV$3|bB(<>Pm7yv}F23`OF delta 18 ZcmZ41#k8!8X@guVhdRrv?70jK3;;mK1>FDu diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_null_0.azshadervariant index e399dbcef0fef75481aaf50adde0ecf40c34350d..d9b2f17848938ba5e6d6c71d609d8e5430695825 100644 GIT binary patch delta 16 XcmbQHJWY8+pCHFZU!Bt{85kGPm7yw6U2Ce`A delta 18 ZcmeB}&D1fQX+uLVhdRrv?70jK3;;uZ1}y*p diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader index bfed840febab47233bd7efbc8529ce1564a32892..c4a83a26dcc61d813d22d92798d7918b141877b3 100644 GIT binary patch delta 128 zcmV-`0Du42>jd!Y1dx{zhff>3WJVrRv6JCxT_9;^1(B#HBTjQ@VPs`;Y-wUIVRUb8 zFJ@(7bairNb1!mXd317NV`*+@vDv?92v(*>G-_7OinE|;{$&U=YprkZ&EN8qdul7Q i(a+*!2;)JARIRz3B9nY-DwpLn0qO{`O;(u!00010-Z>)x delta 99 zcmV-p0G$8u>jc;91dx{zZj^>{MAC&^Q=NV7f!;tKZjq=b3N>?RVPs`;Y-wV#^1o;Z zU%b6Fq`qF?v$<*hWeB8~BN>&;q^GmL&kbb=c7w0H(^#tQlfcg^m;N*X>If$Pg!t9~ F006w*G2s9J diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_dx12_0.azshadervariant index ee2031bf1a37142304bb7bfca95ce2e36ac459d3..fb5b740f040d6ec0f129ca8671a3c651009d85fa 100644 GIT binary patch delta 18 Zcmey=#Q3R+aYL3P$41|{jC3=9kaF>D05 delta 16 XcmbQHJWY8+pCE_Y|CS%u7#J7;I5h@A diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant index e2f5a8cb502b189e07cdec95a357c9d43f7c880f..1eeeffa8be8df2020435b46d5b5de152d8ece66b 100644 GIT binary patch delta 16 XcmccOe#L#m8D)-*zF{*N85kGjdiS1dx#xhff>3WJVrRv6JCxT_9;^1y*bJ4U;SZBO^|8Xklb!a%^d0 zFJW|VZ7*hJVRUtJWpgibVR>|NVPk1-XR*`3Xa^{Jk;V_e?X#L`{$&Ve)u}wHnI$f> ipwA6u2vMlcKO2mee3PNiDwp3h0qO{`P6*{90002M5H^4S delta 102 zcmV-s0Ga>l>jcs31dx#tZj^>{MAC&^Q=NV7f!;tKZjquV3N>?RVPs`;Y-wV#?7(OT zhE_7RJXh(nvuXZi2u!^#t2;G$>64CXE3@R!;$#SV!{+6eVip9Gk7_EH_%s3P2qyoA Ii<Sn-Ln}O7ywN^2OR(a diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_null_0.azshadervariant index 0f2473b60661c98f9fe92e1ec3d3c4f05a572d03..5f0882548721884c084c7c2a24a650074341a961 100644 GIT binary patch delta 16 XcmbQHJWY8+pCHFZKaQtL3=9kaF`oq3 delta 16 XcmbQHJWY8+pCE_Y|F-Vg3=9kaH8cgA diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_vulkan_0.azshadervariant index bfd979e588d5a15ff3c6ccce525bae8a2c8e6fa9..a5b0e842ef46ceb87c42addd8d1c8e4340b4bc17 100644 GIT binary patch delta 16 Xcmewp@F!qHi3Z0;KaQtL3=9kaLPrJr delta 16 Xcmewp@F!qHi3W$-|F-Vg3=9kaMcf9y diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index 0c24c2953d..c4e9306dc9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -67,7 +67,7 @@ namespace AZ // load the RayTracingSceneSrg asset Data::Asset rayTracingSceneSrgAsset = - RPI::AssetUtils::LoadAssetByProductPath("shaderlib/raytracingscenesrg_raytracingscenesrg.azsrg", RPI::AssetUtils::TraceLevel::Error); + RPI::AssetUtils::LoadAssetByProductPath("shaderlib/atom/features/raytracing/raytracingscenesrg_raytracingscenesrg.azsrg", RPI::AssetUtils::TraceLevel::Error); AZ_Assert(rayTracingSceneSrgAsset.IsReady(), "Failed to load RayTracingSceneSrg asset"); m_rayTracingSceneSrg = RPI::ShaderResourceGroup::Create(rayTracingSceneSrgAsset); From ce1191c1437b1fc74ee0171a7779132bb030c3e8 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 1 May 2021 16:02:06 -0700 Subject: [PATCH 012/112] Removed RayTracingSceneSrg.srgi from AutomatedTesting --- .../ShaderLib/raytracingscenesrg.srgi | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 AutomatedTesting/ShaderLib/raytracingscenesrg.srgi diff --git a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi b/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi deleted file mode 100644 index ac1d663bb8..0000000000 --- a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -// Please read README.md for an explanation on why scenesrg.srgi and viewsrg.srgi are -// located in this folder (And how you can optionally customize your own scenesrg.srgi -// and viewsrg.srgi in your game project). - -#include - -partial ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene -{ -/* Intentionally Empty. Helps define the SrgSemantic for RayTracingSceneSrg once.*/ -}; - -#define AZ_COLLECTING_PARTIAL_SRGS -#include -#undef AZ_COLLECTING_PARTIAL_SRGS From 3cbbcf1877f8966eae117362bdde338783758a15 Mon Sep 17 00:00:00 2001 From: balibhan Date: Mon, 3 May 2021 12:10:33 +0530 Subject: [PATCH 013/112] SC branch migration --- .../editor_python_test_tools/utils.py | 14 +- .../AssetEditor_CreateScriptEventFile.py | 124 ++ .../scripting/AssetEditor_NewScriptEvent.py | 129 ++ .../Debugging_TargetMultipleEntities.py | 144 ++ .../Debugging_TargetMultipleGraphs.py | 113 + .../Gem/PythonTests/scripting/Docking_Pane.py | 4 +- .../scripting/EditMenu_UndoRedo.py | 123 ++ .../Entity_AddScriptCanvasComponent.py | 88 + .../scripting/FileMenu_New_Open.py | 98 + .../scripting/GraphClose_SavePrompt.py | 110 + .../scripting/Graph_ZoomInZoomOut.py | 120 ++ .../PythonTests/scripting/ImportPathHelper.py | 1 + .../scripting/NodeInspector_RenameVariable.py | 132 ++ .../scripting/NodePalette_ClearSelection.py | 94 + .../scripting/NodePalette_SelectNode.py | 104 + ...EntityActivatedDeactivated_PrintMessage.py | 185 ++ .../scripting/Opening_Closing_Pane.py | 9 +- .../scripting/Pane_RetainOnSCRestart.py | 164 ++ .../PythonTests/scripting/Resizing_Pane.py | 9 +- .../scripting/ScriptCanvas_ChangingAssets.py | 116 + .../scripting/ScriptCanvas_TwoComponents.py | 118 ++ .../scripting/ScriptCanvas_TwoEntities.py | 107 + .../ScriptEvents_SendReceiveAcrossMultiple.py | 120 ++ .../ScriptEvents_SendReceiveSuccessfully.py | 110 + .../PythonTests/scripting/TestSuite_Active.py | 229 +- .../scripting/Toggle_ScriptCanvasTools.py | 137 ++ .../scripting/UnDockedPane_CloseSCWindow.py | 128 ++ .../VariableManager_CreateDeleteVars.py | 123 ++ .../activator.scriptcanvas | 778 +++++++ .../controller.scriptcanvas | 1865 +++++++++++++++++ .../deactivator.scriptcanvas | 766 +++++++ .../ScriptCanvas_TwoComponents0.scriptcanvas | 365 ++++ .../ScriptCanvas_TwoComponents1.scriptcanvas | 365 ++++ .../ScriptCanvas/T92563191_test.scriptcanvas | 750 +++++++ .../ScriptCanvas/T92567320.scriptcanvas | 1266 +++++++++++ .../ScriptCanvas/T92567321A.scriptcanvas | 778 +++++++ .../ScriptCanvas/T92567321B.scriptcanvas | 880 ++++++++ .../TestAssets/T92567320.scriptevents | 116 + .../TestAssets/T92567321.scriptevents | 166 ++ 39 files changed, 11024 insertions(+), 24 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas create mode 100644 AutomatedTesting/TestAssets/T92567320.scriptevents create mode 100644 AutomatedTesting/TestAssets/T92567321.scriptevents diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py index a9f6d0aa02..c7f1aba031 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py @@ -265,6 +265,7 @@ class Tracer: self.warnings = [] self.errors = [] self.asserts = [] + self.prints = [] self.has_warnings = False self.has_errors = False self.has_asserts = False @@ -310,6 +311,11 @@ class Tracer: def __repr__(self): return f"[Assert: {self.message}]" + + class PrintInfo: + def __init__(self, args): + self.window = args[0] + self.message = args[1] def _on_warning(self, args): warningInfo = Tracer.WarningInfo(args) @@ -331,13 +337,19 @@ class Tracer: Report.info("Tracer caught Assert: %s:%i[%s] \"%s\"" % (assertInfo.filename, assertInfo.line, assertInfo.function, assertInfo.message)) self.has_asserts = True return False - + + def _on_printf(self, args): + printInfo = Tracer.PrintInfo(args) + self.prints.append(printInfo) + return False + def __enter__(self): self.handler = azlmbr.debug.TraceMessageBusHandler() self.handler.connect(None) self.handler.add_callback("OnPreAssert", self._on_assert) self.handler.add_callback("OnPreWarning", self._on_warning) self.handler.add_callback("OnPreError", self._on_error) + self.handler.add_callback("OnPrintf", self._on_printf) return self def __exit__(self, type, value, traceback): diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py new file mode 100644 index 0000000000..dcbbf47f0c --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py @@ -0,0 +1,124 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92569013 +Test Case Title: Script Event file can be created +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569013 +""" + + +# fmt: off +class Tests(): + new_event_created = ("New Script Event created", "New Script Event not created") + child_event_created = ("Child Event created", "Child not created") + file_saved = ("Script event file saved", "Script event file did not save") + console_error = ("No unexpected error in console", "Error found in console") + console_warning = ("No unexpected warning in console", "Warning found in console") +# fmt: on + + +def CreateScriptEventFile(): + """ + Summary: + Script Event file can be created + + Expected Behavior: + File is created without any errors and warnings in Console + + Test Steps: + 1) Open Asset Editor + 2) Get Asset Editor Qt object + 3) Create new Script Event Asset + 4) Add new child event + 5) Save the Script Event file + 6) Verify if file is created + 7) Verify console for errors/warnings + 8) Close Asset Editor + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + import azlmbr.editor as editor + import azlmbr.bus as bus + + # Pyside imports + from PySide2 import QtWidgets + + GENERAL_WAIT = 1.0 # seconds + + FILE_PATH = os.path.join("AutomatedTesting", "ScriptCanvas", "test_file.scriptevent") + + # 1) Open Asset Editor + general.idle_enable(True) + # Initially close the Asset Editor and then reopen to ensure we don't have any existing assets open + general.close_pane("Asset Editor") + general.open_pane("Asset Editor") + helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), 5.0) + + # 2) Get Asset Editor Qt object + editor_window = pyside_utils.get_editor_main_window() + asset_editor_widget = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor").findChild( + QtWidgets.QWidget, "AssetEditorWindowClass" + ) + container = asset_editor_widget.findChild(QtWidgets.QWidget, "ContainerForRows") + menu_bar = asset_editor_widget.findChild(QtWidgets.QMenuBar) + + # 3) Create new Script Event Asset + action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "text": "Script Events"}) + action.trigger() + result = helper.wait_for_condition( + lambda: container.findChild(QtWidgets.QFrame, "Events") is not None, 3 * GENERAL_WAIT + ) + Report.result(Tests.new_event_created, result) + + # 4) Add new child event + add_event = container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "") + add_event.click() + result = helper.wait_for_condition( + lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "EventName") is not None, GENERAL_WAIT + ) + Report.result(Tests.child_event_created, result) + + with Tracer() as section_tracer: + # 5) Save the Script Event file + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", FILE_PATH) + + # 6) Verify if file is created + result = helper.wait_for_condition(lambda: os.path.exists(FILE_PATH), 3 * GENERAL_WAIT) + Report.result(Tests.file_saved, result) + + # 7) Verify console for errors/warnings + Report.result(Tests.console_error, not section_tracer.has_errors) + Report.result(Tests.console_warning, not section_tracer.has_warnings) + + # 8) Close Asset Editor + general.close_pane("Asset Editor") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(CreateScriptEventFile) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py new file mode 100644 index 0000000000..1f801d4eeb --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py @@ -0,0 +1,129 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568942 +Test Case Title: Clicking the "+" button and selecting "New Script Event" opens the +Asset Editor with a new Script Event asset +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568942 +""" + +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import TestHelper as helper +from editor_python_test_tools.utils import Report + + +class Tests: + action_found = "New Script event action found" + asset_editor_opened = "Asset Editor opened" + new_asset = "Asset Editor created with new asset" + script_event = "New Script event created in Asset Editor" + + +GENERAL_WAIT = 0.5 # seconds + + +class TestAssetEditor_NewScriptEvent: + """ + Summary: + Clicking the "+" button in Node Palette and creating New Script Event opens Asset Editor + + Expected Behavior: + Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a + new Script Event asset + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Close any existing AssetEditor window + 3) Get the SC window object + 4) Click on New Script Event on Node palette + 5) Verify if Asset Editor opened + 6) Verify if a new asset with Script Canvas category is opened + 7) Close Script Canvas and Asset Editor + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Close any existing AssetEditor window + general.close_pane("Asset Editor") + helper.wait_for_condition(lambda: not general.is_pane_visible("Asset Editor"), 5.0) + + # 3) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + frame = node_palette.findChild(QtWidgets.QFrame, "searchCustomization") + button = frame.findChild(QtWidgets.QToolButton) + pyside_utils.click_button_async(button) + + # 4) Click on New Script Event on Node palette + menu = None + + def menu_has_focus(): + nonlocal menu + for fw in [ + QtWidgets.QApplication.activePopupWidget(), + QtWidgets.QApplication.activeModalWidget(), + QtWidgets.QApplication.focusWidget(), + QtWidgets.QApplication.activeWindow(), + ]: + print(fw) + if fw and isinstance(fw, QtWidgets.QMenu) and fw.isVisible(): + menu = fw + return True + return False + + await pyside_utils.wait_for_condition(menu_has_focus, GENERAL_WAIT) + action = await pyside_utils.wait_for_action_in_menu(menu, {"text": "New Script Event"}) + Report.info(f"{Tests.action_found}: {action is not None}") + action.trigger() + pyside_utils.queue_hide_event(menu) + + # 5) Verify if Asset Editor opened + result = helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), GENERAL_WAIT) + Report.info(f"{Tests.asset_editor_opened}: {result}") + + # 6) Verify if a new asset with Script Canvas category is opened + asset_editor = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor") + row_container = asset_editor.findChild(QtWidgets.QWidget, "ContainerForRows") + # NOTE: QWidget ContainerForRows will have frames of Name, Category, ToolTip etc. + # To validate if a new script event file is generated, we check for + # QFrame Category and its value + categories = row_container.findChildren(QtWidgets.QFrame, "Category") + Report.info(f"{Tests.new_asset}: {len(categories)>0}") + result = False + for frame in categories: + line_edit = frame.findChild(QtWidgets.QLineEdit) + result = True if (line_edit and line_edit.text() == "Script Events") else False + Report.info(f"{Tests.script_event}: {result}") + + # 7) Close Script Canvas and Asset Editor + general.close_pane("Script Canvas") + general.close_pane("Asset Editor") + + +test = TestAssetEditor_NewScriptEvent() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py new file mode 100644 index 0000000000..a26cb4f923 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py @@ -0,0 +1,144 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568856 +Test Case Title: Multiple Entities can be targeted in the Debugger tool +URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568856 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + entities_found = ("Entities are found in Logging window", "Entities are not found in Logging window") + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Debugging_TargetMultipleEntities(): + """ + Summary: + Multiple Entities can be targeted in the Debugger tool + + Expected Behavior: + Selected files can be checked for logging. + Upon checking, checkboxes of the parent folders change to either full or partial check. + + Test Steps: + 1) Create temp level + 2) Create two entities with scriptcanvas components + 3) Set values for scriptcanvas + 4) Open Script Canvas window and get sc opbject + 5) Open Debugging(Logging) window + 6) Click on Entities tab in logging window + 7) Verify if the scriptcanvas exist under entities + 8) Verify if the entities can be selected + 9) Close Debugging window and Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + import os + import pyside_utils + import hydra_editor_utils as hydra + from utils import TestHelper as helper + from utils import Report + + LEVEL_NAME = "tmp_level" + ASSET_NAME_1 = "ScriptCanvas_TwoComponents0.scriptcanvas" + ASSET_NAME_2 = "ScriptCanvas_TwoComponents1.scriptcanvas" + ASSET_1 = os.path.join("scriptcanvas", ASSET_NAME_1) + ASSET_2 = os.path.join("scriptcanvas", ASSET_NAME_2) + WAIT_TIME = 3.0 + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create two entities with scriptcanvas components + position = math.Vector3(512.0, 512.0, 32.0) + test_entity_1 = hydra.Entity("test_entity_1") + test_entity_1.create_entity(position, ["Script Canvas"]) + test_entity_2 = hydra.Entity("test_entity_2") + test_entity_2.create_entity(position, ["Script Canvas"]) + + # 3) Set values for scriptcanvas + test_entity_1.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_1)) + test_entity_2.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_2)) + + # 4) Open Script Canvas window and get sc opbject + general.open_pane("Script Canvas") + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 5) Open Debugging(Logging) window + if ( + sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") is None + or not sc.findChild(QtWidgets.QDockWidget, "LoggingWindow").isVisible() + ): + action = pyside_utils.find_child_by_pattern(sc, {"text": "Debugging", "type": QtWidgets.QAction}) + action.trigger() + logging_window = sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") + + # 6) Click on Entities tab in logging window + button = pyside_utils.find_child_by_pattern(logging_window, {"type": QtWidgets.QPushButton, "text": "Entities"}) + button.click() + + # 7) Verify if the scriptcanvas exist under entities + entities = logging_window.findChild(QtWidgets.QWidget, "entitiesPage") + tree = entities.findChild(QtWidgets.QTreeView, "pivotTreeView") + asset_1_mi = pyside_utils.find_child_by_pattern(tree, ASSET_NAME_1.lower()) + asset_2_mi = pyside_utils.find_child_by_pattern(tree, ASSET_NAME_2.lower()) + result = asset_1_mi is not None and asset_2_mi is not None + Report.critical_result(Tests.entities_found, result) + + # 8) Verify if the entities can be selected + tree.expandAll() + tree.model().setData(asset_1_mi, 2, Qt.CheckStateRole) + tree.model().setData(asset_2_mi, 2, Qt.CheckStateRole) + checklist = [asset_1_mi, asset_1_mi.parent(), asset_2_mi, asset_2_mi.parent()] + result = all([index.data(Qt.CheckStateRole) == 2 for index in checklist]) + Report.critical_result(Tests.select_multiple_targets, result) + + # 9) Close Debugging window and Script Canvas window + logging_window.close() + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(Debugging_TargetMultipleEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py new file mode 100644 index 0000000000..4aa5c822a7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py @@ -0,0 +1,113 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569137 +Test Case Title: Multiple Graphs can be targeted in the Debugger tool +URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569137 +""" + + +# fmt: off +class Tests(): + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Debugging_TargetMultipleGraphs(): + """ + Summary: + Multiple Graphs can be targeted in the Debugger tool + + Expected Behavior: + Selected files can be checked for logging. + Upon checking, checkboxes of the parent folders change to either full or partial check. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Debugging Tool if not opened already + 4) Select Graphs tab under logging window + 5) Select multiple targets from levels and scriptcanvas + 6) Verify if multiple targets are selected + 7) Close Debugging window and Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + from utils import Report + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 6.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Debugging Tool if not opened already + if ( + sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") is None + or not sc.findChild(QtWidgets.QDockWidget, "LoggingWindow").isVisible() + ): + action = pyside_utils.find_child_by_pattern(sc, {"text": "Debugging", "type": QtWidgets.QAction}) + action.trigger() + logging_window = sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") + + # 4) Select Graphs tab under logging window + button = pyside_utils.find_child_by_pattern(logging_window, {"type": QtWidgets.QPushButton, "text": "Graphs"}) + button.click() + + # 5) Select multiple targets from levels and scriptcanvas + graphs = logging_window.findChild(QtWidgets.QWidget, "graphsPage") + tree = graphs.findChild(QtWidgets.QTreeView, "pivotTreeView") + # Select the first child under levels + level_model_index = pyside_utils.find_child_by_pattern(tree, "levels") + level_child_index = pyside_utils.get_item_view_index(tree, 0, 0, level_model_index) + tree.model().setData(level_child_index, 2, Qt.CheckStateRole) + # Select the first child under scriptcanvas + sc_model_index = pyside_utils.find_child_by_pattern(tree, "scriptcanvas") + sc_child_index = pyside_utils.get_item_view_index(tree, 0, 0, sc_model_index) + tree.model().setData(sc_child_index, 2, Qt.CheckStateRole) + + # 6) Verify if multiple targets are selected + result = all([index.data(Qt.CheckStateRole) != 0 for index in (level_model_index, sc_model_index)]) + result = result and all([index.data(Qt.CheckStateRole) == 2 for index in (level_child_index, sc_child_index)]) + Report.result(Tests.select_multiple_targets, result) + + # 7) Close Debugging window and Script Canvas window + logging_window.close() + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Debugging_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py index 25dd83e5e2..4fa1e1257f 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py @@ -16,7 +16,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") pane_opened = ("Pane is opened successfully", "Failed to open pane") dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") # fmt: on @@ -78,8 +77,7 @@ def Docking_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Make sure Node Palette pane is opened editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py new file mode 100644 index 0000000000..a87d9e9be9 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py @@ -0,0 +1,123 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569049 +Test Case Title: Edit > Undo undoes the last action +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569049 +Test case ID: T92569051 +Test Case Title: Edit > Redo redoes the last undone action +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569051 +""" + + +# fmt: off +class Tests(): + variable_created = ("New variable created", "New variable not created") + undo_worked = ("Undo action working", "Undo action did not work") + redo_worked = ("Redo action working", "Redo action did not work") +# fmt: on + + +def EditMenu_UndoRedo(): + """ + Summary: + Edit > Undo undoes the last action + Edit > Redo redoes the last undone action + We create a new variable in variable manager, undo and verify if variable is removed, + redo it and verify if the variable is created again. + + Expected Behavior: + The last action is undone. + The last undone action is redone. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Create Graph + 5) Create new variable + 6) Verify if the variable is created initially + 7) Trigger Undo action and verify if variable is removed in Variable Manager + 8) Trigger Redo action and verify if variable is readded in Variable Manager + 9) Close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets, QtCore + + import azlmbr.legacy.general as general + + import pyside_utils + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "VariableManager") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Variable Manager", "type": QtWidgets.QAction}) + action.trigger() + variable_manager = sc.findChild(QtWidgets.QDockWidget, "VariableManager") + + # 4) Create Graph + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + + # 5) Create new variable + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() # Click on Create Variable button + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + + # 6) Verify if the variable is created initially + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 # since we added 1 variable, rowcount=1 + Report.result(Tests.variable_created, result) + + # 7) Trigger Undo action and verify if variable is removed in Variable Manager + action = sc.findChild(QtWidgets.QAction, "action_Undo") + action.trigger() + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 0 # since we triggered undo, rowcount=0 + Report.result(Tests.undo_worked, result) + + # 8) Trigger Redo action and verify if variable is readded in Variable Manager + action = sc.findChild(QtWidgets.QAction, "action_Redo") + action.trigger() + result = ( + graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 + ) # since action is redone 1 variable is readded, rowcount=1 + Report.result(Tests.redo_worked, result) + + # 9) Close SC window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(EditMenu_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py new file mode 100644 index 0000000000..fd8e9b1173 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py @@ -0,0 +1,88 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562978 +Test Case Title: Script Canvas Component can be added to an entity +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562978 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "Failed to create new level") + entity_created = ("Test Entity created", "Failed to create test entity") + add_sc_component = ("Script Canvas component added to entity", "Failed to add SC component to entity") + no_errors_found = ("Tracer found no errors", "One or more errors found by Tracer") + no_warnings_found = ("Tracer found no warnings", "One or more warnings found by Tracer") +# fmt: on + + +def Entity_AddScriptCanvasComponent(): + """ + Summary: + verify if Script Canvas component can be added to Entity without any issue + + Expected Behavior: + Script Canvas Component is added to the entity successfully without issue. + + Test Steps: + 1) Create temp level + 2) Create test entity + 3) Start Tracer + 4) Add Script Canvas component to test entity + 5) Search for errors and warnings + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from utils import TestHelper as helper + from utils import Tracer + from editor_entity_utils import EditorEntity + import azlmbr.legacy.general as general + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create new entity + test_entity = EditorEntity.create_editor_entity("test_entity") + Report.result(Tests.entity_created, test_entity.id.IsValid()) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Add Script Canvas component to test entity + test_entity.add_component("Script Canvas") + Report.result(Tests.add_sc_component, test_entity.has_component("Script Canvas")) + + # 5) Search for errors and warnings + Report.result(Tests.no_errors_found, not section_tracer.has_errors) + Report.result(Tests.no_warnings_found, not section_tracer.has_warnings) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(Entity_AddScriptCanvasComponent) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py new file mode 100644 index 0000000000..f72ac8ea01 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py @@ -0,0 +1,98 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569037 +Test Case Title: File > New Script creates a new script +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569037 +Test case ID: T92569039 +Test Case Title: File > Open opens the Open... dialog +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569039 +""" + +import os +import sys +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import Report + +# fmt: off +class Tests(): + new_action = "File->New action working as expected" + open_action = "File->Open action working as expected" +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +class TestFileMenuNewOpen: + """ + Summary: + When clicked on File->New, new script opens and File->Open should open the FileBrowser + + Expected Behavior: + New and Open actions should work as expected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Trigger File->New action + 4) Verify if New tab is opened + 5) Trigger File->Open action + 6) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs") + + # 3) Trigger File->New action + initial_tabs_count = sc_tabs.count() + action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + action.trigger() + + # 4) Verify if New tab is opened + general.idle_wait(GENERAL_WAIT) + Report.info(f"{Tests.new_action}: {sc_tabs.count() == initial_tabs_count + 1}") + + # 5) Trigger File->Open action + action = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_Open", "type": QtWidgets.QAction}) + pyside_utils.trigger_action_async(action) + general.idle_wait(GENERAL_WAIT) + popup = await pyside_utils.wait_for_modal_widget() + Report.info(f"{Tests.open_action}: {popup and 'Open' in popup.windowTitle()}") + popup.close() + + # 6) Close Script Canvas window + general.close_pane("Script Canvas") + + +test = TestFileMenuNewOpen() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py new file mode 100644 index 0000000000..ce610b159b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py @@ -0,0 +1,110 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92563070 +Test Case Title: Graphs can be closed by clicking X on the Graph name tab +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563070 +Test case ID: T92563068 +Test Case Title: Save Prompt: User is prompted to save a graph on close after +creating a new graph +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563068 +""" + +import os +import sys +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import TestHelper as helper +from editor_python_test_tools.utils import Report + +# fmt: off +class Tests(): + new_graph = "New graph created" + save_prompt = "Save prompt opened as expected" + close_graph = "Close button worked as expected" +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +class TestGraphCloseSavePrompt: + """ + Summary: + The graph is closed when x button is clicked. + Save Prompt is opened before closing. + + Expected Behavior: + New and Open actions should work as expected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Trigger File->New action + 4) Verify if New tab is opened + 5) Close new tab using X on top of graph and check for save dialog + 6) Check if tab is closed + 7) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs") + tab_bar = sc_tabs.findChild(QtWidgets.QTabBar) + + # 3) Trigger File->New action + initial_tabs_count = sc_tabs.count() + action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + action.trigger() + + # 4) Verify if New tab is opened + result = helper.wait_for_condition(lambda: sc_tabs.count() == initial_tabs_count + 1, GENERAL_WAIT) + Report.info(f"{Tests.new_graph}: {result}") + + # 5) Close new tab using X on top of graph and check for save dialog + close_button = tab_bar.findChildren(QtWidgets.QAbstractButton)[0] + pyside_utils.click_button_async(close_button) + popup = await pyside_utils.wait_for_modal_widget() + if popup: + Report.info(f"{Tests.save_prompt}: {popup.findChild(QtWidgets.QDialog, 'SaveChangesDialog') is not None}") + dont_save = popup.findChild(QtWidgets.QPushButton, "m_continueButton") + dont_save.click() + + # 6) Check if tab is closed + await pyside_utils.wait_for_condition(lambda: sc_tabs.count() == initial_tabs_count, 5.0) + Report.info(f"{Tests.close_graph}: {sc_tabs.count()==initial_tabs_count}") + + # 7) Close Script Canvas window + general.close_pane("Script Canvas") + + +test = TestGraphCloseSavePrompt() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py new file mode 100644 index 0000000000..a93b6e61d1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py @@ -0,0 +1,120 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569079 +Test Case Title: View > Zoom In zooms the graph in +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569079 +Test case ID: T92569081 +Test Case Title: View > Zoom In zooms the graph out +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569081 +""" + + +# fmt: off +class Tests(): + zoom_in = ("Zoom In action working as expected", "Zoom In action not working as expected") + zoom_out = ("Zoom Out action working as expected", "Zoom Out action not working as expected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Graph_ZoomInZoomOut(): + """ + Summary: + The graph can be zoomed in and zoomed out. + + Expected Behavior: + The graph is zoomed in when when we click View->ZoomIn + The graph is zoomed out when when we click View->ZoomOut + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Create new graph + 4) Get initial graph transform values + 5) Trigger Zoom In and verify if the graph transform scale is increased + 6) Trigger Zoom Out and verify if the graph transform scale is decreased + 7) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + import ImportPathHelper as imports + + imports.init() + + from PySide2 import QtWidgets + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + from utils import Report + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + + # 3) Create new graph + create_new_graph = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + create_new_graph.trigger() + + # 4) Get initial graph transform values + graphics_view = sc_main.findChild(QtWidgets.QGraphicsView) + # NOTE: transform m11 and m22 are horizontal and vertical scales of graph + # they increase when zoomed in and decreased when zoomed out + curr_m11, curr_m22 = graphics_view.transform().m11(), graphics_view.transform().m22() + + # 5) Trigger Zoom In and verify if the graph transform scale is increased + zin = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomIn", "type": QtWidgets.QAction}) + zin.trigger() + result = helper.wait_for_condition( + lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT, + ) + Report.result(Tests.zoom_in, result) + + # 6) Trigger Zoom Out and verify if the graph transform scale is decreased + curr_m11, curr_m22 = graphics_view.transform().m11(), graphics_view.transform().m22() + zout = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomOut", "type": QtWidgets.QAction}) + zout.trigger() + result = helper.wait_for_condition( + lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT, + ) + Report.result(Tests.zoom_out, result) + + # 7) Close Script Canvas window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Graph_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index 8aede24d0e..a45024cebf 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -13,4 +13,5 @@ def init(): import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py new file mode 100644 index 0000000000..33d3f4137a --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py @@ -0,0 +1,132 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92568982 +Test Case Title: Renaming variables in the Node Inspector +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568982 +""" + + +# fmt: off +class Tests(): + variable_created = ("New variable created", "New variable is not created") + node_inspector_rename = ("Variable is renamed in Node Inspector", "Variable is not renamed in Node Inspector") + variable_manager_rename = ("Variable is renamed in Variable Manager", "Variable is not renamed in Variable Manager") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def NodeInspector_RenameVariable(): + """ + Summary: + Renaming variables in the Node Inspector, renames the actual variable. + + Expected Behavior: + The Variable's name is changed in both Node Inspector and Variable Manager. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Open Node Inspector if not opened already + 5) Create new graph and a new variable in Variable manager + 6) Click on the variable + 7) Update name in Node Inspector and click on ENTER + 8) Verify if the name is updated in Node inspector and Variable manager + 9) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + TEST_NAME = "test name" + + from PySide2 import QtWidgets, QtCore, QtTest + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + + def open_tool(sc, dock_widget_name, pane_name): + if sc.findChild(QtWidgets.QDockWidget, dock_widget_name) is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": pane_name, "type": QtWidgets.QAction}) + action.trigger() + tool = sc.findChild(QtWidgets.QDockWidget, dock_widget_name) + return tool + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + variable_manager = open_tool(sc, "VariableManager", "Variable Manager") + + # 4) Open Node Inspector if not opened already + node_inspector = open_tool(sc, "NodeInspector", "Node Inspector") + + # 5) Create new graph and a new variable in Variable manager + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 + var_mi = pyside_utils.find_child_by_pattern(graph_vars, "Variable 1") + result = result and (var_mi is not None) + Report.critical_result(Tests.variable_created, result) + + # 6) Click on the variable + pyside_utils.item_view_index_mouse_click(graph_vars, var_mi) + + # 7) Update name in Node Inspector and click on ENTER + helper.wait_for_condition( + lambda: node_inspector.findChild(QtWidgets.QWidget, "ContainerForRows") is not None, GENERAL_WAIT + ) + row_container = node_inspector.findChild(QtWidgets.QWidget, "ContainerForRows") + name_frame = row_container.findChild(QtWidgets.QWidget, "Name") + name_line_edit = name_frame.findChild(QtWidgets.QLineEdit) + name_line_edit.setText(TEST_NAME) + QtTest.QTest.keyClick(name_line_edit, Qt.Key_Return, Qt.NoModifier) + + # 8) Verify if the name is updated in Node inspector and Variable manager + helper.wait_for_condition(lambda: var_mi.data(Qt.DisplayRole) == TEST_NAME, GENERAL_WAIT) + Report.critical_result(Tests.node_inspector_rename, name_line_edit.text() == TEST_NAME) + Report.critical_result(Tests.variable_manager_rename, var_mi.data(Qt.DisplayRole) == TEST_NAME) + + # 9) Close Script Canvas window + general.close_pane("Script Canvas") + + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(NodeInspector_RenameVariable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py new file mode 100644 index 0000000000..de30e46767 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py @@ -0,0 +1,94 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562993 +Test Case Title: Clicking the X button on the Search Box clears the currently entered string +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562993 +""" + + +# fmt: off +class Tests(): + set_search_string = ("Search string is set", "Search string is not set") + search_string_cleared = ("Search string cleared as expected", "Search string not cleared") +# fmt: on + + +def NodePalette_ClearSelection(): + """ + Summary: + We enter some string in the Node Palette Search box, and click on the X button to verify if the + search string got cleared. + + Expected Behavior: + Clicking the X button on the Search Box clears the currently entered string + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Node Manager if not opened already + 4) Set some string in the Search box + 5) Verify if the test string is set + 6) Clear search string and verify if it is cleared + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + + from utils import TestHelper as helper + + import azlmbr.legacy.general as general + + import pyside_utils + + TEST_STRING = "Test String" + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 3.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Node Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + search_frame = node_palette.findChild(QtWidgets.QFrame, "searchFrame") + + # 4) Set some string in the Search box + search_box = search_frame.findChild(QtWidgets.QLineEdit, "searchFilter") + search_box.setText(TEST_STRING) + + # 5) Verify if the test string is set + Report.result(Tests.set_search_string, search_box.text() == TEST_STRING) + + # 6) Clear search string and verify if it is cleared + clear_text_button = search_frame.findChild(QtWidgets.QToolButton, "ClearToolButton") + clear_text_button.click() + Report.result(Tests.search_string_cleared, search_box.text() == "") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(NodePalette_ClearSelection) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py new file mode 100644 index 0000000000..2ab76071a6 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py @@ -0,0 +1,104 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568940 +Test Case Title: Categories and Nodes can be selected +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568940 +""" + + +# fmt: off +class Tests(): + category_selected = ("Category can be selected", "Category cannot be selected") + node_selected = ("Node can be selected", "Node cannot be selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def NodePalette_SelectNode(): + """ + Summary: + Categories and Nodes can be selected + + Expected Behavior: + When clicked on Node Palette, nodes and categories can be selected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Expand QTreeView + 4) Click on category and check if it is selected + 5) Click on node and check if it is selected + 6) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + CATEGORY = "AI" + NODE = "Find Path To Entity" + + from PySide2 import QtWidgets + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + tree = node_palette.findChild(QtWidgets.QTreeView, "treeView") + + # 3) Expand QTreeView + tree.expandAll() + + # 4) Click on category and check if it is selected + category_index = pyside_utils.find_child_by_hierarchy(tree, CATEGORY) + tree.scrollTo(category_index) + pyside_utils.item_view_index_mouse_click(tree, category_index) + pyside_utils.wait_for_condition(tree.selectedIndexes() and tree.selectedIndexes()[0] == category_index) + Report.result(Tests.category_selected, tree.selectedIndexes()[0] == category_index) + + # 5) Click on node and check if it is selected + node_index = pyside_utils.find_child_by_pattern(tree, NODE) + helper.wait_for_condition(lambda: tree.isExpanded(node_index), GENERAL_WAIT) + pyside_utils.item_view_index_mouse_click(tree, node_index) + pyside_utils.wait_for_condition(tree.selectedIndexes()[0] == node_index) + Report.result(Tests.node_selected, tree.selectedIndexes()[0] == node_index) + + # 6) Close Script Canvas window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(NodePalette_SelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py new file mode 100644 index 0000000000..cea1230348 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -0,0 +1,185 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92569253 // T92569254 +Test Case Title: On Entity Activated // On Entity Deactivated +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569253 // https://testrail.agscollab.com/index.php?/tests/view/92569254 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temp level", "Failed to create temp level") + controller_exists = ("Successfully found controller entity", "Failed to find controller entity") + activated_exists = ("Successfully found activated entity", "Failed to find activated entity") + deactivated_exists = ("Successfully found deactivated entity","Failed to find deactivated entity") + start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") + game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") + lines_found = ("Successfully found expected prints", "Failed to find expected prints") + game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") +# fmt: on + + +def OnEntityActivatedDeactivated_PrintMessage(): + """ + Summary: + Verify that the On Entity Activation node is working as expected + + Expected Behavior: + Upon entering game mode, the Controller entity will wait 1 second and then activate the ActivationTest + entity. The script attached to ActivationTest will print out a message on activation. The Controller + will also deactivate the DeactivationTest entity, which should print a message. + + Test Steps: + 1) Create temp level + 2) Setup the level + 3) Validate the entities + 4) Start the Tracer + 5) Enter Game Mode + 6) Validate Print message + 7) Exit game mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from utils import TestHelper as helper + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import Tracer + + import azlmbr.legacy.general as general + + EditorEntity = str + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + EXPECTED_LINES = ["Activator Script: Activated", "Deactivator Script: Deactivated"] + controller_dict = { + "name": "Controller", + "status": "active", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas") + } + activated_dict = { + "name": "ActivationTest", + "status": "inactive", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas") + } + deactivated_dict = { + "name": "DeactivationTest", + "status": "active", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas") + } + + def get_asset(asset_path): + return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + + def setup_level(): + def create_editor_entity(entity_dict:dict, entity_to_activate:EditorEntity=None, entity_to_deactivate:EditorEntity=None) -> EditorEntity: + entity = Entity.create_editor_entity(entity_dict["name"]) + entity.set_start_status(entity_dict["status"]) + sc_component = entity.add_component("Script Canvas") + sc_component.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"])) + + if entity_dict["name"] == "Controller": + sc_component.get_property_tree() + sc_component.set_component_property_value("Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", entity_to_activate.id) + sc_component.set_component_property_value("Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", entity_to_deactivate.id) + return entity + + activated = create_editor_entity(activated_dict) + deactivated = create_editor_entity(deactivated_dict) + create_editor_entity(controller_dict, activated, deactivated) + + def validate_entity_exist(entity_name: str, test_tuple: tuple): + """ + Validate the entity with the given name exists in the level + :return: entity: editor entity object + """ + entity = Entity.find_editor_entity(entity_name) + Report.critical_result(test_tuple, entity.id.IsValid()) + return entity + + def validate_start_state(entity:EditorEntity, expected_state:str): + """ + Validate that the starting state of the entity is correct, if it isn't then attempt to rectify and recheck. + :return: bool: Whether state is set as expected + """ + state_options = { + "active": azlmbr.globals.property.EditorEntityStartStatus_StartActive, + "inactive": azlmbr.globals.property.EditorEntityStartStatus_StartInactive, + "editor": azlmbr.globals.property.EditorEntityStartStatus_EditorOnly, + } + if expected_state.lower() not in state_options.keys(): + raise ValueError(f"{expected_state} is an invalid option; valid options: active, inactive, or editor.") + + state = entity.get_start_status() + if state != state_options[expected_state]: + # If state fails to set, set_start_status will assert + entity.set_start_status(expected_state) + return True + + def validate_entities_in_level(): + controller = validate_entity_exist(controller_dict["name"], Tests.controller_exists) + state1_correct = validate_start_state(controller, controller_dict["status"]) + + act_tester = validate_entity_exist(activated_dict["name"], Tests.activated_exists) + state2_correct = validate_start_state(act_tester, activated_dict["status"]) + + deac_tester = validate_entity_exist(deactivated_dict["name"], Tests.deactivated_exists) + state3_correct = validate_start_state(deac_tester, deactivated_dict["status"]) + + all_states_correct = state1_correct and state2_correct and state3_correct + Report.critical_result(Tests.start_states_correct, all_states_correct) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + print(f"bhanu: {found_lines}") + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Setup the level + setup_level() + + # 3) Validate the entities + validate_entities_in_level() + + # 4) Start the Tracer + with Tracer() as section_tracer: + + # 5) Enter Game Mode + helper.enter_game_mode(Tests.game_mode_entered) + + # 6) Validate Print message + helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + + Report.result(Tests.lines_found, locate_expected_lines(EXPECTED_LINES)) + + # 7) Exit game mode + helper.exit_game_mode(Tests.game_mode_exited) + + +if __name__ == "__main__": + import ImportPathHelper as imports + imports.init() + + from utils import Report + + Report.start_test(OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py index 6100285092..666f052240 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py @@ -17,7 +17,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") default_visible = ("All the panes visible by default", "One or more panes do not visible by default") open_panes = ("All the Panes opened successfully", "Failed to open one or more panes") close_pane = ("All the Panes closed successfully", "Failed to close one or more panes") @@ -49,11 +48,6 @@ def Opening_Closing_Pane(): :return: None """ - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -82,8 +76,7 @@ def Opening_Closing_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Restore default layout editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py new file mode 100644 index 0000000000..fa5e9e6068 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py @@ -0,0 +1,164 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C1702821 // C1702832 +Test Case Title: Retain visibility, size and location upon Script Canvas restart +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702821 and + https://testrail.agscollab.com/index.php?/cases/view/1702832 +""" + + +# fmt: off +class Tests(): + relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") + test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") + close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") + visiblity_retained = ("Test pane retained its visiblity on SC restart", "Failed to retain visiblity of test pane on SC restart") + resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") + size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") + location_changed = ("Location of test pane 2 changed successfully", "Failed to change locatio of test pane 2") + location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") +# fmt: on + + +def Pane_RetainOnSCRestart(): + """ + Summary: + The Script Canvas window is opened to verify if Script canvas panes can retain its visibility, size and location + upon ScriptCanvas restart. + + Expected Behavior: + The ScriptCanvas pane retain it's visiblity, size and location upon ScriptCanvas restart. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Make sure test panes are open and visible + 3) Close test pane 1 + 4) Change dock location of test pane 2 + 5) Resize test pane 3 + 6) Relaunch Script Canvas + 7) Verify if test pane 1 retain its visiblity + 8) Verify if location of test pane 2 is retained + 9) Verify if size of test pane 3 is retained + 10) Restore default layout and close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine Imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtCore, QtWidgets + from PySide2.QtCore import Qt + + # Constants + TEST_PANE_1 = "NodePalette" # test visibility + TEST_PANE_2 = "VariableManager" # test location + TEST_PANE_3 = "NodeInspector" # test size + SCALE_INT = 10 # Random resize scale integer + DOCKAREA = Qt.TopDockWidgetArea # Preferred top area since no widget is docked on top + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 3.0) + + # 2) Make sure test panes are open and visible + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + test_pane_1 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_1) + test_pane_2 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_2) + test_pane_3 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_3) + + Report.result( + Tests.test_panes_visible, test_pane_1.isVisible() and test_pane_2.isVisible() and test_pane_3.isVisible() + ) + + # Initiate try block here to restore default in finally block + try: + # 3) Close test pane + test_pane_1.close() + Report.result(Tests.close_pane_1, not test_pane_1.isVisible()) + + # 4) Change dock location of test pane 2 + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_main.addDockWidget(DOCKAREA, find_pane(sc_main, TEST_PANE_2), QtCore.Qt.Vertical) + Report.result(Tests.location_changed, sc_main.dockWidgetArea(find_pane(sc_main, TEST_PANE_2)) == DOCKAREA) + + # 5) Resize test pane 3 + initial_size = test_pane_3.frameSize() + test_pane_3.resize(initial_size.width() + SCALE_INT, initial_size.height() + SCALE_INT) + new_size = test_pane_3.frameSize() + resize_success = ( + abs(initial_size.width() - new_size.width()) == abs(initial_size.height() - new_size.height()) == SCALE_INT + ) + Report.result(Tests.resize_pane_3, resize_success) + + # 6) Relaunch Script Canvas + general.close_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 2.0) + + general.open_pane("Script Canvas") + sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + Report.result(Tests.relaunch_sc, sc_visible) + + # 7) Verify if test pane 1 retain its visiblity + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + Report.result(Tests.visiblity_retained, not find_pane(sc, TEST_PANE_1).isVisible()) + + # 8) Verify if location of test pane 2 is retained + sc_main = sc.findChild(QtWidgets.QMainWindow) + Report.result(Tests.location_retained, sc_main.dockWidgetArea(find_pane(sc_main, TEST_PANE_2)) == DOCKAREA) + + # 9) Verify if size of test pane 3 is retained + test_pane_3 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_3) + retained_size = test_pane_3.frameSize() + retain_success = retained_size != initial_size + Report.result(Tests.size_retained, retain_success) + + finally: + # 10) Restore default layout and close SC window + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Pane_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py index 9262e76cb0..180f577953 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py @@ -16,7 +16,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") open_pane = ("Pane opened successfully", "Failed to open pane") resize_pane = ("Pane window resized successfully", "Failed to resize pane window") # fmt: on @@ -46,11 +45,6 @@ def Resizing_Pane(): :return: None """ - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -76,8 +70,7 @@ def Resizing_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Restore default layout editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py new file mode 100644 index 0000000000..38d60ad871 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py @@ -0,0 +1,116 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562986 +Test Case Title: Changing the assigned Script Canvas Asset on an entity properly updates +level functionality +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562986 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + entity_created = ("Test Entity created", "Test Entity not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +def ScriptCanvas_ChangingAssets(): + """ + Summary: + Changing the assigned Script Canvas Asset on an entity properly updates level functionality + + Expected Behavior: + When game mode is entered, respective strings of assigned assets should be printed + + Test Steps: + 1) Create temp level + 2) Create new entity + 3) Start Tracer + 4) Set first script and evaluate + 5) Set second script and evaluate + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import os + + from utils import TestHelper as helper + from utils import Tracer + import hydra_editor_utils as hydra + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.paths as paths + + LEVEL_NAME = "tmp_level" + ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") + ASSET_2 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents1.scriptcanvas") + EXP_LINE_1 = "Greetings from the first script" + EXP_LINE_2 = "Greetings from the second script" + WAIT_TIME = 3.0 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + def find_expected_line(expected_line): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + return expected_line in found_lines + + def set_asset_evaluate(test_entity, ASSET_PATH, EXP_LINE): + # Set Script Canvas entity + test_entity.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + + # Enter/exit game mode + helper.enter_game_mode(Tests.game_mode_entered) + helper.wait_for_condition(lambda: find_expected_line(EXP_LINE), WAIT_TIME) + Report.result(Tests.found_lines, find_expected_line(EXP_LINE)) + helper.exit_game_mode(Tests.game_mode_exited) + + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create new entity + position = math.Vector3(512.0, 512.0, 32.0) + test_entity = hydra.Entity("test_entity") + test_entity.create_entity(position, ["Script Canvas"]) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Set first script and evaluate + set_asset_evaluate(test_entity, ASSET_1, EXP_LINE_1) + + # 5) Set second script and evaluate + set_asset_evaluate(test_entity, ASSET_2, EXP_LINE_2) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(ScriptCanvas_ChangingAssets) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py new file mode 100644 index 0000000000..896bee96e5 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py @@ -0,0 +1,118 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92563190 +Test Case Title: A single Entity with two Script Canvas components works properly +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563190 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +class LogLines: + expected_lines = ["Greetings from the first script", "Greetings from the second script"] + + +def ScriptCanvas_TwoComponents(): + """ + Summary: + A test entity contains two Script Canvas components with different unique script canvas files. + Each of these files will have a print node set to activate on graph start. + + Expected Behavior: + When game mode is entered, two unique strings should be printed out to the console + + Test Steps: + 1) Create level + 2) Create entity with SC components + 3) Start Tracer + 4) Enter game mode + 5) Wait for expected lines to be found + 6) Report if expected lines were found + 7) Exit game mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from utils import TestHelper as helper + import hydra_editor_utils as hydra + from utils import Report + from utils import Tracer + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") + ASSET_2 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents1.scriptcanvas") + WAIT_TIME = 3.0 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + def locate_expected_lines(): + found_lines = [] + for printInfo in section_tracer.prints: + found_lines.append(printInfo.message.strip()) + + return all(line in found_lines for line in LogLines.expected_lines) + + # 1) Create level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create entity with SC components + position = math.Vector3(512.0, 512.0, 32.0) + test_entity = hydra.Entity("test_entity") + test_entity.create_entity(position, ["Script Canvas", "Script Canvas"]) + test_entity.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_1)) + test_entity.get_set_test(1, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_2)) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter game mode + helper.enter_game_mode(Tests.game_mode_entered) + + # 5) Wait for expected lines to be found + helper.wait_for_condition(locate_expected_lines, WAIT_TIME) + + # 6) Report if expected lines were found + Report.result(Tests.found_lines, locate_expected_lines()) + + # 7) Exit game mode + helper.exit_game_mode(Tests.game_mode_exited) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(ScriptCanvas_TwoComponents) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py new file mode 100644 index 0000000000..401e6c0271 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py @@ -0,0 +1,107 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92563191 +Test Case Title: Two Entities can use the same Graph asset successfully at RunTime +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563191 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +def ScriptCanvas_TwoEntities(): + """ + Summary: + Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset + attached to the enties will print the respective entity names. + + Expected Behavior: + When game mode is entered, respective strings of different entities should be printed. + + Test Steps: + 1) Create temp level + 2) Create two new entities with different names + 3) Set ScriptCanvas asset to both the entities + 4) Enter/Exit game mode and verify log lines + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import os + + from utils import TestHelper as helper + from utils import Tracer + import hydra_editor_utils as hydra + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + ASSET_PATH = os.path.join("scriptcanvas", "T92563191_test.scriptcanvas") + EXPECTED_LINES = ["Entity Name: test_entity_1", "Entity Name: test_entity_2"] + WAIT_TIME = 0.5 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create two new entities with different names + position = math.Vector3(512.0, 512.0, 32.0) + test_entity_1 = hydra.Entity("test_entity_1") + test_entity_1.create_entity(position, ["Script Canvas"]) + + test_entity_2 = hydra.Entity("test_entity_2") + test_entity_2.create_entity(position, ["Script Canvas"]) + + # 3) Set ScriptCanvas asset to both the entities + test_entity_1.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + test_entity_2.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + + # 4) Enter/Exit game mode and verify log lines + with Tracer() as section_tracer: + + helper.enter_game_mode(Tests.game_mode_entered) + # wait for WAIT_TIME to let the script print strings + general.idle_wait(WAIT_TIME) + helper.exit_game_mode(Tests.game_mode_exited) + + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + result = all(line in found_lines for line in EXPECTED_LINES) + + Report.result(Tests.found_lines, result) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(ScriptCanvas_TwoEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py new file mode 100644 index 0000000000..d671229cdf --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py @@ -0,0 +1,120 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92567321 +Test Case Title: Script Events: Can send and receive a script event across multiple entities successfully +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567321 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temporary level", "Failed to create temporary level") + entitya_created = ("Successfully created EntityA", "Failed to create EntityA") + entityb_created = ("Successfully created EntityB", "Failed to create EntityB") + enter_game_mode = ("Successfully entered game mode", "Failed to enter game mode") + lines_found = ("Successfully found expected message", "Failed to find expected message") + exit_game_mode = ("Successfully exited game mode", "Failed to exit game mode") +# fmt: on + + +def ScriptEvents_SendReceiveAcrossMultiple(): + """ + Summary: + EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. The Script Event created for the test will be sent from EntityA to EntityB. + + Expected Behavior: + The output of the Script Event should be printed to the console + + Test Steps: + 1) Create test level + 2) Create EntityA/EntityB (add scriptcanvas files part of entity setup) + 3) Start Tracer + 4) Enter Game Mode + 5) Read for line + 6) Exit Game Mode + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + + import azlmbr.legacy.general as general + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 + ASSET_PREFIX = "T92567321" + asset_paths = { + "event": os.path.join("TestAssets", f"{ASSET_PREFIX}.scriptevents"), + "assetA": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}A.scriptcanvas"), + "assetB": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}B.scriptcanvas"), + } + sc_for_entities = { + "EntityA": asset_paths["assetA"], + "EntityB": asset_paths["assetB"] + } + EXPECTED_LINES = ["Incoming Message Received"] + + def get_asset(asset_path): + return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + + def create_editor_entity(name, sc_asset): + entity = Entity.create_editor_entity(name) + sc_comp = entity.add_component("Script Canvas") + sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(sc_asset)) + Report.critical_result(Tests.__dict__[name.lower()+"_created"], entity.id.isValid()) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create EntityA/EntityB + for key in sc_for_entities.keys(): + create_editor_entity(key, sc_for_entities[key]) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter Game Mode + helper.enter_game_mode(Tests.enter_game_mode) + + # 5) Read for line + lines_located = helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + Report.result(Tests.lines_found, lines_located) + + # 6) Exit Game Mode + helper.exit_game_mode(Tests.exit_game_mode) + + +if __name__ == "__main__": + import ImportPathHelper as imports + imports.init() + + from utils import Report + + Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py new file mode 100644 index 0000000000..b5e26d14ae --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py @@ -0,0 +1,110 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92567320 +Test Case Title: Script Events: Can send and receive a script event successfully +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567320 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temporary level", "Failed to create temporary level") + entity_created = ("Successfully created test entity", "Failed to create test entity") + enter_game_mode = ("Successfully entered game mode", "Failed to enter game mode") + lines_found = ("Successfully found expected message", "Failed to find expected message") + exit_game_mode = ("Successfully exited game mode", "Failed to exit game mode") +# fmt: on + + +def ScriptEvents_SendReceiveSuccessfully(): + """ + Summary: + An entity exists in the level that contains a Script Canvas component. In the graph is both a Send Event + and a Receive Event. + + Expected Behavior: + After entering game mode the graph on the entity should print an expected message to the console + + Test Steps: + 1) Create test level + 2) Create test entity + 3) Start Tracer + 4) Enter Game Mode + 5) Read for line + 6) Exit Game Mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + + import azlmbr.legacy.general as general + import azlmbr.asset as asset + import azlmbr.math as math + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + EXPECTED_LINES = ["T92567320: Message Received"] + SC_ASSET_PATH = os.path.join("ScriptCanvas", "T92567320.scriptcanvas") + + def create_editor_entity(name, sc_asset): + entity = Entity.create_editor_entity(name) + sc_comp = entity.add_component("Script Canvas") + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", sc_asset, math.Uuid(), False) + sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", asset_id) + Report.critical_result(Tests.entity_created, entity.id.isValid()) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create test entity + create_editor_entity("TestEntity", SC_ASSET_PATH) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter Game Mode + helper.enter_game_mode(Tests.enter_game_mode) + + # 5) Read for line + lines_located = helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + Report.result(Tests.lines_found, lines_located) + + # 6) Exit Game Mode + helper.exit_game_mode(Tests.exit_game_mode) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(ScriptEvents_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index 8c34f29ebf..d87f2986bf 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -12,22 +12,243 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import pytest import os import sys +sys.path.append(os.path.dirname(__file__)) +import ImportPathHelper as imports +imports.init() + +import hydra_test_utils as hydra +import ly_test_tools.environment.file_system as file_system from ly_test_tools import LAUNCHERS - -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - from base import TestAutomationBase +TEST_DIRECTORY = os.path.dirname(__file__) + + @pytest.mark.SUITE_periodic @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - + @pytest.mark.test_case_id("C1702834", "C1702823") + def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): + from . import Opening_Closing_Pane as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702824") def test_Docking_Pane(self, request, workspace, editor, launcher_platform): from . import Docking_Pane as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.test_case_id("C1702829") def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): from . import Resizing_Pane as test_module self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92563190") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_TwoComponents as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562986") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_ChangingAssets as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569079", "T92569081") + def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): + from . import Graph_ZoomInZoomOut as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568940") + def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): + from . import NodePalette_SelectNode as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569253") + @pytest.mark.test_case_id("T92569254") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import OnEntityActivatedDeactivated_PrintMessage as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562993") + def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): + from . import NodePalette_ClearSelection as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92563191") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_TwoEntities as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569013") + def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): + def teardown(): + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + request.addfinalizer(teardown) + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + from . import AssetEditor_CreateScriptEventFile as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569165", "T92569167", "T92569168", "T92569170") + def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): + from . import Toggle_ScriptCanvasTools as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568982") + def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): + from . import NodeInspector_RenameVariable as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569137") + def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): + from . import Debugging_TargetMultipleGraphs as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568856") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import Debugging_TargetMultipleEntities as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569049", "T92569051") + def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): + from . import EditMenu_UndoRedo as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702825", "C1702831") + def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): + from . import UnDockedPane_CloseSCWindow as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562978") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import Entity_AddScriptCanvasComponent as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702821", "C1702832") + def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): + from . import Pane_RetainOnSCRestart as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92567321") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptEvents_SendReceiveAcrossMultiple as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92567320") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptEvents_SendReceiveSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + +# NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method +# fails because of pyside_utils import +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ["windows_editor"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestScriptCanvasTests(object): + """ + The following tests use hydra_test_utils.py to launch the editor and validate the results. + """ + + @pytest.mark.test_case_id("T92569037", "T92569039") + def test_FileMenu_New_Open(self, request, editor, launcher_platform): + expected_lines = [ + "File->New action working as expected: True", + "File->Open action working as expected: True", + ] + hydra.launch_and_validate_results( + request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, + ) + + @pytest.mark.test_case_id("T92568942") + def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): + expected_lines = [ + "New Script event action found: True", + "Asset Editor opened: True", + "Asset Editor created with new asset: True", + "New Script event created in Asset Editor: True", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "AssetEditor_NewScriptEvent.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) + + @pytest.mark.test_case_id("T92563068", "T92563070") + def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): + expected_lines = [ + "New graph created: True", + "Save prompt opened as expected: True", + "Close button worked as expected: True", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "GraphClose_SavePrompt.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) + + @pytest.mark.test_case_id("T92564789", "T92568873") + def test_VariableManager_CreateDeleteVars(self, request, editor, launcher_platform): + var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] + expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] + expected_lines.extend([f"Success: {var_type} variable is deleted" for var_type in var_types]) + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "VariableManager_CreateDeleteVars.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py new file mode 100644 index 0000000000..4024e28277 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py @@ -0,0 +1,137 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C92569165, C92569167, C92569168, C92569170 +Test Case Title: Tools > Node Palette toggles the Node Palette + Tools > Node Inspector toggles the Node Inspector + Tools > Bookmarks toggles the Bookmarks + Tools > Variable Manager toggles the Variable Manager + +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/92569165 + https://testrail.agscollab.com/index.php?/cases/view/92569167 + https://testrail.agscollab.com/index.php?/cases/view/92569168 + https://testrail.agscollab.com/index.php?/cases/view/92569170 +""" + + +# fmt: off +class Tests(): + node_palette_opened = ("NodePalette is opened successfully", "Failed to open NodePalette") + node_inspector_opened = ("NodeInspector is opened successfully", "Failed to open NodeInspector") + bookmark_opened = ("Bookmarks is opened successfully", "Failed to open Bookmarks") + variable_manager_opened = ("VariableManager is opened successfully", "Failed to open VariableManager") + node_palette_closed_by_start = ("NodePalette is closed successfully", "Failed to close NodePalette") + node_inspector_closed_by_start = ("NodeInspector is closed successfully", "Failed to close NodeInspector") + bookmark_closed_by_start = ("Bookmarks is closed successfully", "Failed to close Bookmarks") + variable_manager_closed_by_start = ("VariableManager is closed successfully", "Failed to close VariableManager") + node_palette_closed_by_end = ("NodePalette is closed successfully", "Failed to close NodePalette") + node_inspector_closed_by_end = ("NodeInspector is closed successfully", "Failed to close NodeInspector") + bookmark_closed_by_end = ("Bookmarks is closed successfully", "Failed to close Bookmarks") + variable_manager_closed_by_end = ("VariableManager is closed successfully", "Failed to close VariableManager") +# fmt: on + + +def Toggle_ScriptCanvasTools(): + """ + Summary: + Toggle Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas. + Make sure each pane opens and closes successfully. + + Expected Behavior: + Each pane opens and closes successfully. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Make sure Node Palette, Node Inspector, Bookmarks and Variable Manager panes are closed in Script Canvas window + 3) Open Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + 4) Close Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + 5) Restore default layout + 6) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtWidgets + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + def close_tool(window, pane_widget, test_tuple): + pane = find_pane(window, pane_widget) + pane.close() + Report.result(test_tuple, not pane.isVisible()) + + def open_tool(window, pane_widget, tool, test_tuple): + pane = find_pane(window, pane_widget) + if not pane.isVisible(): + click_menu_option(window, tool) + pane = find_pane(window, pane_widget) + Report.result(test_tuple, pane.isVisible()) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Make sure Node Palette, Node Inspector, Bookmarks and Variable Manager panes are closed in Script Canvas window + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + close_tool(sc, "NodePalette", Tests.node_palette_closed_by_start) + close_tool(sc, "NodeInspector", Tests.node_inspector_closed_by_start) + close_tool(sc, "BookmarkDockWidget", Tests.bookmark_closed_by_start) + close_tool(sc, "VariableManager", Tests.variable_manager_closed_by_start) + + # 3) Open Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + open_tool(sc, "NodePalette", "Node Palette", Tests.node_palette_opened) + open_tool(sc, "NodeInspector", "Node Inspector", Tests.node_inspector_opened) + open_tool(sc, "BookmarkDockWidget", "Bookmarks", Tests.bookmark_opened) + open_tool(sc, "VariableManager", "Variable Manager", Tests.variable_manager_opened) + + # 4) Close Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + close_tool(sc, "NodePalette", Tests.node_palette_closed_by_end) + close_tool(sc, "NodeInspector", Tests.node_inspector_closed_by_end) + close_tool(sc, "BookmarkDockWidget", Tests.bookmark_closed_by_end) + close_tool(sc, "VariableManager", Tests.variable_manager_closed_by_end) + + # 5) Restore default layout + # Need this step to restore to default in case of test failure + click_menu_option(sc, "Restore Default Layout") + + # 6) Close Script Canvas window + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Toggle_ScriptCanvasTools) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py new file mode 100644 index 0000000000..875f28ec95 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py @@ -0,0 +1,128 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C1702825 // C1702831 +Test Case Title: Undocking // Closing script canvas with the pane floating +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702825 & + https://testrail.agscollab.com/index.php?/cases/view/1702831 +""" + + +# fmt: off +class Tests(): + undock_pane = ("Pane is undocked successfully", "Failed to undock pane") + close_sc_window = ("Script Canvas window is closed", "Failed to close Script Canvas window") + pane_closed = ("Pane is closed successfully", "Failed to close the pane") +# fmt: on + + +def UnDockedPane_CloseSCWindow(): + """ + Summary: + The Script Canvas window is opened with one of the pane undocked. + Verify if undocked pane closes upon closing Script canvas window. + + Expected Behavior: + The undocked pane closes when Script Canvas window closed. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Undock Node Palette pane + 3) Connect to Pane visibility signal emitter to verify pane closed + 4) Close Script Canvas window + 5) Restore default layout + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtWidgets + + TEST_PANE = "NodePalette" # Chosen most commonly used pane + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + def on_top_level_changed(): + # This function has test condition always True since it gets emitted only when condition satisfied + Report.result(Tests.undock_pane, True) + + def on_pane_closed(): + # This function has test condition always True since it gets emitted only when condition satisfied + Report.result(Tests.pane_closed, True) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Undock Node Palette pane + # Make sure Node Palette pane is opened + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + pane = find_pane(sc, TEST_PANE) + if not pane.isVisible(): + click_menu_option(sc, "Node Palette") + pane = find_pane(sc, TEST_PANE) # New reference + + # We drag/drop pane over the graph since it doesn't allow docking, so this will undock it + try: + graph = find_pane(sc, "GraphCanvasEditorCentralWidget") + try: + pane.topLevelChanged.connect(on_top_level_changed) + pyside_utils.drag_and_drop(pane, graph) + finally: + pane.topLevelChanged.disconnect(on_top_level_changed) + + # 3) Connect to Pane visibility signal emitter to verify pane closed + # No need to disconnect this since pane widget gets deleted when SC window closed + pane.visibilityChanged.connect(on_pane_closed) + + # 4) Close Script Canvas window + sc.close() + is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 2.0) + Report.result(Tests.close_sc_window, not is_sc_visible) + + finally: + # 5) Restore default layout + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(UnDockedPane_CloseSCWindow) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py new file mode 100644 index 0000000000..6facc324d4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py @@ -0,0 +1,123 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92564789 +Test Case Title: Each Variable type can be created +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92564789 +Test case ID: T92568873 +Test Case Title: Each Variable type can be deleted +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568873 +""" + + +def VariableManager_CreateDeleteVars(): + """ + Summary: + Each variable type can be created and deleted in variable manager. + + Expected Behavior: + Each variable type can be created and deleted in variable manager. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Create Graph + 5) Create variable of each type and verify if it is created + 6) Delete each type of variable and verify if it is deleted + 7) Close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets, QtCore, QtTest + + from PySide2.QtCore import Qt + + from utils import TestHelper as helper + + import azlmbr.legacy.general as general + + import pyside_utils + + def generate_test_tuple(var_type, action): + return (f"{var_type} variable is {action}d", f"{var_type} variable is not {action}d") + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 10.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "VariableManager") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Variable Manager", "type": QtWidgets.QAction}) + action.trigger() + variable_manager = sc.findChild(QtWidgets.QDockWidget, "VariableManager") + + # 4) Create Graph + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + + var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] + + # 5) Create variable of each type and verify if it is created + for index, var_type in enumerate(var_types): + # Create new variable + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() # Click on Create Variable button + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, var_type) + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + # Verify if the variable is created + # NOTE: To check if variable of a type is created, we are checking 1) rowcount + # 2) If we have row with variable "Variable " + # 3) Type of variable, which is next column of the variable name + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == ( + index + 1 + ) # since we added 1 variable, rowcount will increase by 1 + var_mi = pyside_utils.find_child_by_pattern(graph_vars, f"Variable {index+1}") + result = result and (var_mi is not None) and (var_mi.siblingAtColumn(1).data(Qt.DisplayRole) == var_type) + Report.result(generate_test_tuple(var_type, "create"), result) + + # 6) Delete each type of variable and verify if it is deleted + for index, var_type in enumerate(var_types): + # Delete variable and verify if its deleted + # NOTE: To check if variable of a type is deleted, we are checking rowcount + var_mi = pyside_utils.find_child_by_pattern(graph_vars, f"Variable {index+1}") + pyside_utils.item_view_index_mouse_click(graph_vars, var_mi) + QtTest.QTest.keyClick(graph_vars, Qt.Key_Delete, Qt.NoModifier) + # since variable is deleted, rowcount will decrease by 1 + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == (len(var_types) - (index + 1)) + Report.result(generate_test_tuple(var_type, "delete"), result) + + # 7) Close SC window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(VariableManager_CreateDeleteVars) diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas new file mode 100644 index 0000000000..89d86f0d54 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas @@ -0,0 +1,778 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas new file mode 100644 index 0000000000..83a899798e --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas @@ -0,0 +1,1865 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas new file mode 100644 index 0000000000..ca98ee303a --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas @@ -0,0 +1,766 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas new file mode 100644 index 0000000000..af3afead19 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas new file mode 100644 index 0000000000..0a16717520 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas new file mode 100644 index 0000000000..f0797739a5 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas @@ -0,0 +1,750 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas new file mode 100644 index 0000000000..d509442435 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas @@ -0,0 +1,1266 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas new file mode 100644 index 0000000000..644a5daa17 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas @@ -0,0 +1,778 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas new file mode 100644 index 0000000000..54c83c2933 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas @@ -0,0 +1,880 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/TestAssets/T92567320.scriptevents b/AutomatedTesting/TestAssets/T92567320.scriptevents new file mode 100644 index 0000000000..63cf20f2d0 --- /dev/null +++ b/AutomatedTesting/TestAssets/T92567320.scriptevents @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/TestAssets/T92567321.scriptevents b/AutomatedTesting/TestAssets/T92567321.scriptevents new file mode 100644 index 0000000000..6f9308ad02 --- /dev/null +++ b/AutomatedTesting/TestAssets/T92567321.scriptevents @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From d115c8904357ee330f2d305e9931db98f08a7c35 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 11:48:48 -0500 Subject: [PATCH 014/112] Fixes for using the DebugDisplayRequestBus in game mode --- .../AtomDebugDisplayViewportInterface.cpp | 38 +- ...AtomDebugDisplayViewportInterface.cpp.orig | 1544 +++++++++++++++++ .../AtomDebugDisplayViewportInterface.h | 9 + .../AtomLyIntegration/AtomFont/FFont.h | 2 +- .../AtomFont/Code/Source/FFont.cpp | 13 +- .../CoreLights/EditorAreaLightComponent.cpp | 1 + 6 files changed, 1595 insertions(+), 12 deletions(-) create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 690963e26b..871d75f194 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -244,9 +244,6 @@ namespace AZ::AtomBridge } //////////////////////////////////////////////////////////////////////// - // Partial implementation of the DebugDisplayRequestBus on Atom. - // Commented out function prototypes are waiting to be implemented. - // work tracked in [ATOM-3459] AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) { ResetRenderState(); @@ -272,9 +269,8 @@ namespace AZ::AtomBridge InitInternal(scene, nullptr); } - void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + void AtomDebugDisplayViewportInterface::UpdateAuxGeom(RPI::Scene* scene, AZ::RPI::View* view) { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); if (!scene) { m_auxGeomPtr = nullptr; @@ -286,20 +282,48 @@ namespace AZ::AtomBridge m_auxGeomPtr = nullptr; return; } - if (m_defaultInstance) + if (m_defaultInstance || !view) { m_auxGeomPtr = auxGeomFP->GetDrawQueue(); } else { - m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); + m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(view); } + } + + void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + UpdateAuxGeom(scene, viewportContextPtr ? viewportContextPtr->GetDefaultView().get() : nullptr); AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); + if (!m_defaultInstance) + { + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusConnect(viewportContextPtr->GetId()); + } + } + + + void AtomDebugDisplayViewportInterface::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) + { + ResetRenderState(); + if (m_defaultInstance) + { + RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + UpdateAuxGeom(scene, nullptr); + } + else + { + auto viewportContextManager = AZ::Interface::Get(); + AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); + UpdateAuxGeom(viewportContextPtr->GetRenderScene().get(), viewportContextPtr->GetDefaultView().get()); + } } AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() { AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusDisconnect(); m_viewportId = AzFramework::InvalidViewportId; m_auxGeomPtr = nullptr; } diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig new file mode 100644 index 0000000000..a4093ec937 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig @@ -0,0 +1,1544 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace // unnamed namespace to hold copies of Cry AuxGeom state enum's, this is to avoid creating a dependency on IRenderAuxGeom.h +{ + // Notes: + // Don't change the xxxShift values, they need to match the values from legacy cry rendering + // This also applies to the individual flags in EAuxGeomPublicRenderflags_*! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + enum EAuxGeomPublicRenderflagBitMasks + { + e_Mode2D3DShift = 31, + e_Mode2D3DMask = 0x1 << e_Mode2D3DShift, + + e_AlphaBlendingShift = 29, + e_AlphaBlendingMask = 0x3 << e_AlphaBlendingShift, + + e_DrawInFrontShift = 28, + e_DrawInFrontMask = 0x1 << e_DrawInFrontShift, + + e_FillModeShift = 26, + e_FillModeMask = 0x3 << e_FillModeShift, + + e_CullModeShift = 24, + e_CullModeMask = 0x3 << e_CullModeShift, + + e_DepthWriteShift = 23, + e_DepthWriteMask = 0x1 << e_DepthWriteShift, + + e_DepthTestShift = 22, + e_DepthTestMask = 0x1 << e_DepthTestShift, + + e_PublicParamsMask = e_Mode2D3DMask | e_AlphaBlendingMask | e_DrawInFrontMask | e_FillModeMask | + e_CullModeMask | e_DepthWriteMask | e_DepthTestMask + }; + + // Notes: + // e_Mode2D renders in normalized [0.. 1] screen space. + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_Mode2D3D + { + e_Mode3D = 0x0 << e_Mode2D3DShift, + e_Mode2D = 0x1 << e_Mode2D3DShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_AlphaBlendMode + { + e_AlphaNone = 0x0 << e_AlphaBlendingShift, + e_AlphaAdditive = 0x1 << e_AlphaBlendingShift, + e_AlphaBlended = 0x2 << e_AlphaBlendingShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DrawInFrontMode + { + e_DrawInFrontOff = 0x0 << e_DrawInFrontShift, + e_DrawInFrontOn = 0x1 << e_DrawInFrontShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_FillMode + { + e_FillModeSolid = 0x0 << e_FillModeShift, + e_FillModeWireframe = 0x1 << e_FillModeShift, + e_FillModePoint = 0x2 << e_FillModeShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_CullMode + { + e_CullModeNone = 0x0 << e_CullModeShift, + e_CullModeFront = 0x1 << e_CullModeShift, + e_CullModeBack = 0x2 << e_CullModeShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DepthWrite + { + e_DepthWriteOn = 0x0 << e_DepthWriteShift, + e_DepthWriteOff = 0x1 << e_DepthWriteShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DepthTest + { + e_DepthTestOn = 0x0 << e_DepthTestShift, + e_DepthTestOff = 0x1 << e_DepthTestShift, + }; +}; + +namespace AZ::AtomBridge +{ + + //////////////////////////////////////////////////////////////////////// + SingleColorDynamicSizeLineHelper::SingleColorDynamicSizeLineHelper( + int estimatedNumLineSegments + ) + { + m_points.reserve(estimatedNumLineSegments * 2); + } + + void SingleColorDynamicSizeLineHelper::AddLineSegment( + const AZ::Vector3& lineStart, + const AZ::Vector3& lineEnd + ) + { + m_points.push_back(lineStart); + m_points.push_back(lineEnd); + } + + void SingleColorDynamicSizeLineHelper::Draw( + AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, + const RenderState& rendState + ) const + { + if (auxGeomDrawPtr && !m_points.empty()) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = m_points.data(); + drawArgs.m_vertCount = aznumeric_cast(m_points.size()); + drawArgs.m_colors = &rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = rendState.m_lineWidth; + drawArgs.m_opacityType = rendState.m_opacityType; + drawArgs.m_depthTest = rendState.m_depthTest; + drawArgs.m_depthWrite = rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = rendState.m_viewProjOverrideIndex; + auxGeomDrawPtr->DrawLines( drawArgs ); + } + } + + void SingleColorDynamicSizeLineHelper::Draw2d( + AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, + const RenderState& rendState + ) const + { + if (auxGeomDrawPtr && !m_points.empty()) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = m_points.data(); + drawArgs.m_vertCount = aznumeric_cast(m_points.size()); + drawArgs.m_colors = &rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = rendState.m_lineWidth; + drawArgs.m_opacityType = rendState.m_opacityType; + drawArgs.m_depthTest = rendState.m_depthTest; + drawArgs.m_depthWrite = rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = auxGeomDrawPtr->GetOrAdd2DViewProjOverride(); + auxGeomDrawPtr->DrawLines( drawArgs ); + } + } + + void SingleColorDynamicSizeLineHelper::Reset() + { + m_points.clear(); + } + //////////////////////////////////////////////////////////////////////// + + // Partial implementation of the DebugDisplayRequestBus on Atom. + // Commented out function prototypes are waiting to be implemented. + // work tracked in [ATOM-3459] + AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) + { + ResetRenderState(); + m_viewportId = viewportContextPtr->GetId(); + m_defaultInstance = false; + auto setupScene = [this](RPI::ScenePtr scene) + { + auto viewportContextManager = AZ::Interface::Get(); + AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); + InitInternal(scene.get(), viewportContextPtr); + }; + setupScene(viewportContextPtr->GetRenderScene()); + m_sceneChangeHandler = AZ::RPI::ViewportContext::SceneChangedEvent::Handler(setupScene); + viewportContextPtr->ConnectSceneChangedHandler(m_sceneChangeHandler); + } + + AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(uint32_t defaultInstanceAddress) + { + ResetRenderState(); + m_viewportId = defaultInstanceAddress; + m_defaultInstance = true; + RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + InitInternal(scene, nullptr); + } + + void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + if (!scene) + { + m_auxGeomPtr = nullptr; + return; + } + auto auxGeomFP = scene->GetFeatureProcessor(); + if (!auxGeomFP) + { + m_auxGeomPtr = nullptr; + return; + } + if (m_defaultInstance) + { + m_auxGeomPtr = auxGeomFP->GetDrawQueue(); + } + else + { + m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); + } + AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); + } + + AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + m_viewportId = AzFramework::InvalidViewportId; + m_auxGeomPtr = nullptr; + } + + void AtomDebugDisplayViewportInterface::ResetRenderState() + { + m_rendState = RenderState(); + for (int index = 0; index < RenderState::TransformStackSize; ++index) + { + m_rendState.m_transformStack[index] = AZ::Matrix3x4::Identity(); + } + } + + void AtomDebugDisplayViewportInterface::SetColor(float r, float g, float b, float a) + { + m_rendState.m_color = AZ::Color(r, g, b, a); + } + + void AtomDebugDisplayViewportInterface::SetColor(const AZ::Color& color) + { + m_rendState.m_color = color; + } + + void AtomDebugDisplayViewportInterface::SetColor(const AZ::Vector4& color) + { + m_rendState.m_color = AZ::Color(color); + } + + void AtomDebugDisplayViewportInterface::SetAlpha(float a) + { + m_rendState.m_color.SetA(a); + if (a < 1.0f) + { + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; + } + else + { + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; + } + } + + void AtomDebugDisplayViewportInterface::DrawQuad( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::Vector3 triangles[6]; + triangles[0] = wsPoints[0]; + triangles[1] = wsPoints[1]; + triangles[2] = wsPoints[2]; + triangles[3] = wsPoints[2]; + triangles[4] = wsPoints[3]; + triangles[5] = wsPoints[0]; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = triangles; + drawArgs.m_vertCount = 6; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawQuad(float width, float height) + { + if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) + { + return; + } + + m_auxGeomPtr->DrawQuad( + width, + height, + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = wsPoints; + drawArgs.m_vertCount = 4; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad(float width, float height) + { + if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) + { + return; + } + + m_auxGeomPtr->DrawQuad( + width, + height, + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + + void AtomDebugDisplayViewportInterface::DrawQuadGradient( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4, + const AZ::Vector4& firstColor, + const AZ::Vector4& secondColor) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::Vector3 triangles[6]; + AZ::Color colors[6]; + triangles[0] = wsPoints[0]; colors[0] = firstColor; + triangles[1] = wsPoints[1]; colors[1] = firstColor; + triangles[2] = wsPoints[2]; colors[2] = secondColor; + triangles[3] = wsPoints[2]; colors[3] = secondColor; + triangles[4] = wsPoints[3]; colors[4] = secondColor; + triangles[5] = wsPoints[0]; colors[5] = firstColor; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = triangles; + drawArgs.m_vertCount = 6; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 6; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTri(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector3& p3) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[3] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 3; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTriangles(const AZStd::vector& vertices, const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = vertices.data(); + drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTrianglesIndexed( + const AZStd::vector& vertices, + const AZStd::vector& indices, + const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicIndexedDrawArguments drawArgs; + drawArgs.m_verts = vertices.data(); + drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_indices = indices.data(); + drawArgs.m_indexCount = aznumeric_cast(indices.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireBox(const AZ::Vector3& min, const AZ::Vector3& max) + { + if (m_auxGeomPtr) + { + m_auxGeomPtr->DrawAabb( + AZ::Aabb::CreateFromMinMax(min, max), + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidBox(const AZ::Vector3& min, const AZ::Vector3& max) + { + if (m_auxGeomPtr) + { + m_auxGeomPtr->DrawAabb( + AZ::Aabb::CreateFromMinMax(min, max), + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidOBB( + const AZ::Vector3& center, + const AZ::Vector3& axisX, + const AZ::Vector3& axisY, + const AZ::Vector3& axisZ, + const AZ::Vector3& halfExtents) + { + if (m_auxGeomPtr) + { + AZ::Quaternion rotation = AZ::Quaternion::CreateFromMatrix3x3(AZ::Matrix3x3::CreateFromColumns(axisX, axisY, axisZ)); + AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(center, rotation, halfExtents); + m_auxGeomPtr->DrawObb( + obb, + AZ::Vector3::CreateZero(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + } + + void AtomDebugDisplayViewportInterface::DrawPoint(const AZ::Vector3& p, int nSize) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoint = ToWorldSpacePosition(p); + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = &wsPoint; + drawArgs.m_vertCount = 1; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = aznumeric_cast(nSize); + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPoints(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector4& col1, const AZ::Vector4& col2) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; + AZ::Color colors[2] = {col1, col2}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 2; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLines(const AZStd::vector& lines, const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = lines.data(); + drawArgs.m_vertCount = aznumeric_cast(lines.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawPolyLine(const AZ::Vector3* pnts, int numPoints, bool cycled) + { + if (m_auxGeomPtr) + { + AZStd::vector wsPoints(static_cast(numPoints)); + for (int index = 0; index < numPoints; ++index) + { + wsPoints[index] = ToWorldSpacePosition(pnts[index]); + } + AZ::RPI::AuxGeomDraw::PolylineEnd polylineEnd = cycled ? AZ::RPI::AuxGeomDraw::PolylineEnd::Closed : AZ::RPI::AuxGeomDraw::PolylineEnd::Open; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = wsPoints.data(); + drawArgs.m_vertCount = aznumeric_cast(numPoints); + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPolylines(drawArgs, polylineEnd); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[4]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p1.GetY(), z); + points[2] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + points[3] = AZ::Vector3(p1.GetX(), p2.GetY(), z); + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 4; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[2]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine2dGradient(const AZ::Vector2& p1, const AZ::Vector2& p2, float z, const AZ::Vector4& firstColor, const AZ::Vector4& secondColor) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[2]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + AZ::Color colors[2] = {firstColor, secondColor}; + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 2; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCircle2d(const AZ::Vector2& center, float radius, float z) + { + if (m_auxGeomPtr) + { + // Draw axis aligned arc + constexpr float angularStepDegrees = 10.0f; + constexpr float startAngleDegrees = 0.0f; + constexpr float sweepAngleDegrees = 360.0f; + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + AZ::Vector3 pos = AZ::Vector3(center.GetX(), center.GetY(), z); + CreateAxisAlignedArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + CircleAxis::CircleAxisZ + ); + lines.Draw2d(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawArc( + const AZ::Vector3& pos, + float radius, + float startAngleDegrees, + float sweepAngleDegrees, + float angularStepDegrees, + int referenceAxis) + { + if (m_auxGeomPtr) + { + // Draw axis aligned arc + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateAxisAlignedArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + static_cast(referenceAxis) + ); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawArc( + const AZ::Vector3& pos, + float radius, + float startAngleDegrees, + float sweepAngleDegrees, + float angularStepDegrees, + const AZ::Vector3& fixedAxis) + { + if (m_auxGeomPtr) + { + // Draw arbitraty axis arc + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateArbitraryAxisArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + fixedAxis + ); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawCircle(const AZ::Vector3& pos, float radius, int nUnchangedAxis) + { + if (m_auxGeomPtr) + { + // Draw circle with default radius. + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateAxisAlignedArc( + lines, + step, + 0.0f, + maxAngle, + pos, + radiusV3, + static_cast(nUnchangedAxis)); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawHalfDottedCircle(const AZ::Vector3& pos, float radius, const AZ::Vector3& viewPos, int nUnchangedAxis) + { + if (m_auxGeomPtr) + { + // Draw circle with single radius. + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. + + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldView = ToWorldSpacePosition(viewPos); + const AZ::Vector3 worldDir = worldView - worldPos; + + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, radiusV3, static_cast(nUnchangedAxis%CircleAxisMax), + [&worldPos, &worldDir](const AZ::Vector3& lineStart, const AZ::Vector3& lineEnd, int segmentIndex) + { + AZ_UNUSED(lineEnd); + const float dot = (lineStart - worldPos).Dot(worldDir); + const bool facing = dot > 0.0f; + // if so skip every other line to produce a dotted effect + if (facing || segmentIndex % 2 == 0) + { + return true; + } + return false; + }); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); + m_auxGeomPtr->DrawCone( + worldPos, + worldDir, + radius, + height, + m_rendState.m_color, + drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinder( + worldCenter, + worldAxis, + radius, + height, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidCylinder( + const AZ::Vector3& center, + const AZ::Vector3& axis, + float radius, + float height, + bool drawShaded) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinder( + worldCenter, + worldAxis, + radius, + height, + m_rendState.m_color, + drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCapsule( + const AZ::Vector3& center, + const AZ::Vector3& axis, + float radius, + float heightStraightSection) + { + if (m_auxGeomPtr && radius > FLT_EPSILON && axis.GetLengthSq() > FLT_EPSILON) + { + AZ::Vector3 axisNormalized = axis.GetNormalizedEstimate(); + SingleColorStaticSizeLineHelper<(16+1) * 5> lines; // 360/22.5 = 16, 5 possible calls to CreateArbitraryAxisArc + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + float stepAngle = DegToRad(22.5f); + float Deg0 = DegToRad(0.0f); + + + // Draw cylinder part (or just a circle around the middle) + if (heightStraightSection > FLT_EPSILON) + { + DrawWireCylinder(center, axis, radius, heightStraightSection); + } + else + { + float Deg360 = DegToRad(360.0f); + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg0, + Deg360, + center, + radiusV3, + axisNormalized + ); + } + + float Deg90 = DegToRad(90.0f); + float Deg180 = DegToRad(180.0f); + + AZ::Vector3 ortho1Normalized, ortho2Normalized; + CalcBasisVectors(axisNormalized, ortho1Normalized, ortho2Normalized); + AZ::Vector3 centerToTopCircleCenter = axisNormalized * heightStraightSection * 0.5f; + AZ::Vector3 topCenter = center + centerToTopCircleCenter; + AZ::Vector3 bottomCenter = center - centerToTopCircleCenter; + + // Draw top cap as two criss-crossing 180deg arcs + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg90, + Deg90 + Deg180, + topCenter, + radiusV3, + ortho1Normalized + ); + + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg180, + Deg180 + Deg180, + topCenter, + radiusV3, + ortho2Normalized + ); + + // Draw bottom cap + CreateArbitraryAxisArc( + lines, + stepAngle, + -Deg90, + -Deg90 + Deg180, + bottomCenter, + radiusV3, + ortho1Normalized + ); + + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg0, + Deg0 + Deg180, + bottomCenter, + radiusV3, + ortho2Normalized + ); + + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, float radius) + { + if (m_auxGeomPtr) + { + + m_auxGeomPtr->DrawSphere( + ToWorldSpacePosition(pos), + radius, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) + { + if (m_auxGeomPtr) + { + // This matches Cry behavior, the DrawWireSphere above may need modifying to use the same approach. + // Draw 3 axis aligned circles + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40*3> lines; // hard code to 40 lines * 3 circles until DegToRad is constexpr. + + // Z Axis + AZ::Vector3 axisRadius(radius.GetX(), radius.GetY(), 0.0f); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisZ); + + // X Axis + axisRadius = AZ::Vector3(0.0f, radius.GetY(), radius.GetZ()); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisX); + + // Y Axis + axisRadius = AZ::Vector3(radius.GetX(), 0.0f, radius.GetZ()); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisY); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) + { + if (m_auxGeomPtr) + { + + // Draw 3 axis aligned circles + const float stepAngle = DegToRad(11.25f); + const float startAngle = DegToRad(0.0f); + const float stopAngle = DegToRad(360.0f) + startAngle; + SingleColorDynamicSizeLineHelper lines(2+static_cast(360.0f/11.25f)); // num disk segments + 1 for azis line + 1 for spare + const AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateArbitraryAxisArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + dir + ); + + lines.AddLineSegment(ToWorldSpacePosition(pos), ToWorldSpacePosition(pos + dir * (radius * 0.2f))); // 0.2f comes from Code\Sandbox\Editor\Objects\DisplayContextShared.inl DisplayContext::DrawWireDisk + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded) + { + if (m_auxGeomPtr) + { + // get the max scaled radius in case the transform on the stack is scaled non-uniformly + const float transformedRadiusX = ToWorldSpaceVector(AZ::Vector3(radius, 0.0f, 0.0f)).GetLengthEstimate(); + const float transformedRadiusY = ToWorldSpaceVector(AZ::Vector3(0.0f, radius, 0.0f)).GetLengthEstimate(); + const float transformedRadiusZ = ToWorldSpaceVector(AZ::Vector3(0.0f, 0.0f, radius)).GetLengthEstimate(); + const float maxTransformedRadius = + AZ::GetMax(transformedRadiusX, AZ::GetMax(transformedRadiusY, transformedRadiusZ)); + + AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid; + m_auxGeomPtr->DrawSphere( + ToWorldSpacePosition(pos), + maxTransformedRadius, + m_rendState.m_color, + drawStyle, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); + m_auxGeomPtr->DrawDisk( + worldPos, + worldDir, + radius, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawArrow(const AZ::Vector3& src, const AZ::Vector3& trg, float headScale, bool dualEndedArrow) + { + if (m_auxGeomPtr) + { + float f2dScale = 1.0f; + float arrowLen = 0.4f * headScale; + float arrowRadius = 0.1f * headScale; + // if (flags & DISPLAY_2D) + // { + // f2dScale = 1.2f * ToWorldSpaceVector(Vec3(1, 0, 0)).GetLength(); + // } + AZ::Vector3 dir = trg - src; + dir = ToWorldSpaceVector(dir.GetNormalized()); + AZ::Vector3 verts[2] = {ToWorldSpacePosition(src), ToWorldSpacePosition(trg)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + if (!dualEndedArrow) + { + verts[1] -= dir * arrowLen; + m_auxGeomPtr->DrawLines(drawArgs); + m_auxGeomPtr->DrawCone( + verts[1], + dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + else + { + verts[0] += dir * arrowLen; + verts[1] -= dir * arrowLen; + m_auxGeomPtr->DrawLines(drawArgs); + m_auxGeomPtr->DrawCone( + verts[0], + -dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + m_auxGeomPtr->DrawCone( + verts[1], + dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + } + + void AtomDebugDisplayViewportInterface::DrawTextLabel( + const AZ::Vector3& pos, + float size, + const char* text, + const bool center, + int srcOffsetX [[maybe_unused]], + int srcOffsetY [[maybe_unused]]) + { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); + // abort draw if font draw interface is missing + if (!fontDrawInterface) + { + return; + } + // if 2d draw need to project pos to screen first + AzFramework::TextDrawParameters params; + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works + params.m_position = pos; + 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 + params.m_monospace = false; //! disable character proportional spacing + params.m_depthTest = false; //! Test character against the depth buffer + params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger + params.m_multiline = true; //! text respects ascii newline characters + + fontDrawInterface->DrawScreenAlignedText3d(params, text); + } + + void AtomDebugDisplayViewportInterface::Draw2dTextLabel( + float x, + float y, + float size, + const char* text, + bool center) + { +<<<<<<< HEAD + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); + // abort draw if font draw interface is missing + if (!fontDrawInterface) +======= + auto fontQueryInterface = AZ::Interface::Get(); + if (!fontQueryInterface) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = fontQueryInterface->GetDefaultFontDrawInterface(); + if (!fontDrawInterface || !text || size == 0.0f) +>>>>>>> upstream/main + { + return; + } + // if 2d draw need to project pos to screen first + AzFramework::TextDrawParameters params; + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works + params.m_position = AZ::Vector3(x, y, 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 + params.m_monospace = false; //! disable character proportional spacing + params.m_depthTest = false; //! Test character against the depth buffer + params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger + params.m_multiline = true; //! text respects ascii newline characters + + fontDrawInterface->DrawScreenAlignedText2d(params, text); + } + + void AtomDebugDisplayViewportInterface::DrawTextOn2DBox( + const AZ::Vector3& pos [[maybe_unused]], + const char* text [[maybe_unused]], + float textScale [[maybe_unused]], + const AZ::Vector4& TextColor [[maybe_unused]], + const AZ::Vector4& TextBackColor [[maybe_unused]]) + { + AZ_Assert(false, "Unexpected use of legacy api, please file a feature request with the rendering team to get this implemented!"); + } + // unhandledled on Atom - virtual void DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; + // void AtomDebugDisplayViewportInterface::DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; + + void AtomDebugDisplayViewportInterface::SetLineWidth(float width) + { + AZ_Assert(width >= 0.0f && width <= 255.0f, "Width (%f) exceeds allowable range [0 - 255]", width); + m_rendState.m_lineWidth = static_cast(width); + } + + bool AtomDebugDisplayViewportInterface::IsVisible(const AZ::Aabb& bounds) + { + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + const AZ::Matrix4x4& worldToClip = viewportContext->GetDefaultView()->GetWorldToClipMatrix(); + AZ::Frustum frustum = AZ::Frustum::CreateFromMatrixColumnMajor(worldToClip, Frustum::ReverseDepth::True); + return frustum.IntersectAabb(bounds) != AZ::IntersectResult::Exterior; + } + // int AtomDebugDisplayViewportInterface::SetFillMode(int nFillMode) override; + float AtomDebugDisplayViewportInterface::GetLineWidth() + { + return m_rendState.m_lineWidth; + } + + float AtomDebugDisplayViewportInterface::GetAspectRatio() + { + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + auto windowSize = viewportContext->GetViewportSize(); + return aznumeric_cast(windowSize.m_width)/aznumeric_cast(windowSize.m_height); + } + + void AtomDebugDisplayViewportInterface::DepthTestOff() + { + m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::Off; + } + + void AtomDebugDisplayViewportInterface::DepthTestOn() + { + m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::On; + } + + void AtomDebugDisplayViewportInterface::DepthWriteOff() + { + m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::Off; + } + + void AtomDebugDisplayViewportInterface::DepthWriteOn() + { + m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::On; + } + + void AtomDebugDisplayViewportInterface::CullOff() + { + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::None; + } + + void AtomDebugDisplayViewportInterface::CullOn() + { + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Back; + } + + bool AtomDebugDisplayViewportInterface::SetDrawInFrontMode(bool on) + { + AZ_UNUSED(on); + return false; + } + + AZ::u32 AtomDebugDisplayViewportInterface::GetState() + { + return ConvertRenderStateToCry(); + } + + AZ::u32 AtomDebugDisplayViewportInterface::SetState(AZ::u32 state) + { + uint32_t currentState = ConvertRenderStateToCry(); + uint32_t changedState = (state & e_PublicParamsMask) ^ currentState; + + if (changedState & e_Mode2D3DMask) + { + // this is the only way to turn on 2d Mode under Atom + if (state & e_Mode2D) + { + AZ_Assert((currentState & e_DrawInFrontOn) == 0 && (changedState & e_DrawInFrontOn) == 0, "Atom doesnt support Draw In Front and 2d at the same time"); + m_rendState.m_viewProjOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_rendState.m_2dMode = true; + } + else // switch back to mode 3d + { + m_rendState.m_viewProjOverrideIndex = -1; + m_rendState.m_2dMode = false; + } + } + + if (changedState & e_AlphaBlendingMask) + { + switch (state&e_AlphaBlendingMask) + { + case e_AlphaNone: + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; + break; + case e_AlphaAdditive: + [[fallthrough]]; // Additive not currently supported in Atom AuxGeom implementation + case e_AlphaBlended: + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; + break; + } + } + + if (changedState & e_DrawInFrontMask) + { + AZ_Assert( // either state is turning DrawInFront off or Mode 2D has to be off + (state & e_DrawInFrontOn) == 0 || + ((currentState & e_Mode2D) == 0 && (changedState & e_Mode2D) == 0), + "Atom doesnt support Draw In Front and 2d at the same time"); + SetDrawInFrontMode(changedState & e_DrawInFrontOn); + } + + if (changedState & e_CullModeMask) + { + switch (state & e_CullModeMask) + { + case e_CullModeNone: + CullOff(); + break; + case e_CullModeFront: + // Currently no other way to set front face culling in DebugDisplayRequestBus + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Front; + break; + case e_CullModeBack: + CullOn(); + break; + } + } + + if (changedState & e_DepthWriteMask) + { + if (state & e_DepthWriteOff) + { + DepthWriteOff(); + } + else + { + DepthWriteOn(); + } + } + + if (changedState & e_DepthTestMask) + { + if (state & e_DepthTestOff) + { + DepthTestOff(); + } + else + { + DepthTestOn(); + } + } + + return currentState; + } + + void AtomDebugDisplayViewportInterface::PushMatrix(const AZ::Transform& tm) + { + AZ_Assert(m_rendState.m_currentTransform < RenderState::TransformStackSize, "Exceeded AtomDebugDisplayViewportInterface matrix stack size"); + if (m_rendState.m_currentTransform < RenderState::TransformStackSize) + { + m_rendState.m_currentTransform++; + m_rendState.m_transformStack[m_rendState.m_currentTransform] = m_rendState.m_transformStack[m_rendState.m_currentTransform - 1] * AZ::Matrix3x4::CreateFromTransform(tm); + } + } + + void AtomDebugDisplayViewportInterface::PopMatrix() + { + AZ_Assert(m_rendState.m_currentTransform > 0, "Underflowed AtomDebugDisplayViewportInterface matrix stack"); + if (m_rendState.m_currentTransform > 0) + { + m_rendState.m_currentTransform--; + } + } + + const AZ::Matrix3x4& AtomDebugDisplayViewportInterface::GetCurrentTransform() const + { + return m_rendState.m_transformStack[m_rendState.m_currentTransform]; + } + + AZ::RPI::ViewportContextPtr AtomDebugDisplayViewportInterface::GetViewportContext() const + { + auto viewContextManager = AZ::Interface::Get(); + if (m_defaultInstance) + { + return viewContextManager->GetViewportContextByName(viewContextManager->GetDefaultViewportContextName()); + } + else + { + return viewContextManager->GetViewportContextById(m_viewportId); + } + } + + uint32_t AtomDebugDisplayViewportInterface::ConvertRenderStateToCry() const + { + uint32_t result = 0; + + result |= m_rendState.m_2dMode ? e_Mode2D : e_Mode3D; + result |= m_rendState.m_opacityType == AZ::RPI::AuxGeomDraw::OpacityType::Opaque ? e_AlphaNone : e_AlphaBlended; + result |= m_rendState.m_drawInFront ? e_DrawInFrontOn : e_DrawInFrontOff; + result |= m_rendState.m_depthTest == AZ::RPI::AuxGeomDraw::DepthTest::On ? e_DepthTestOn : e_DepthTestOff; + result |= m_rendState.m_depthWrite == AZ::RPI::AuxGeomDraw::DepthWrite::On ? e_DepthWriteOn : e_DepthWriteOff; + switch (m_rendState.m_faceCullMode) + { + case AZ::RPI::AuxGeomDraw::FaceCullMode::None: + result |= e_CullModeNone; + break; + case AZ::RPI::AuxGeomDraw::FaceCullMode::Front: + result |= e_CullModeFront; + break; + case AZ::RPI::AuxGeomDraw::FaceCullMode::Back: + result |= e_CullModeBack; + break; + default: + AZ_Assert(false, "Trying to convert an unknown culling mode to cry!"); + break; + } + + return result; + } +} diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index 021d816ca4..4520b60041 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -25,6 +25,7 @@ #include #include #include +#include namespace AZ::AtomBridge { @@ -121,6 +122,7 @@ namespace AZ::AtomBridge class AtomDebugDisplayViewportInterface final : public AzFramework::DebugDisplayRequestBus::Handler + , public AZ::RPI::ViewportContextIdNotificationBus::Handler { public: AZ_RTTI(AtomDebugDisplayViewportInterface, "{09AF6A46-0100-4FBF-8F94-E6B221322D14}", AzFramework::DebugDisplayRequestBus::Handler); @@ -198,6 +200,12 @@ namespace AZ::AtomBridge void PopMatrix() override; private: + + // ViewportContextIdNotificationBus handlers + void OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) override; + + + // internal helper functions using LineSegmentFilterFunc = AZStd::function; enum CircleAxis { @@ -245,6 +253,7 @@ namespace AZ::AtomBridge const AZ::Matrix3x4& GetCurrentTransform() const; + void UpdateAuxGeom(RPI::Scene* scene, AZ::RPI::View* view); void InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr); AZ::RPI::ViewportContextPtr GetViewportContext() const; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 8e60cc2055..fd66534197 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -226,7 +226,7 @@ namespace AZ private: virtual ~FFont(); - bool InitFont(); + bool InitFont(AZ::RPI::Scene* renderScene); bool InitTexture(); bool InitCache(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 20879876e7..d36307e4ec 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -99,7 +99,7 @@ AZ::RPI::WindowContextSharedPtr AZ::FFont::GetDefaultWindowContext() const return {}; } -bool AZ::FFont::InitFont() +bool AZ::FFont::InitFont(AZ::RPI::Scene* renderScene) { auto initializationState = InitializationState::Uninitialized; // Do an atomic transition to Initializing if we're in the Uninitialized state. @@ -111,8 +111,13 @@ bool AZ::FFont::InitFont() return initializationState == InitializationState::Initialized; } + if (!renderScene) + { + return false; + } + // Create and initialize DynamicDrawContext for font draw - AZ::RPI::Ptr dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(GetDefaultViewportContext()->GetRenderScene().get()); + AZ::RPI::Ptr dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(renderScene); // Save draw srg input indices for later use Data::Instance drawSrg = dynamicDraw->NewDrawSrg(); @@ -299,7 +304,7 @@ void AZ::FFont::DrawStringUInternal( const TextDrawContext& ctx) { // Lazily ensure we're initialized before attempting to render. - if (!InitFont()) + if (!viewportContext || !InitFont(viewportContext->GetRenderScene().get())) { return; } @@ -1623,7 +1628,7 @@ void AZ::FFont::ScaleCoord(const RHI::Viewport& viewport, float& x, float& y) co void AZ::FFont::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapScene) { - InitFont(); + InitFont(bootstrapScene); } static void SetCommonContextFlags(AZ::TextDrawContext& ctx, const AzFramework::TextDrawParameters& params) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index 8c5f6d6836..a77bcfdd12 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -336,6 +336,7 @@ namespace AZ bool needsFullRefresh = HandleLightTypeChange(); LmbrCentral::EditorShapeComponentRequestsBus::Event(GetEntityId(), &LmbrCentral::EditorShapeComponentRequests::SetShapeColor, m_controller.m_configuration.m_color); + LmbrCentral::EditorShapeComponentRequestsBus::Event(GetEntityId(), &LmbrCentral::EditorShapeComponentRequests::SetShapeWireframeColor, m_controller.m_configuration.m_color); // If photometric unit changes, convert the intensities so the actual intensity doesn't change. m_controller.ConvertToIntensityMode(m_controller.m_configuration.m_intensityMode); From f6479aca98f14b1d371fa438903cc6fdedf54898 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Mon, 3 May 2021 11:37:08 -0700 Subject: [PATCH 015/112] Fixed ATOM-15434 "Decal + POM (Grey outline issue)" Made sure the depth and shadow shaders enable parallax calculations when alpha clipping is enabled (instead of only when parallax POM is enabled). Moved the alpha calculations to be *after* the parallax calculations. Factored out ShouldHandleParallax() and ShouldHandleParallaxInDepthShaders() utility functions, which help us ensure consistent application of parallax calculations across the various shaders in each material type. Removed some dead code in a couple shaders where dirToCamera was calculated but not used. Also did ATOM-15034 "Remove Opacity From Multi-Layer Material Types For Now" rather than addressing whatever additional alpha cutout issues might be present on multilayer materials. Testing: AtomSampleViewer full test suite. Added a new AtomSampleViewer screenshot test for alpha clipping with parallax (separate repo). Addional testing of relevant properties in Matirial Editor. Tested updated StandardMultilayerPBR in Editor.exe where I had shadows and clipping against other geometry. --- .../Materials/Types/EnhancedPBR_Common.azsli | 17 +++ .../Types/EnhancedPBR_DepthPass_WithPS.azsl | 20 ++-- .../Types/EnhancedPBR_ForwardPass.azsl | 10 +- .../Types/EnhancedPBR_Shadowmap_WithPS.azsl | 34 ++---- .../Types/StandardMultilayerPBR.materialtype | 106 +----------------- .../Types/StandardMultilayerPBR_Common.azsli | 27 ++++- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 15 +-- .../StandardMultilayerPBR_ForwardPass.azsl | 51 +++------ .../StandardMultilayerPBR_ShaderEnable.lua | 39 +++++++ ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 17 +-- .../Materials/Types/StandardPBR_Common.azsli | 16 +++ .../Types/StandardPBR_DepthPass_WithPS.azsl | 18 ++- .../Types/StandardPBR_ForwardPass.azsl | 10 +- .../Types/StandardPBR_Shadowmap_WithPS.azsl | 32 ++---- 14 files changed, 167 insertions(+), 245 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli index fd6961c50d..314f15e8e1 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli @@ -14,6 +14,8 @@ #include #include +#include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -107,3 +109,18 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } + +COMMON_OPTIONS_PARALLAX() + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer, or when + // parallax could affect texel clipping. + return ShouldHandleParallax() && (o_parallax_enablePixelDepthOffset || o_opacity_mode == OpacityMode::Cutout); +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl index 5d6c0fafd8..1aeed26697 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl @@ -11,7 +11,6 @@ */ #include -#include #include "./EnhancedPBR_Common.azsli" #include #include @@ -56,7 +55,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -75,15 +74,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Clip Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -97,5 +90,12 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + // Clip Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 7d50cbf69b..09a16556d6 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -26,8 +26,8 @@ COMMON_OPTIONS_NORMAL() COMMON_OPTIONS_CLEAR_COAT() COMMON_OPTIONS_OCCLUSION() COMMON_OPTIONS_EMISSIVE() -COMMON_OPTIONS_PARALLAX() COMMON_OPTIONS_DETAIL_MAPS() +// Note COMMON_OPTIONS_PARALLAX is in StandardPBR_Common.azsli because it's needed by all StandardPBR shaders. // Alpha #include "MaterialInputs/AlphaInput.azsli" @@ -67,7 +67,6 @@ struct VSOutput float2 m_detailUv[UvSetCount] : UV3; }; -#include #include #include @@ -88,8 +87,11 @@ VSOutput EnhancedPbr_ForwardPassVS(VSInput IN) // but we would need to address how it works with the parallax code below that indexes into the m_detailUV array. OUT.m_detailUv[0] = mul(MaterialSrg::m_detailUvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_detailUv[1] = mul(MaterialSrg::m_detailUvMatrix, float3(IN.m_uv1, 1.0)).xy; + + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; - VertexHelper(IN, OUT, worldPosition, o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset); + VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; } @@ -119,7 +121,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) + if(ShouldHandleParallax()) { // GetParallaxInput applies an tangent offset to the UV. We want to apply the same offset to the detailUv (note: this needs to be tested with content) // The math is: offset = newUv - oldUv; detailUv += offset; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl index e344886c4b..70b3f51804 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl @@ -13,7 +13,6 @@ #include #include #include "EnhancedPBR_Common.azsli" -#include #include #include #include @@ -55,8 +54,8 @@ VertexOutput MainVS(VertexInput IN) // By design, only UV0 is allowed to apply transforms. OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -76,27 +75,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Clip Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - - float3 dirToCamera; - if(ViewSrg::m_projectionMatrix[0].w) - { - // orthographic projection (directional light) - // No view position, use light direction - dirToCamera = ViewSrg::m_viewMatrix[2].xyz; - } - else - { - dirToCamera = ViewSrg::m_worldPosition.xyz - IN.m_worldPosition; - } - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { static const float ShadowMapDepthBias = 0.000001; @@ -114,5 +95,12 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth += ShadowMapDepthBias; } + + // Clip Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 7610a4c9db..780a055c78 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -18,11 +18,6 @@ "displayName": "Parallax Settings", "description": "Properties for configuring the parallax effect, applied to all layers." }, - { - "id": "opacity", - "displayName": "Opacity", - "description": "Properties for configuring the materials transparency." - }, { "id": "uv", "displayName": "UVs", @@ -410,73 +405,6 @@ } } ], - "opacity": [ - { - "id": "mode", - "displayName": "Opacity Mode", - "description": "Opacity mode for this texture.", - "type": "Enum", - "enumValues": [ "Opaque", "Cutout", "Blended" ], - "defaultValue": "Opaque", - "connection": { - "type": "ShaderOption", - "id": "o_opacity_mode" - } - }, - { - "id": "alphaSource", - "displayName": "Alpha Source", - "description": "Source texture of alpha value.", - "type": "Enum", - "enumValues": [ "Packed", "Split", "None" ], - "defaultValue": "Packed", - "connection": { - "type": "ShaderOption", - "id": "o_opacity_source" - } - }, - { - "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface opacity.", - "type": "Image", - "connection": { - "type": "ShaderInput", - "id": "m_opacityMap" - } - }, - { - "id": "textureMapUv", - "displayName": "UV", - "description": "Opacity texture map UV set", - "type": "Enum", - "enumIsUv": true, - "defaultValue": "Tiled", - "connection": { - "type": "ShaderInput", - "id": "m_opacityMapUvIndex" - } - }, - { - "id": "factor", - "displayName": "Factor", - "description": "Factor for cutout threshold and blending", - "type": "Float", - "min": 0.0, - "max": 1.0, - "defaultValue": 0.5, - "connection": { - "type": "ShaderInput", - "id": "m_opacityFactor" - } - }, - { - "id": "doubleSided", - "displayName": "Double-sided", - "description": "Whether to render back-faces or just front-faces.", - "type": "Bool" - } - ], "uv": [ { "id": "center", @@ -2851,16 +2779,7 @@ { "file": "Shaders/MotionVector/SkinnedMeshMotionVector.shader", "tag": "SkinnedMeshMotionVector" - }, - // Used by the light culling system to produce accurate depth bounds for this object when it uses blended transparency - { - "file": "Shaders/Depth/DepthPassTransparentMin.shader", - "tag": "DepthPassTransparentMin" - }, - { - "file": "Shaders/Depth/DepthPassTransparentMax.shader", - "tag": "DepthPassTransparentMax" - } + } ], "functors": [ //############################################################################################## @@ -2885,7 +2804,7 @@ { "type": "Lua", "args": { - "file": "StandardPBR_ShaderEnable.lua" + "file": "StandardMultilayerPBR_ShaderEnable.lua" } }, { @@ -2925,27 +2844,6 @@ "file": "StandardPBR_SubsurfaceState.lua" } }, - { - "type": "Lua", - "args": { - "file": "StandardPBR_HandleOpacityDoubleSided.lua" - } - }, - { - "type": "OverrideDrawList", - "args": { - "triggerProperty": "opacity.mode", - "triggerValue": "Blended", - "shaderIndex": 1, - "drawList": "transparent" - } - }, - { - "type": "Lua", - "args": { - "file": "StandardPBR_HandleOpacityMode.lua" - } - }, //############################################################################################## // Layer 1 Functors //############################################################################################## diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index db3ec45e0c..93cf9fdb7c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -14,6 +14,7 @@ #include #include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -26,6 +27,8 @@ #include "MaterialInputs/ParallaxInput.azsli" #include "MaterialInputs/UvSetCount.azsli" +// ------ ShaderResourceGroup ---------------------------------------- + #define DEFINE_LAYER_SRG_INPUTS(prefix) \ COMMON_SRG_INPUTS_BASE_COLOR(prefix) \ COMMON_SRG_INPUTS_ROUGHNESS(prefix) \ @@ -64,10 +67,6 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial float3x3 m_uvMatrixInverse; float4 m_pad5; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. - float m_opacityFactor; - Texture2D m_opacityMap; - uint m_opacityMapUvIndex; - Sampler m_sampler { AddressU = Wrap; @@ -109,6 +108,8 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial uint m_transmissionThicknessMapUvIndex; } +// ------ Shader Options ---------------------------------------- + enum class DebugDrawMode { None, BlendMaskValues, DepthMaps }; option DebugDrawMode o_debugDrawMode; @@ -121,6 +122,8 @@ option BlendMaskSource o_blendSource; // [GFX TODO][ATOM-14475]: Come up with a more elegant way to associate the isBound flag with the input stream. option bool o_blendMask_isBound; +// ------ Blend Utilities ---------------------------------------- + //! Returns the BlendMaskSource that will actually be used when rendering (not necessarily the same BlendMaskSource specified by the user) BlendMaskSource GetFinalBlendMaskSource() { @@ -181,6 +184,22 @@ float3 BlendLayers(float3 layer1, float3 layer2, float3 layer3, float3 blendMask return layer1 * blendMaskValues.r + layer2 * blendMaskValues.g + layer3 * blendMaskValues.b; } +// ------ Parallax Utilities ---------------------------------------- + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + // Also, all the debug draw modes avoid parallax (they early-return before parallax code actually) so you can see exactly where the various maps appear on the surface UV space. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_debugDrawMode == DebugDrawMode::None; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer (or when + // parallax could affect texel clipping but we don't have alpha/clipping support in multilayer PBR). + return ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; +} + // These static values are used to pass extra data to the GetDepth callback function during the parallax depth search. static float3 s_blendMaskFromVertexStream; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index 8e25292e9c..bc8045f412 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -11,12 +11,10 @@ */ #include -#include #include #include #include -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" @@ -72,7 +70,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -101,18 +99,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 layer1_baseColorUV = IN.m_uv[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUV = IN.m_uv[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = SampleAlpha(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index 05a40d0f9d..3f49152c1c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -42,7 +42,6 @@ DEFINE_LAYER_OPTIONS(o_layer1_) DEFINE_LAYER_OPTIONS(o_layer2_) DEFINE_LAYER_OPTIONS(o_layer3_) -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/SubsurfaceInput.azsli" #include "MaterialInputs/TransmissionInput.azsli" #include "StandardMultilayerPBR_Common.azsli" @@ -83,7 +82,7 @@ struct VSOutput float3 m_blendMask : UV7; }; -#include +#include // TODO: Remove this after OpacityMode is removed from LightingModel #include #include @@ -107,9 +106,8 @@ VSOutput ForwardPassVS(VSInput IN) OUT.m_blendMask = float3(1,1,1); } - // We can skip per-vertex shadow coords when parallax is enabled because we need to calculate per-pixel shadow coords anyway. - // We cannot skip shadow coords when o_debugDrawMode is on because some debug draw modes return before parallax. - bool skipShadowCoords = o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset; + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; @@ -157,7 +155,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Parallax ------- // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled) + if(ShouldHandleParallax()) { GetDepth_Setup(IN.m_blendMask); @@ -199,15 +197,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // Now that any parallax has been calculated, we calculate the blend factors for any layers that are impacted by the parallax. float3 blendMaskValues = GetBlendMaskValues(IN.m_uv[MaterialSrg::m_blendMaskUvIndex], IN.m_blendMask); - // ------- Alpha & Clip ------- - - float2 layer1_baseColorUv = uvLayer1[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUv = uvLayer2[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 layer3_baseColorUv = uvLayer3[MaterialSrg::m_layer3_m_baseColorMapUvIndex]; - float2 opacityUv = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = GetAlphaInputAndClip(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUv, opacityUv, MaterialSrg::m_sampler, MaterialSrg::m_opacityFactor, o_opacity_source); - // ------- Normal ------- float3 layer1_normalFactor = MaterialSrg::m_layer1_m_normalFactor * blendMaskValues.r; @@ -226,6 +215,10 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 normalWS = normalize(TangentSpaceToWorld(normalTS, IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex])); // ------- Base Color ------- + + float2 layer1_baseColorUv = uvLayer1[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; + float2 layer2_baseColorUv = uvLayer2[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; + float2 layer3_baseColorUv = uvLayer3[MaterialSrg::m_layer3_m_baseColorMapUvIndex]; float3 layer1_sampledColor = GetBaseColorInput(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_sampler, layer1_baseColorUv, MaterialSrg::m_layer1_m_baseColor.rgb, o_layer1_o_baseColor_useTexture); float3 layer2_sampledColor = GetBaseColorInput(MaterialSrg::m_layer2_m_baseColorMap, MaterialSrg::m_sampler, layer2_baseColorUv, MaterialSrg::m_layer2_m_baseColor.rgb, o_layer2_o_baseColor_useTexture); @@ -352,34 +345,18 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Lighting Calculation ------- const float2 anisotropy = 0.0; // Does not affect calculations unless 'o_enableAnisotropy' is enabled + const float alpha = 1.0; PbrLightingOutput lightingOutput = PbrLighting(IN, baseColor, metallic, roughness, specularF0Factor, normalWS, tangents[0], bitangents[0], anisotropy, - emissive, diffuseAmbientOcclusion, specularOcclusion, transmissionTintThickness, MaterialSrg::m_transmissionParams, clearCoatFactor, clearCoatRoughness, clearCoatNormal, alpha, o_opacity_mode); + emissive, diffuseAmbientOcclusion, specularOcclusion, transmissionTintThickness, MaterialSrg::m_transmissionParams, clearCoatFactor, clearCoatRoughness, clearCoatNormal, alpha, OpacityMode::Opaque); - // ------- Opacity ------- - - if (o_opacity_mode == OpacityMode::Blended) - { - // [GFX_TODO ATOM-13187] PbrLighting shouldn't be writing directly to render targets. It's confusing when - // specular is being added to diffuse just because we're calling render target 0 "diffuse". - - // For blended mode, we do (dest * alpha) + (source * 1.0). This allows the specular - // to be added on top of the diffuse, but then the diffuse must be pre-multiplied. - // It's done this way because surface transparency doesn't really change specular response (eg, glass). - lightingOutput.m_diffuseColor.rgb *= lightingOutput.m_diffuseColor.w; // pre-multiply diffuse - lightingOutput.m_diffuseColor.rgb += lightingOutput.m_specularColor.rgb; // add specular - } - else - { - // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 - uint factorAndQuality = dot(round(float2(saturate(surfaceScatteringFactor), MaterialSrg::m_subsurfaceScatteringQuality) * 255), float2(256, 1)); - lightingOutput.m_diffuseColor.w = factorAndQuality * (o_enableSubsurfaceScattering ? 1.0 : -1.0); - lightingOutput.m_scatterDistance = MaterialSrg::m_scatterDistance; - } + // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 + uint factorAndQuality = dot(round(float2(saturate(surfaceScatteringFactor), MaterialSrg::m_subsurfaceScatteringQuality) * 255), float2(256, 1)); + lightingOutput.m_diffuseColor.w = factorAndQuality * (o_enableSubsurfaceScattering ? 1.0 : -1.0); + lightingOutput.m_scatterDistance = MaterialSrg::m_scatterDistance; - return lightingOutput; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua new file mode 100644 index 0000000000..69df610ab2 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua @@ -0,0 +1,39 @@ +-------------------------------------------------------------------------------------- +-- +-- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +-- its licensors. +-- +-- For complete copyright and license terms please see the LICENSE at the root of this +-- distribution (the "License"). All use of this software is governed by the License, +-- or, if provided, by the license below or the license accompanying this file. Do not +-- remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- +-- +---------------------------------------------------------------------------------------------------- + +function GetMaterialPropertyDependencies() + return {"parallax.enable", "parallax.pdo"} +end + +function Process(context) + local parallaxEnabled = context:GetMaterialPropertyValue_bool("parallax.enable") + local parallaxPdoEnabled = context:GetMaterialPropertyValue_bool("parallax.pdo") + + local depthPass = context:GetShaderByTag("DepthPass") + local shadowMap = context:GetShaderByTag("Shadowmap") + local forwardPassEDS = context:GetShaderByTag("ForwardPass_EDS") + local depthPassWithPS = context:GetShaderByTag("DepthPass_WithPS") + local shadowMapWitPS = context:GetShaderByTag("Shadowmap_WithPS") + local forwardPass = context:GetShaderByTag("ForwardPass") + + local shadingAffectsDepth = parallaxEnabled and parallaxPdoEnabled; + + depthPass:SetEnabled(not shadingAffectsDepth) + shadowMap:SetEnabled(not shadingAffectsDepth) + forwardPassEDS:SetEnabled(not shadingAffectsDepth) + + depthPassWithPS:SetEnabled(shadingAffectsDepth) + shadowMapWitPS:SetEnabled(shadingAffectsDepth) + forwardPass:SetEnabled(shadingAffectsDepth) +end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 0c9c186a11..6fa721ef47 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -12,12 +12,10 @@ #include #include -#include #include #include #include -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" @@ -71,7 +69,7 @@ VertexOutput MainVS(VertexInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -100,18 +98,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 layer1_baseColorUV = IN.m_uv[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUV = IN.m_uv[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = SampleAlpha(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -132,6 +121,6 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth = depth; } - + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index 70137a88c1..ee1533cf16 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -14,6 +14,8 @@ #include #include +#include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -97,3 +99,17 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } +COMMON_OPTIONS_PARALLAX() + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer, or when + // parallax could affect texel clipping. + return ShouldHandleParallax() && (o_parallax_enablePixelDepthOffset || o_opacity_mode == OpacityMode::Cutout); +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl index 3c04e9b391..5d0498dbe9 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl @@ -11,7 +11,6 @@ */ #include -#include #include "./StandardPBR_Common.azsli" #include #include @@ -57,7 +56,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -76,16 +75,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -99,7 +91,13 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + // Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index d55b865a27..4d12eb181d 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -26,7 +26,7 @@ COMMON_OPTIONS_NORMAL() COMMON_OPTIONS_CLEAR_COAT() COMMON_OPTIONS_OCCLUSION() COMMON_OPTIONS_EMISSIVE() -COMMON_OPTIONS_PARALLAX() +// Note COMMON_OPTIONS_PARALLAX is in StandardPBR_Common.azsli because it's needed by all StandardPBR shaders. // Alpha #include "MaterialInputs/AlphaInput.azsli" @@ -66,7 +66,6 @@ struct VSOutput float2 m_uv[UvSetCount] : UV1; }; -#include #include #include @@ -80,7 +79,10 @@ VSOutput StandardPbr_ForwardPassVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - VertexHelper(IN, OUT, worldPosition, o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset); + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; + + VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; } @@ -110,7 +112,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) + if(ShouldHandleParallax()) { float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl index 8f33b4cec6..cad951b5b5 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl @@ -13,7 +13,6 @@ #include #include #include "StandardPBR_Common.azsli" -#include #include #include #include @@ -57,7 +56,7 @@ VertexOutput MainVS(VertexInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -77,28 +76,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - float3 dirToCamera; - if(ViewSrg::m_projectionMatrix[0].w) - { - // orthographic projection (directional light) - // No view position, use light direction - dirToCamera = ViewSrg::m_viewMatrix[2].xyz; - } - else - { - dirToCamera = ViewSrg::m_worldPosition.xyz - IN.m_worldPosition; - } - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { static const float ShadowMapDepthBias = 0.000001; @@ -116,5 +96,13 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth += ShadowMapDepthBias; } + + // Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } From 83e06912432d2207a91cec158b3b8903f819fe52 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 14:58:15 -0500 Subject: [PATCH 016/112] Added some comments to clarify the role of the default instance --- .../Source/AtomDebugDisplayViewportInterface.cpp | 12 +++++------- .../Code/Source/AtomDebugDisplayViewportInterface.h | 8 +++++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 871d75f194..8a063cd7a7 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -282,12 +282,14 @@ namespace AZ::AtomBridge m_auxGeomPtr = nullptr; return; } + // default instance draws to all viewports in the default scene if (m_defaultInstance || !view) { m_auxGeomPtr = auxGeomFP->GetDrawQueue(); } else { + // cache the aux geom draw interface for the current view (aka camera) m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(view); } } @@ -297,7 +299,7 @@ namespace AZ::AtomBridge AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); UpdateAuxGeom(scene, viewportContextPtr ? viewportContextPtr->GetDefaultView().get() : nullptr); AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); - if (!m_defaultInstance) + if (!m_defaultInstance) // only the per viewport instances need to listen for viewport changes { AZ::RPI::ViewportContextIdNotificationBus::Handler::BusConnect(viewportContextPtr->GetId()); } @@ -307,13 +309,9 @@ namespace AZ::AtomBridge void AtomDebugDisplayViewportInterface::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) { ResetRenderState(); - if (m_defaultInstance) - { - RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - UpdateAuxGeom(scene, nullptr); - } - else + if (!m_defaultInstance) { + // handle viewport update (view change, scene change, etc auto viewportContextManager = AZ::Interface::Get(); AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); UpdateAuxGeom(viewportContextPtr->GetRenderScene().get(), viewportContextPtr->GetDefaultView().get()); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index 4520b60041..c872e2b81e 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -263,10 +263,12 @@ namespace AZ::AtomBridge RenderState m_rendState; AZ::RPI::AuxGeomDrawPtr m_auxGeomPtr; - bool m_defaultInstance = false; // only true for drawing to a particular viewport. What would 2D drawing mean in a scene with several windows? + + // m_defaultInstance is true for the instance that multicasts the debug draws to all viewports + // (with an AuxGeom render pass) in the default scene. + bool m_defaultInstance = false; AzFramework::ViewportId m_viewportId = AzFramework::InvalidViewportId; // Address this instance answers on. - AZ::RPI::ViewportContext::SceneChangedEvent::Handler - m_sceneChangeHandler; + AZ::RPI::ViewportContext::SceneChangedEvent::Handler m_sceneChangeHandler; }; // this is duplicated from Cry_Math.h, GetBasisVectors. From 1a712857d9534dfad45c16044747802ff88311ac Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 15:22:04 -0500 Subject: [PATCH 017/112] Delete a mistakenly commited .orig file --- ...AtomDebugDisplayViewportInterface.cpp.orig | 1544 ----------------- 1 file changed, 1544 deletions(-) delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig deleted file mode 100644 index a4093ec937..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig +++ /dev/null @@ -1,1544 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace // unnamed namespace to hold copies of Cry AuxGeom state enum's, this is to avoid creating a dependency on IRenderAuxGeom.h -{ - // Notes: - // Don't change the xxxShift values, they need to match the values from legacy cry rendering - // This also applies to the individual flags in EAuxGeomPublicRenderflags_*! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - enum EAuxGeomPublicRenderflagBitMasks - { - e_Mode2D3DShift = 31, - e_Mode2D3DMask = 0x1 << e_Mode2D3DShift, - - e_AlphaBlendingShift = 29, - e_AlphaBlendingMask = 0x3 << e_AlphaBlendingShift, - - e_DrawInFrontShift = 28, - e_DrawInFrontMask = 0x1 << e_DrawInFrontShift, - - e_FillModeShift = 26, - e_FillModeMask = 0x3 << e_FillModeShift, - - e_CullModeShift = 24, - e_CullModeMask = 0x3 << e_CullModeShift, - - e_DepthWriteShift = 23, - e_DepthWriteMask = 0x1 << e_DepthWriteShift, - - e_DepthTestShift = 22, - e_DepthTestMask = 0x1 << e_DepthTestShift, - - e_PublicParamsMask = e_Mode2D3DMask | e_AlphaBlendingMask | e_DrawInFrontMask | e_FillModeMask | - e_CullModeMask | e_DepthWriteMask | e_DepthTestMask - }; - - // Notes: - // e_Mode2D renders in normalized [0.. 1] screen space. - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_Mode2D3D - { - e_Mode3D = 0x0 << e_Mode2D3DShift, - e_Mode2D = 0x1 << e_Mode2D3DShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_AlphaBlendMode - { - e_AlphaNone = 0x0 << e_AlphaBlendingShift, - e_AlphaAdditive = 0x1 << e_AlphaBlendingShift, - e_AlphaBlended = 0x2 << e_AlphaBlendingShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DrawInFrontMode - { - e_DrawInFrontOff = 0x0 << e_DrawInFrontShift, - e_DrawInFrontOn = 0x1 << e_DrawInFrontShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_FillMode - { - e_FillModeSolid = 0x0 << e_FillModeShift, - e_FillModeWireframe = 0x1 << e_FillModeShift, - e_FillModePoint = 0x2 << e_FillModeShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_CullMode - { - e_CullModeNone = 0x0 << e_CullModeShift, - e_CullModeFront = 0x1 << e_CullModeShift, - e_CullModeBack = 0x2 << e_CullModeShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DepthWrite - { - e_DepthWriteOn = 0x0 << e_DepthWriteShift, - e_DepthWriteOff = 0x1 << e_DepthWriteShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DepthTest - { - e_DepthTestOn = 0x0 << e_DepthTestShift, - e_DepthTestOff = 0x1 << e_DepthTestShift, - }; -}; - -namespace AZ::AtomBridge -{ - - //////////////////////////////////////////////////////////////////////// - SingleColorDynamicSizeLineHelper::SingleColorDynamicSizeLineHelper( - int estimatedNumLineSegments - ) - { - m_points.reserve(estimatedNumLineSegments * 2); - } - - void SingleColorDynamicSizeLineHelper::AddLineSegment( - const AZ::Vector3& lineStart, - const AZ::Vector3& lineEnd - ) - { - m_points.push_back(lineStart); - m_points.push_back(lineEnd); - } - - void SingleColorDynamicSizeLineHelper::Draw( - AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, - const RenderState& rendState - ) const - { - if (auxGeomDrawPtr && !m_points.empty()) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = m_points.data(); - drawArgs.m_vertCount = aznumeric_cast(m_points.size()); - drawArgs.m_colors = &rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = rendState.m_lineWidth; - drawArgs.m_opacityType = rendState.m_opacityType; - drawArgs.m_depthTest = rendState.m_depthTest; - drawArgs.m_depthWrite = rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = rendState.m_viewProjOverrideIndex; - auxGeomDrawPtr->DrawLines( drawArgs ); - } - } - - void SingleColorDynamicSizeLineHelper::Draw2d( - AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, - const RenderState& rendState - ) const - { - if (auxGeomDrawPtr && !m_points.empty()) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = m_points.data(); - drawArgs.m_vertCount = aznumeric_cast(m_points.size()); - drawArgs.m_colors = &rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = rendState.m_lineWidth; - drawArgs.m_opacityType = rendState.m_opacityType; - drawArgs.m_depthTest = rendState.m_depthTest; - drawArgs.m_depthWrite = rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = auxGeomDrawPtr->GetOrAdd2DViewProjOverride(); - auxGeomDrawPtr->DrawLines( drawArgs ); - } - } - - void SingleColorDynamicSizeLineHelper::Reset() - { - m_points.clear(); - } - //////////////////////////////////////////////////////////////////////// - - // Partial implementation of the DebugDisplayRequestBus on Atom. - // Commented out function prototypes are waiting to be implemented. - // work tracked in [ATOM-3459] - AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) - { - ResetRenderState(); - m_viewportId = viewportContextPtr->GetId(); - m_defaultInstance = false; - auto setupScene = [this](RPI::ScenePtr scene) - { - auto viewportContextManager = AZ::Interface::Get(); - AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); - InitInternal(scene.get(), viewportContextPtr); - }; - setupScene(viewportContextPtr->GetRenderScene()); - m_sceneChangeHandler = AZ::RPI::ViewportContext::SceneChangedEvent::Handler(setupScene); - viewportContextPtr->ConnectSceneChangedHandler(m_sceneChangeHandler); - } - - AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(uint32_t defaultInstanceAddress) - { - ResetRenderState(); - m_viewportId = defaultInstanceAddress; - m_defaultInstance = true; - RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - InitInternal(scene, nullptr); - } - - void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) - { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); - if (!scene) - { - m_auxGeomPtr = nullptr; - return; - } - auto auxGeomFP = scene->GetFeatureProcessor(); - if (!auxGeomFP) - { - m_auxGeomPtr = nullptr; - return; - } - if (m_defaultInstance) - { - m_auxGeomPtr = auxGeomFP->GetDrawQueue(); - } - else - { - m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); - } - AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); - } - - AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() - { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); - m_viewportId = AzFramework::InvalidViewportId; - m_auxGeomPtr = nullptr; - } - - void AtomDebugDisplayViewportInterface::ResetRenderState() - { - m_rendState = RenderState(); - for (int index = 0; index < RenderState::TransformStackSize; ++index) - { - m_rendState.m_transformStack[index] = AZ::Matrix3x4::Identity(); - } - } - - void AtomDebugDisplayViewportInterface::SetColor(float r, float g, float b, float a) - { - m_rendState.m_color = AZ::Color(r, g, b, a); - } - - void AtomDebugDisplayViewportInterface::SetColor(const AZ::Color& color) - { - m_rendState.m_color = color; - } - - void AtomDebugDisplayViewportInterface::SetColor(const AZ::Vector4& color) - { - m_rendState.m_color = AZ::Color(color); - } - - void AtomDebugDisplayViewportInterface::SetAlpha(float a) - { - m_rendState.m_color.SetA(a); - if (a < 1.0f) - { - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; - } - else - { - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; - } - } - - void AtomDebugDisplayViewportInterface::DrawQuad( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::Vector3 triangles[6]; - triangles[0] = wsPoints[0]; - triangles[1] = wsPoints[1]; - triangles[2] = wsPoints[2]; - triangles[3] = wsPoints[2]; - triangles[4] = wsPoints[3]; - triangles[5] = wsPoints[0]; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = triangles; - drawArgs.m_vertCount = 6; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawQuad(float width, float height) - { - if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) - { - return; - } - - m_auxGeomPtr->DrawQuad( - width, - height, - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = wsPoints; - drawArgs.m_vertCount = 4; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad(float width, float height) - { - if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) - { - return; - } - - m_auxGeomPtr->DrawQuad( - width, - height, - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - - void AtomDebugDisplayViewportInterface::DrawQuadGradient( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4, - const AZ::Vector4& firstColor, - const AZ::Vector4& secondColor) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::Vector3 triangles[6]; - AZ::Color colors[6]; - triangles[0] = wsPoints[0]; colors[0] = firstColor; - triangles[1] = wsPoints[1]; colors[1] = firstColor; - triangles[2] = wsPoints[2]; colors[2] = secondColor; - triangles[3] = wsPoints[2]; colors[3] = secondColor; - triangles[4] = wsPoints[3]; colors[4] = secondColor; - triangles[5] = wsPoints[0]; colors[5] = firstColor; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = triangles; - drawArgs.m_vertCount = 6; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 6; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTri(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector3& p3) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[3] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 3; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTriangles(const AZStd::vector& vertices, const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTrianglesIndexed( - const AZStd::vector& vertices, - const AZStd::vector& indices, - const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicIndexedDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); - drawArgs.m_indices = indices.data(); - drawArgs.m_indexCount = aznumeric_cast(indices.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireBox(const AZ::Vector3& min, const AZ::Vector3& max) - { - if (m_auxGeomPtr) - { - m_auxGeomPtr->DrawAabb( - AZ::Aabb::CreateFromMinMax(min, max), - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidBox(const AZ::Vector3& min, const AZ::Vector3& max) - { - if (m_auxGeomPtr) - { - m_auxGeomPtr->DrawAabb( - AZ::Aabb::CreateFromMinMax(min, max), - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidOBB( - const AZ::Vector3& center, - const AZ::Vector3& axisX, - const AZ::Vector3& axisY, - const AZ::Vector3& axisZ, - const AZ::Vector3& halfExtents) - { - if (m_auxGeomPtr) - { - AZ::Quaternion rotation = AZ::Quaternion::CreateFromMatrix3x3(AZ::Matrix3x3::CreateFromColumns(axisX, axisY, axisZ)); - AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(center, rotation, halfExtents); - m_auxGeomPtr->DrawObb( - obb, - AZ::Vector3::CreateZero(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - } - - void AtomDebugDisplayViewportInterface::DrawPoint(const AZ::Vector3& p, int nSize) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoint = ToWorldSpacePosition(p); - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = &wsPoint; - drawArgs.m_vertCount = 1; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = aznumeric_cast(nSize); - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPoints(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector4& col1, const AZ::Vector4& col2) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; - AZ::Color colors[2] = {col1, col2}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 2; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLines(const AZStd::vector& lines, const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = lines.data(); - drawArgs.m_vertCount = aznumeric_cast(lines.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawPolyLine(const AZ::Vector3* pnts, int numPoints, bool cycled) - { - if (m_auxGeomPtr) - { - AZStd::vector wsPoints(static_cast(numPoints)); - for (int index = 0; index < numPoints; ++index) - { - wsPoints[index] = ToWorldSpacePosition(pnts[index]); - } - AZ::RPI::AuxGeomDraw::PolylineEnd polylineEnd = cycled ? AZ::RPI::AuxGeomDraw::PolylineEnd::Closed : AZ::RPI::AuxGeomDraw::PolylineEnd::Open; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = wsPoints.data(); - drawArgs.m_vertCount = aznumeric_cast(numPoints); - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPolylines(drawArgs, polylineEnd); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[4]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p1.GetY(), z); - points[2] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - points[3] = AZ::Vector3(p1.GetX(), p2.GetY(), z); - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 4; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[2]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine2dGradient(const AZ::Vector2& p1, const AZ::Vector2& p2, float z, const AZ::Vector4& firstColor, const AZ::Vector4& secondColor) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[2]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - AZ::Color colors[2] = {firstColor, secondColor}; - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 2; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCircle2d(const AZ::Vector2& center, float radius, float z) - { - if (m_auxGeomPtr) - { - // Draw axis aligned arc - constexpr float angularStepDegrees = 10.0f; - constexpr float startAngleDegrees = 0.0f; - constexpr float sweepAngleDegrees = 360.0f; - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - AZ::Vector3 pos = AZ::Vector3(center.GetX(), center.GetY(), z); - CreateAxisAlignedArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - CircleAxis::CircleAxisZ - ); - lines.Draw2d(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawArc( - const AZ::Vector3& pos, - float radius, - float startAngleDegrees, - float sweepAngleDegrees, - float angularStepDegrees, - int referenceAxis) - { - if (m_auxGeomPtr) - { - // Draw axis aligned arc - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateAxisAlignedArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - static_cast(referenceAxis) - ); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawArc( - const AZ::Vector3& pos, - float radius, - float startAngleDegrees, - float sweepAngleDegrees, - float angularStepDegrees, - const AZ::Vector3& fixedAxis) - { - if (m_auxGeomPtr) - { - // Draw arbitraty axis arc - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateArbitraryAxisArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - fixedAxis - ); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawCircle(const AZ::Vector3& pos, float radius, int nUnchangedAxis) - { - if (m_auxGeomPtr) - { - // Draw circle with default radius. - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateAxisAlignedArc( - lines, - step, - 0.0f, - maxAngle, - pos, - radiusV3, - static_cast(nUnchangedAxis)); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawHalfDottedCircle(const AZ::Vector3& pos, float radius, const AZ::Vector3& viewPos, int nUnchangedAxis) - { - if (m_auxGeomPtr) - { - // Draw circle with single radius. - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. - - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldView = ToWorldSpacePosition(viewPos); - const AZ::Vector3 worldDir = worldView - worldPos; - - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, radiusV3, static_cast(nUnchangedAxis%CircleAxisMax), - [&worldPos, &worldDir](const AZ::Vector3& lineStart, const AZ::Vector3& lineEnd, int segmentIndex) - { - AZ_UNUSED(lineEnd); - const float dot = (lineStart - worldPos).Dot(worldDir); - const bool facing = dot > 0.0f; - // if so skip every other line to produce a dotted effect - if (facing || segmentIndex % 2 == 0) - { - return true; - } - return false; - }); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); - m_auxGeomPtr->DrawCone( - worldPos, - worldDir, - radius, - height, - m_rendState.m_color, - drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); - const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); - m_auxGeomPtr->DrawCylinder( - worldCenter, - worldAxis, - radius, - height, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidCylinder( - const AZ::Vector3& center, - const AZ::Vector3& axis, - float radius, - float height, - bool drawShaded) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); - const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); - m_auxGeomPtr->DrawCylinder( - worldCenter, - worldAxis, - radius, - height, - m_rendState.m_color, - drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCapsule( - const AZ::Vector3& center, - const AZ::Vector3& axis, - float radius, - float heightStraightSection) - { - if (m_auxGeomPtr && radius > FLT_EPSILON && axis.GetLengthSq() > FLT_EPSILON) - { - AZ::Vector3 axisNormalized = axis.GetNormalizedEstimate(); - SingleColorStaticSizeLineHelper<(16+1) * 5> lines; // 360/22.5 = 16, 5 possible calls to CreateArbitraryAxisArc - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - float stepAngle = DegToRad(22.5f); - float Deg0 = DegToRad(0.0f); - - - // Draw cylinder part (or just a circle around the middle) - if (heightStraightSection > FLT_EPSILON) - { - DrawWireCylinder(center, axis, radius, heightStraightSection); - } - else - { - float Deg360 = DegToRad(360.0f); - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg360, - center, - radiusV3, - axisNormalized - ); - } - - float Deg90 = DegToRad(90.0f); - float Deg180 = DegToRad(180.0f); - - AZ::Vector3 ortho1Normalized, ortho2Normalized; - CalcBasisVectors(axisNormalized, ortho1Normalized, ortho2Normalized); - AZ::Vector3 centerToTopCircleCenter = axisNormalized * heightStraightSection * 0.5f; - AZ::Vector3 topCenter = center + centerToTopCircleCenter; - AZ::Vector3 bottomCenter = center - centerToTopCircleCenter; - - // Draw top cap as two criss-crossing 180deg arcs - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg90, - Deg90 + Deg180, - topCenter, - radiusV3, - ortho1Normalized - ); - - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg180, - Deg180 + Deg180, - topCenter, - radiusV3, - ortho2Normalized - ); - - // Draw bottom cap - CreateArbitraryAxisArc( - lines, - stepAngle, - -Deg90, - -Deg90 + Deg180, - bottomCenter, - radiusV3, - ortho1Normalized - ); - - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg0 + Deg180, - bottomCenter, - radiusV3, - ortho2Normalized - ); - - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, float radius) - { - if (m_auxGeomPtr) - { - - m_auxGeomPtr->DrawSphere( - ToWorldSpacePosition(pos), - radius, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) - { - if (m_auxGeomPtr) - { - // This matches Cry behavior, the DrawWireSphere above may need modifying to use the same approach. - // Draw 3 axis aligned circles - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40*3> lines; // hard code to 40 lines * 3 circles until DegToRad is constexpr. - - // Z Axis - AZ::Vector3 axisRadius(radius.GetX(), radius.GetY(), 0.0f); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisZ); - - // X Axis - axisRadius = AZ::Vector3(0.0f, radius.GetY(), radius.GetZ()); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisX); - - // Y Axis - axisRadius = AZ::Vector3(radius.GetX(), 0.0f, radius.GetZ()); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisY); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) - { - if (m_auxGeomPtr) - { - - // Draw 3 axis aligned circles - const float stepAngle = DegToRad(11.25f); - const float startAngle = DegToRad(0.0f); - const float stopAngle = DegToRad(360.0f) + startAngle; - SingleColorDynamicSizeLineHelper lines(2+static_cast(360.0f/11.25f)); // num disk segments + 1 for azis line + 1 for spare - const AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateArbitraryAxisArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - dir - ); - - lines.AddLineSegment(ToWorldSpacePosition(pos), ToWorldSpacePosition(pos + dir * (radius * 0.2f))); // 0.2f comes from Code\Sandbox\Editor\Objects\DisplayContextShared.inl DisplayContext::DrawWireDisk - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded) - { - if (m_auxGeomPtr) - { - // get the max scaled radius in case the transform on the stack is scaled non-uniformly - const float transformedRadiusX = ToWorldSpaceVector(AZ::Vector3(radius, 0.0f, 0.0f)).GetLengthEstimate(); - const float transformedRadiusY = ToWorldSpaceVector(AZ::Vector3(0.0f, radius, 0.0f)).GetLengthEstimate(); - const float transformedRadiusZ = ToWorldSpaceVector(AZ::Vector3(0.0f, 0.0f, radius)).GetLengthEstimate(); - const float maxTransformedRadius = - AZ::GetMax(transformedRadiusX, AZ::GetMax(transformedRadiusY, transformedRadiusZ)); - - AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid; - m_auxGeomPtr->DrawSphere( - ToWorldSpacePosition(pos), - maxTransformedRadius, - m_rendState.m_color, - drawStyle, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); - m_auxGeomPtr->DrawDisk( - worldPos, - worldDir, - radius, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawArrow(const AZ::Vector3& src, const AZ::Vector3& trg, float headScale, bool dualEndedArrow) - { - if (m_auxGeomPtr) - { - float f2dScale = 1.0f; - float arrowLen = 0.4f * headScale; - float arrowRadius = 0.1f * headScale; - // if (flags & DISPLAY_2D) - // { - // f2dScale = 1.2f * ToWorldSpaceVector(Vec3(1, 0, 0)).GetLength(); - // } - AZ::Vector3 dir = trg - src; - dir = ToWorldSpaceVector(dir.GetNormalized()); - AZ::Vector3 verts[2] = {ToWorldSpacePosition(src), ToWorldSpacePosition(trg)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - if (!dualEndedArrow) - { - verts[1] -= dir * arrowLen; - m_auxGeomPtr->DrawLines(drawArgs); - m_auxGeomPtr->DrawCone( - verts[1], - dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - else - { - verts[0] += dir * arrowLen; - verts[1] -= dir * arrowLen; - m_auxGeomPtr->DrawLines(drawArgs); - m_auxGeomPtr->DrawCone( - verts[0], - -dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - m_auxGeomPtr->DrawCone( - verts[1], - dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - } - - void AtomDebugDisplayViewportInterface::DrawTextLabel( - const AZ::Vector3& pos, - float size, - const char* text, - const bool center, - int srcOffsetX [[maybe_unused]], - int srcOffsetY [[maybe_unused]]) - { - // abort draw if draw is invalid or font query interface is missing. - if (!text || size == 0.0f || !AZ::Interface::Get()) - { - return; - } - - AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - // abort draw if font draw interface is missing - if (!fontDrawInterface) - { - return; - } - // if 2d draw need to project pos to screen first - AzFramework::TextDrawParameters params; - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = pos; - 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 - params.m_monospace = false; //! disable character proportional spacing - params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution - params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger - params.m_multiline = true; //! text respects ascii newline characters - - fontDrawInterface->DrawScreenAlignedText3d(params, text); - } - - void AtomDebugDisplayViewportInterface::Draw2dTextLabel( - float x, - float y, - float size, - const char* text, - bool center) - { -<<<<<<< HEAD - // abort draw if draw is invalid or font query interface is missing. - if (!text || size == 0.0f || !AZ::Interface::Get()) - { - return; - } - - AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - // abort draw if font draw interface is missing - if (!fontDrawInterface) -======= - auto fontQueryInterface = AZ::Interface::Get(); - if (!fontQueryInterface) - { - return; - } - AzFramework::FontDrawInterface* fontDrawInterface = fontQueryInterface->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) ->>>>>>> upstream/main - { - return; - } - // if 2d draw need to project pos to screen first - AzFramework::TextDrawParameters params; - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = AZ::Vector3(x, y, 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 - params.m_monospace = false; //! disable character proportional spacing - params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution - params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger - params.m_multiline = true; //! text respects ascii newline characters - - fontDrawInterface->DrawScreenAlignedText2d(params, text); - } - - void AtomDebugDisplayViewportInterface::DrawTextOn2DBox( - const AZ::Vector3& pos [[maybe_unused]], - const char* text [[maybe_unused]], - float textScale [[maybe_unused]], - const AZ::Vector4& TextColor [[maybe_unused]], - const AZ::Vector4& TextBackColor [[maybe_unused]]) - { - AZ_Assert(false, "Unexpected use of legacy api, please file a feature request with the rendering team to get this implemented!"); - } - // unhandledled on Atom - virtual void DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; - // void AtomDebugDisplayViewportInterface::DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; - - void AtomDebugDisplayViewportInterface::SetLineWidth(float width) - { - AZ_Assert(width >= 0.0f && width <= 255.0f, "Width (%f) exceeds allowable range [0 - 255]", width); - m_rendState.m_lineWidth = static_cast(width); - } - - bool AtomDebugDisplayViewportInterface::IsVisible(const AZ::Aabb& bounds) - { - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - const AZ::Matrix4x4& worldToClip = viewportContext->GetDefaultView()->GetWorldToClipMatrix(); - AZ::Frustum frustum = AZ::Frustum::CreateFromMatrixColumnMajor(worldToClip, Frustum::ReverseDepth::True); - return frustum.IntersectAabb(bounds) != AZ::IntersectResult::Exterior; - } - // int AtomDebugDisplayViewportInterface::SetFillMode(int nFillMode) override; - float AtomDebugDisplayViewportInterface::GetLineWidth() - { - return m_rendState.m_lineWidth; - } - - float AtomDebugDisplayViewportInterface::GetAspectRatio() - { - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - auto windowSize = viewportContext->GetViewportSize(); - return aznumeric_cast(windowSize.m_width)/aznumeric_cast(windowSize.m_height); - } - - void AtomDebugDisplayViewportInterface::DepthTestOff() - { - m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::Off; - } - - void AtomDebugDisplayViewportInterface::DepthTestOn() - { - m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::On; - } - - void AtomDebugDisplayViewportInterface::DepthWriteOff() - { - m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::Off; - } - - void AtomDebugDisplayViewportInterface::DepthWriteOn() - { - m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::On; - } - - void AtomDebugDisplayViewportInterface::CullOff() - { - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::None; - } - - void AtomDebugDisplayViewportInterface::CullOn() - { - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Back; - } - - bool AtomDebugDisplayViewportInterface::SetDrawInFrontMode(bool on) - { - AZ_UNUSED(on); - return false; - } - - AZ::u32 AtomDebugDisplayViewportInterface::GetState() - { - return ConvertRenderStateToCry(); - } - - AZ::u32 AtomDebugDisplayViewportInterface::SetState(AZ::u32 state) - { - uint32_t currentState = ConvertRenderStateToCry(); - uint32_t changedState = (state & e_PublicParamsMask) ^ currentState; - - if (changedState & e_Mode2D3DMask) - { - // this is the only way to turn on 2d Mode under Atom - if (state & e_Mode2D) - { - AZ_Assert((currentState & e_DrawInFrontOn) == 0 && (changedState & e_DrawInFrontOn) == 0, "Atom doesnt support Draw In Front and 2d at the same time"); - m_rendState.m_viewProjOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_rendState.m_2dMode = true; - } - else // switch back to mode 3d - { - m_rendState.m_viewProjOverrideIndex = -1; - m_rendState.m_2dMode = false; - } - } - - if (changedState & e_AlphaBlendingMask) - { - switch (state&e_AlphaBlendingMask) - { - case e_AlphaNone: - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; - break; - case e_AlphaAdditive: - [[fallthrough]]; // Additive not currently supported in Atom AuxGeom implementation - case e_AlphaBlended: - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; - break; - } - } - - if (changedState & e_DrawInFrontMask) - { - AZ_Assert( // either state is turning DrawInFront off or Mode 2D has to be off - (state & e_DrawInFrontOn) == 0 || - ((currentState & e_Mode2D) == 0 && (changedState & e_Mode2D) == 0), - "Atom doesnt support Draw In Front and 2d at the same time"); - SetDrawInFrontMode(changedState & e_DrawInFrontOn); - } - - if (changedState & e_CullModeMask) - { - switch (state & e_CullModeMask) - { - case e_CullModeNone: - CullOff(); - break; - case e_CullModeFront: - // Currently no other way to set front face culling in DebugDisplayRequestBus - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Front; - break; - case e_CullModeBack: - CullOn(); - break; - } - } - - if (changedState & e_DepthWriteMask) - { - if (state & e_DepthWriteOff) - { - DepthWriteOff(); - } - else - { - DepthWriteOn(); - } - } - - if (changedState & e_DepthTestMask) - { - if (state & e_DepthTestOff) - { - DepthTestOff(); - } - else - { - DepthTestOn(); - } - } - - return currentState; - } - - void AtomDebugDisplayViewportInterface::PushMatrix(const AZ::Transform& tm) - { - AZ_Assert(m_rendState.m_currentTransform < RenderState::TransformStackSize, "Exceeded AtomDebugDisplayViewportInterface matrix stack size"); - if (m_rendState.m_currentTransform < RenderState::TransformStackSize) - { - m_rendState.m_currentTransform++; - m_rendState.m_transformStack[m_rendState.m_currentTransform] = m_rendState.m_transformStack[m_rendState.m_currentTransform - 1] * AZ::Matrix3x4::CreateFromTransform(tm); - } - } - - void AtomDebugDisplayViewportInterface::PopMatrix() - { - AZ_Assert(m_rendState.m_currentTransform > 0, "Underflowed AtomDebugDisplayViewportInterface matrix stack"); - if (m_rendState.m_currentTransform > 0) - { - m_rendState.m_currentTransform--; - } - } - - const AZ::Matrix3x4& AtomDebugDisplayViewportInterface::GetCurrentTransform() const - { - return m_rendState.m_transformStack[m_rendState.m_currentTransform]; - } - - AZ::RPI::ViewportContextPtr AtomDebugDisplayViewportInterface::GetViewportContext() const - { - auto viewContextManager = AZ::Interface::Get(); - if (m_defaultInstance) - { - return viewContextManager->GetViewportContextByName(viewContextManager->GetDefaultViewportContextName()); - } - else - { - return viewContextManager->GetViewportContextById(m_viewportId); - } - } - - uint32_t AtomDebugDisplayViewportInterface::ConvertRenderStateToCry() const - { - uint32_t result = 0; - - result |= m_rendState.m_2dMode ? e_Mode2D : e_Mode3D; - result |= m_rendState.m_opacityType == AZ::RPI::AuxGeomDraw::OpacityType::Opaque ? e_AlphaNone : e_AlphaBlended; - result |= m_rendState.m_drawInFront ? e_DrawInFrontOn : e_DrawInFrontOff; - result |= m_rendState.m_depthTest == AZ::RPI::AuxGeomDraw::DepthTest::On ? e_DepthTestOn : e_DepthTestOff; - result |= m_rendState.m_depthWrite == AZ::RPI::AuxGeomDraw::DepthWrite::On ? e_DepthWriteOn : e_DepthWriteOff; - switch (m_rendState.m_faceCullMode) - { - case AZ::RPI::AuxGeomDraw::FaceCullMode::None: - result |= e_CullModeNone; - break; - case AZ::RPI::AuxGeomDraw::FaceCullMode::Front: - result |= e_CullModeFront; - break; - case AZ::RPI::AuxGeomDraw::FaceCullMode::Back: - result |= e_CullModeBack; - break; - default: - AZ_Assert(false, "Trying to convert an unknown culling mode to cry!"); - break; - } - - return result; - } -} From 64d980bc0361748bb6f09a2b58819584b4604a38 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 15:40:32 -0500 Subject: [PATCH 018/112] Deleted AzFramework::AtomActiveInterface --- Code/CryEngine/CrySystem/System.cpp | 26 ------- Code/CryEngine/CrySystem/SystemInit.cpp | 16 ----- .../AzFramework/API/AtomActiveInterface.h | 26 ------- .../AzFramework/azframework_files.cmake | 1 - .../Utilities/HandleDpiAwareness_Windows.cpp | 1 - .../Editor/Core/LevelEditorMenuHandler.cpp | 1 - Code/Sandbox/Editor/CryEditDoc.cpp | 38 +---------- Code/Sandbox/Editor/EditorViewportWidget.cpp | 1 - Code/Sandbox/Editor/IconManager.cpp | 67 ++----------------- Code/Sandbox/Editor/LayoutWnd.cpp | 1 - Code/Sandbox/Editor/MainWindow.cpp | 14 +--- Code/Sandbox/Editor/RenderViewport.cpp | 27 ++------ Code/Sandbox/Editor/ToolbarManager.cpp | 1 - Code/Sandbox/Editor/ViewManager.cpp | 5 +- Code/Sandbox/Editor/ViewPane.cpp | 1 - .../SandboxIntegration.cpp | 3 +- .../Plugins/EditorCommon/QViewport.cpp | 13 ++-- .../Code/Source/AtomBridgeSystemComponent.cpp | 2 - .../Code/Source/AtomBridgeSystemComponent.h | 2 - .../Code/Source/BuilderComponent.cpp | 2 - .../AtomBridge/Code/Source/BuilderComponent.h | 2 - .../Pipeline/RCExt/Actor/ActorBuilder.cpp | 1 - .../Integration/Components/ActorComponent.h | 7 +- .../Components/EditorActorComponent.cpp | 2 +- .../Editor/EditorImageBuilderComponent.cpp | 10 +-- .../ImGuiEditorWindowSystemComponent.cpp | 15 ----- Gems/ImGui/Code/Source/ImGuiManager.cpp | 16 +---- .../Code/Source/WhiteBoxSystemComponent.cpp | 8 +-- 28 files changed, 26 insertions(+), 283 deletions(-) delete mode 100644 Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index a48f63afdf..827a393103 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include @@ -1162,31 +1161,6 @@ void CSystem::SleepIfInactive() { return; } - -#if defined(WIN32) - if (!AZ::Interface::Get()) - { - WIN_HWND hRendWnd = GetIRenderer()->GetHWND(); - if (!hRendWnd) - { - return; - } - - AZ_TRACE_METHOD(); - // Loop here waiting for window to be activated. - for (int nLoops = 0; nLoops < 5; nLoops++) - { - WIN_HWND hActiveWnd = ::GetActiveWindow(); - if (hActiveWnd == hRendWnd) - { - break; - } - - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); - Sleep(5); - } - } -#endif } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index d293f9ca80..826810ef8a 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -68,7 +68,6 @@ #include #include #include -#include #include #include @@ -2462,21 +2461,6 @@ AZ_POP_DISABLE_WARNING m_env.pRenderer->SetViewport(0, 0, screenWidth, screenHeight); - // Skip splash screen rendering - if (!AZ::Interface::Get()) - { - // make sure it's rendered in full screen mode when triple buffering is enabled as well - for (size_t n = 0; n < 3; n++) - { - m_env.pRenderer->BeginFrame(); - m_env.pRenderer->SetCullMode(R_CULL_NONE); - m_env.pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - m_env.pRenderer->Draw2dImageStretchMode(true); - m_env.pRenderer->Draw2dImage(x * vx, y * vy, w * vx, h * vy, pTex->GetTextureID(), 0.0f, 1.0f, 1.0f, 0.0f); - m_env.pRenderer->Draw2dImageStretchMode(false); - m_env.pRenderer->EndFrame(); - } - } #if defined(AZ_PLATFORM_IOS) || defined(AZ_PLATFORM_MAC) // Pump system events in order to update the screen AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); diff --git a/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h b/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h deleted file mode 100644 index 80d4f6c867..0000000000 --- a/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#pragma once - -#include - -namespace AzFramework -{ - class AtomActiveInterface - { - public: - AZ_RTTI(AtomActiveInterface, "{4BB59C86-0848-485D-AB28-700540470B2B}"); - - AtomActiveInterface() = default; - virtual ~AtomActiveInterface() = default; - }; -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index b126a192ac..88f68d8bab 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -14,7 +14,6 @@ set(FILES AzFrameworkModule.h AzFrameworkModule.cpp API/ApplicationAPI.h - API/AtomActiveInterface.h Application/Application.cpp Application/Application.h Archive/Archive.cpp diff --git a/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp b/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp index 9ffe06f7e3..b834995bd9 100644 --- a/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp +++ b/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp @@ -16,7 +16,6 @@ #include #include -#include #include namespace AzQtComponents diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 3f396894ff..869fa2fe25 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -23,7 +23,6 @@ #include "Objects/SelectionGroup.h" #include "ViewManager.h" -#include #include // Qt diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 41c49ab026..2bc4dcf10c 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -27,7 +27,6 @@ // AzFramework #include #include -#include // AzToolsFramework #include @@ -2417,42 +2416,7 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU void CCryEditDoc::CreateDefaultLevelAssets(int resolution, int unitSize) { - if (AZ::Interface::Get()) - { - AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); - } - else - { - bool isPrefabSystemEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); - - if (!isPrefabSystemEnabled) - { - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - m_envProbeSliceAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, m_envProbeSliceRelativePath, - azrtti_typeid(), false); - - if (m_envProbeSliceAssetId.IsValid()) - { - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().FindOrCreateAsset( - m_envProbeSliceAssetId, AZ::Data::AssetLoadBehavior::Default); - if (asset) - { - m_terrainSize = resolution * unitSize; - const float halfTerrainSize = m_terrainSize / 2.0f; - - AZ::Transform worldTransform = AZ::Transform::CreateIdentity(); - worldTransform = AZ::Transform::CreateTranslation(AZ::Vector3(halfTerrainSize, halfTerrainSize, m_envProbeHeight / 2)); - - AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); - GetIEditor()->SuspendUndo(); - AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Broadcast( - &AzToolsFramework::SliceEditorEntityOwnershipServiceRequests::InstantiateEditorSlice, asset, worldTransform); - } - } - } - } + AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); } void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 9165809c7f..1a8d3a863d 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -40,7 +40,6 @@ # include #endif // defined(AZ_PLATFORM_WINDOWS) #include // for AzFramework::InputDeviceMouse -#include #include // AzQtComponents diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 09c2d41035..3916ee7726 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -15,7 +15,6 @@ #include "IconManager.h" -#include #include // AzToolsFramework @@ -115,69 +114,11 @@ int CIconManager::GetIconTexture(const char* iconName) return 0; } - if (AZ::Interface::Get()) + ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; + if (texture) { - ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; - if (texture) - { - id = texture->GetTextureID(); - m_textures[iconName] = id; - } - } - else - { - QString ext = Path::GetExt(iconName); - QString actualName = iconName; - - char iconPath[AZ_MAX_PATH_LEN] = { 0 }; - gEnv->pFileIO->ResolvePath(actualName.toUtf8().data(), iconPath, AZ_MAX_PATH_LEN); - - // if we can't find it at the resolved path, try the devroot if necessary: - if (!gEnv->pFileIO->Exists(iconPath)) - { - if (iconName[0] != '@') // it has no specified alias - { - if (QString::compare(ext, "dds", Qt::CaseInsensitive) != 0) // if its a DDS, it comes out of processed files in @assets@, and assets is assumed by default (legacy renderer) - { - // check for a source file - AZStd::string iconFullPath; - bool pathFound = false; - using AssetSysReqBus = AzToolsFramework::AssetSystemRequestBus; - AssetSysReqBus::BroadcastResult(pathFound, &AssetSysReqBus::Events::GetFullSourcePathFromRelativeProductPath, iconName, iconFullPath); - - if (pathFound) - { - azstrncpy(iconPath, AZ_MAX_PATH_LEN, iconFullPath.c_str(), iconFullPath.length() + 1); - } - } - } - } - - CImageEx image; - // Load icon. - if (CImageUtil::LoadImage(iconPath, image)) - { - IRenderer* pRenderer(GetIEditor()->GetRenderer()); - if (pRenderer->GetRenderType() != eRT_DX11) - { - image.SwapRedAndBlue(); - } - - if (QString::compare(ext, "bmp", Qt::CaseInsensitive) == 0 || QString::compare(ext, "jpg", Qt::CaseInsensitive) == 0) - { - int sz = image.GetWidth() * image.GetHeight(); - uint8* buf = (uint8*)image.GetData(); - for (int i = 0; i < sz; i++) - { - uint32 alpha = max(max(buf[i * 4], buf[i * 4 + 1]), buf[i * 4 + 2]); - alpha *= 2; - buf[i * 4 + 3] = (alpha > 255) ? 255 : alpha; - } - } - - id = pRenderer->DownLoadToVideoMemory((unsigned char*)image.GetData(), image.GetWidth(), image.GetHeight(), eTF_R8G8B8A8, eTF_R8G8B8A8, 0, 0, 0); - m_textures[iconName] = id; - } + id = texture->GetTextureID(); + m_textures[iconName] = id; } return id; diff --git a/Code/Sandbox/Editor/LayoutWnd.cpp b/Code/Sandbox/Editor/LayoutWnd.cpp index 34a96bca53..54389f30c1 100644 --- a/Code/Sandbox/Editor/LayoutWnd.cpp +++ b/Code/Sandbox/Editor/LayoutWnd.cpp @@ -24,7 +24,6 @@ #include #include -#include #include // for AzQtComponents::Style // Editor diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 96f4da7312..eadc137900 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -42,7 +42,6 @@ AZ_POP_DISABLE_WARNING #include #include #include -#include // AzToolsFramework #include @@ -1095,7 +1094,7 @@ void MainWindow::InitActions() QAction* saveLevelStatsAction = am->AddAction(ID_TOOLS_LOGMEMORYUSAGE, tr("Save Level Statistics")) .SetStatusTip(tr("Logs Editor memory usage.")); - if( saveLevelStatsAction && AZ::Interface::Get()) + if( saveLevelStatsAction ) { saveLevelStatsAction->setEnabled(false); } @@ -1191,13 +1190,6 @@ void MainWindow::InitActions() .SetIcon(Style::icon("Audio")) .SetApplyHoverEffect(); - if (!AZ::Interface::Get()) - { - am->AddAction(ID_TERRAIN_TIMEOFDAYBUTTON, tr("Time of Day Editor")) - .SetToolTip(tr("Open Time of Day")) - .SetApplyHoverEffect(); - } - am->AddAction(ID_OPEN_UICANVASEDITOR, tr(LyViewPane::UiEditor)) .SetToolTip(tr("Open UI Editor")) .SetApplyHoverEffect(); @@ -1654,10 +1646,6 @@ void MainWindow::RegisterStdViewClasses() AzAssetBrowserWindow::RegisterViewClass(); AssetEditorWindow::RegisterViewClass(); - if (!AZ::Interface::Get()) - { - CTimeOfDayDialog::RegisterViewClass(); - } #ifdef ThumbnailDemo ThumbnailsSampleWidget::RegisterViewClass(); #endif diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..3e726f2468 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -42,7 +42,6 @@ # include #endif // defined(AZ_PLATFORM_WINDOWS) #include // for AzFramework::InputDeviceMouse -#include // AzQtComponents #include @@ -275,13 +274,10 @@ void CRenderViewport::resizeEvent(QResizeEvent* event) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - if (AZ::Interface::Get()) - { - // We queue the window resize event because the render overlay may be hidden. - // If the render overlay is not visible, the native window that is backing it will - // also be hidden, and it will not resize until it becomes visible. - m_windowResizedEvent = true; - } + // We queue the window resize event because the render overlay may be hidden. + // If the render overlay is not visible, the native window that is backing it will + // also be hidden, and it will not resize until it becomes visible. + m_windowResizedEvent = true; } ////////////////////////////////////////////////////////////////////////// @@ -1553,14 +1549,6 @@ void CRenderViewport::OnRender() if (levelIsDisplayable) { m_renderer->SetViewport(0, 0, m_renderer->GetWidth(), m_renderer->GetHeight(), m_nCurViewportID); - - if (!AZ::Interface::Get()) - { - m_engine->Tick(); - m_engine->Update(); - - m_engine->RenderWorld(SHDF_ALLOW_AO | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOW_WATER | SHDF_ALLOWHDR | SHDF_ZPASS, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera), __FUNCTION__); - } } else { @@ -3659,11 +3647,8 @@ bool CRenderViewport::CreateRenderContext() { m_bRenderContextCreated = true; - if (AZ::Interface::Get()) - { - AzFramework::WindowRequestBus::Handler::BusConnect(renderOverlayHWND()); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, renderOverlayHWND()); - } + AzFramework::WindowRequestBus::Handler::BusConnect(renderOverlayHWND()); + AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, renderOverlayHWND()); WIN_HWND oldContext = m_renderer->GetCurrentContextHWND(); m_renderer->CreateContext(renderOverlayHWND()); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 01bd7be82b..bbb3ef6790 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -16,7 +16,6 @@ // AzCore #include -#include #include // Qt diff --git a/Code/Sandbox/Editor/ViewManager.cpp b/Code/Sandbox/Editor/ViewManager.cpp index 7dd0f3e033..334e78a826 100644 --- a/Code/Sandbox/Editor/ViewManager.cpp +++ b/Code/Sandbox/Editor/ViewManager.cpp @@ -34,7 +34,6 @@ #include "EditorViewportWidget.h" #include "CryEditDoc.h" -#include #include AZ_CVAR(bool, ed_useAtomNativeViewport, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new Atom-native Editor viewport (experimental, not yet stable"); @@ -42,7 +41,7 @@ AZ_CVAR(bool, ed_useAtomNativeViewport, true, nullptr, AZ::ConsoleFunctorFlags:: bool CViewManager::IsMultiViewportEnabled() { // Enable multi-viewport for legacy renderer, or if we're using the new fully Atom-native viewport - return !AZ::Interface::Get() || ed_useAtomNativeViewport; + return ed_useAtomNativeViewport; } ////////////////////////////////////////////////////////////////////// @@ -81,7 +80,7 @@ CViewManager::CViewManager() RegisterQtViewPane(GetIEditor(), "Left", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportCamera; - if (ed_useAtomNativeViewport && AZ::Interface::Get()) + if (ed_useAtomNativeViewport) { RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); } diff --git a/Code/Sandbox/Editor/ViewPane.cpp b/Code/Sandbox/Editor/ViewPane.cpp index 43e4330113..480e39bedf 100644 --- a/Code/Sandbox/Editor/ViewPane.cpp +++ b/Code/Sandbox/Editor/ViewPane.cpp @@ -33,7 +33,6 @@ // AzFramework #include -#include #include // Editor diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..b0dce80ec8 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -163,7 +162,7 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); // turn on the this debug display request bus implementation if no other implementation is active - if( !(AZ::Interface::Get() && AzFramework::DebugDisplayRequestBus::HasHandlers())) + if( !(AzFramework::DebugDisplayRequestBus::HasHandlers())) { m_debugDisplayBusImplementationActive = true; AzFramework::DebugDisplayRequestBus::Handler::BusConnect( diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp index 5ca6cf5ac6..362452a67e 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp @@ -37,8 +37,6 @@ #include #include -#include - #include // Class to implement the WindowRequestBus::Handler instead of the QViewport class. @@ -365,7 +363,7 @@ bool QViewport::CreateRenderContext() HWND windowHandle = reinterpret_cast(QWidget::winId()); - if( AZ::Interface::Get() && m_renderContextCreated && windowHandle == m_lastHwnd) + if( m_renderContextCreated && windowHandle == m_lastHwnd) { // the hwnd has not changed, no need to destroy and recreate context (and swap chain etc) return false; @@ -377,13 +375,10 @@ bool QViewport::CreateRenderContext() { m_renderContextCreated = true; - if (AZ::Interface::Get()) - { - m_viewportRequests.get()->BusConnect(windowHandle); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, windowHandle); + m_viewportRequests.get()->BusConnect(windowHandle); + AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, windowHandle); - m_lastHwnd = windowHandle; - } + m_lastHwnd = windowHandle; StorePreviousContext(); GetIEditor()->GetEnv()->pRenderer->CreateContext(windowHandle); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp index f04e156afd..90731488f4 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp @@ -62,12 +62,10 @@ namespace AZ AtomBridgeSystemComponent::AtomBridgeSystemComponent() { - AZ::Interface::Register(this); } AtomBridgeSystemComponent::~AtomBridgeSystemComponent() { - AZ::Interface::Unregister(this); } void AtomBridgeSystemComponent::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h index 2ffd966216..da75d3c35c 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h @@ -17,7 +17,6 @@ #include -#include #include #include @@ -37,7 +36,6 @@ namespace AZ class AtomBridgeSystemComponent : public Component - , public AzFramework::AtomActiveInterface , public AzFramework::Render::RenderSystemRequestBus::Handler , public AzFramework::Components::DeprecatedComponentsRequestBus::Handler , public Render::Bootstrap::NotificationBus::Handler diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp index b6ff2cb66d..997b7c3b0c 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp @@ -36,12 +36,10 @@ namespace AZ BuilderComponent::BuilderComponent() { - AZ::Interface::Register(this); } BuilderComponent::~BuilderComponent() { - AZ::Interface::Unregister(this); } void BuilderComponent::Activate() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h index 4e75fd2a88..d6c462cc43 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h @@ -13,7 +13,6 @@ #pragma once #include -#include namespace AZ { @@ -21,7 +20,6 @@ namespace AZ { class BuilderComponent final : public AZ::Component - , public AzFramework::AtomActiveInterface { public: AZ_COMPONENT(BuilderComponent, "{D1FE015B-8431-4155-8FD0-8197F246901A}"); diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp index d57105a589..1327045806 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp @@ -43,7 +43,6 @@ #include #include #include -#include #include diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 1a185edccc..416705bff4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -130,11 +129,7 @@ namespace EMotionFX provided.push_back(AZ_CRC("EMotionFXActorService", 0xd6e8f48d)); provided.push_back(AZ_CRC("MeshService", 0x71d8a455)); provided.push_back(AZ_CRC("CharacterPhysicsDataService", 0x34757927)); - - if (AZ::Interface::Get()) - { - provided.push_back(AZ_CRC("MaterialReceiverService", 0x0d1a6a74)); - } + provided.push_back(AZ_CRC("MaterialReceiverService", 0x0d1a6a74)); } static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index bcb1e3f300..42deabda49 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -822,7 +822,7 @@ namespace EMotionFX bool EditorActorComponent::IsAtomDisabled() const { - return !AZ::Interface::Get(); + return false; } void EditorActorComponent::OnActorReady(Actor* actor) diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index bd1fbfb464..d7fcd3e56e 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -334,14 +333,7 @@ namespace GradientSignal AZStd::unique_ptr EditorImageBuilderWorker::LoadImageFromPath(const AZStd::string& fullPath) { - if (AZ::Interface::Get()) - { - return AtomLoadImageFromPath(fullPath); - } - else - { - return LegacyLoadImageFromPath(fullPath); - } + return AtomLoadImageFromPath(fullPath); } AZStd::unique_ptr EditorImageBuilderWorker::LoadImageSettingsFromPath(const AZStd::string& fullPath) diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp index 6c370e091c..07ab3b0a42 100644 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp +++ b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp @@ -18,7 +18,6 @@ #include "ImGuiEditorWindowSystemComponent.h" #include "ImGuiMainWindow.h" #include -#include static const char* s_ImGuiQtViewPaneName = "ImGui Editor"; @@ -60,19 +59,5 @@ namespace ImGui void ImGuiEditorWindowSystemComponent::NotifyRegisterViews() { - if (!AZ::Interface::Get()) - { - // The Tools->ImGui menu currently crashes trying to enable a render pipeline when this is invoked - // Disable this menu item for now - // [GFX TODO][ATOM-4607] - QtViewOptions options; - options.canHaveMultipleInstances = false; - AzToolsFramework::EditorRequests::Bus::Broadcast( - &AzToolsFramework::EditorRequests::RegisterViewPane, - s_ImGuiQtViewPaneName, - "Tools", - options, - [](QWidget* parent = nullptr) { return new ImGui::ImGuiMainWindow(parent); }); - } } } diff --git a/Gems/ImGui/Code/Source/ImGuiManager.cpp b/Gems/ImGui/Code/Source/ImGuiManager.cpp index e10a59bde1..c9b32ac692 100644 --- a/Gems/ImGui/Code/Source/ImGuiManager.cpp +++ b/Gems/ImGui/Code/Source/ImGuiManager.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -380,14 +379,8 @@ void ImGuiManager::Render() TransformationMatrices backupSceneMatrices; - AZ::u32 backBufferWidth = 0; - AZ::u32 backBufferHeight = 0; - - if (AZ::Interface::Get()) - { - backBufferWidth = m_windowSize.m_width; - backBufferHeight = m_windowSize.m_height; - } + AZ::u32 backBufferWidth = m_windowSize.m_width; + AZ::u32 backBufferHeight = m_windowSize.m_height; // Find ImGui Render Resolution. int renderRes[2]; @@ -759,10 +752,7 @@ void ImGuiManager::RenderImGuiBuffers(const ImVec2& scaleRects) //@rky: Only render the main ImGui if it is visible if (m_clientMenuBarState != DisplayState::Hidden) { - if (AZ::Interface::Get()) - { - OtherActiveImGuiRequestBus::Broadcast(&OtherActiveImGuiRequestBus::Events::RenderImGuiBuffers, *drawData); - } + OtherActiveImGuiRequestBus::Broadcast(&OtherActiveImGuiRequestBus::Events::RenderImGuiBuffers, *drawData); } } diff --git a/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp b/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp index 6f24d409c9..8dc37c94fe 100644 --- a/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp +++ b/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp @@ -19,7 +19,6 @@ #include #include -#include namespace WhiteBox { @@ -63,12 +62,7 @@ namespace WhiteBox SetRenderMeshInterfaceBuilder( []() -> AZStd::unique_ptr { - if (AZ::Interface::Get()) - { - return AZStd::make_unique(); - } - - return AZStd::make_unique(); + return AZStd::make_unique(); }); WhiteBoxRequestBus::Handler::BusConnect(); From f4def0c93fd20bd0b885c06276dcf0927e298963 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 16:33:06 -0500 Subject: [PATCH 019/112] Minor compile warning cleanup --- Code/Sandbox/Editor/CryEditDoc.cpp | 2 +- .../Editor/EditorImageBuilderComponent.cpp | 33 ------------------- 2 files changed, 1 insertion(+), 34 deletions(-) diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 2bc4dcf10c..6f3afa6850 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -2414,7 +2414,7 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU GetIEditor()->SetStatusText("Ready"); } -void CCryEditDoc::CreateDefaultLevelAssets(int resolution, int unitSize) +void CCryEditDoc::CreateDefaultLevelAssets([[maybe_unused]] int resolution, [[maybe_unused]] int unitSize) { AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); } diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index d7fcd3e56e..cc207b59a3 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -257,39 +257,6 @@ namespace GradientSignal return AZ::Uuid::CreateString("{7520DF20-16CA-4CF6-A6DB-D96759A09EE4}"); } - static AZStd::unique_ptr LegacyLoadImageFromPath(const AZStd::string& fullPath) - { - ImageProcessing::IImageObjectPtr imageObject; - ImageProcessing::ImageProcessingRequestBus::BroadcastResult(imageObject, &ImageProcessing::ImageProcessingRequests::LoadImage, - fullPath); - - if (!imageObject) - { - return {}; - } - - //create a new image asset - auto imageAsset = AZStd::make_unique(); - - if (!imageAsset) - { - return {}; - } - - imageAsset->m_imageWidth = imageObject->GetWidth(0); - imageAsset->m_imageHeight = imageObject->GetHeight(0); - imageAsset->m_imageFormat = imageObject->GetPixelFormat(); - - AZ::u8* mem = nullptr; - AZ::u32 pitch = 0; - AZ::u32 mipBufferSize = imageObject->GetMipBufSize(0); - imageObject->GetImagePointer(0, mem, pitch); - - imageAsset->m_imageData = { mem, mem + mipBufferSize }; - - return imageAsset; - } - static ImageProcessing::EPixelFormat AtomPixelFormatToLegacyPixelFormat(ImageProcessingAtom::EPixelFormat atomPixFormat) { // This could be dangerous to do if these enums have differences in the middle. From 6eddf39effc6c6160bfe9f90bb7154aa4a2fcb7f Mon Sep 17 00:00:00 2001 From: jonbeer Date: Mon, 3 May 2021 15:27:26 -0700 Subject: [PATCH 020/112] Adding additional PhysX tests for work with Prefabs --- .../Physics/ShapeConfiguration.cpp | 18 +++ Gems/PhysX/Code/CMakeLists.txt | 1 + .../Code/Tests/PhysXColliderPrefabTests.cpp | 126 ++++++++++++++++++ Gems/PhysX/Code/physx_tests_files.cmake | 1 + 4 files changed, 146 insertions(+) create mode 100644 Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp index f01e42a443..617fd026b6 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp @@ -32,6 +32,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Radius", &SphereShapeConfiguration::m_radius) @@ -60,6 +63,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Configuration", &BoxShapeConfiguration::m_dimensions) @@ -88,6 +94,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Height", &CapsuleShapeConfiguration::m_height) @@ -137,6 +146,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("PhysicsAsset", &PhysicsAssetShapeConfiguration::m_asset) @@ -169,6 +181,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Scale", &NativeShapeConfiguration::m_nativeShapeScale) @@ -192,6 +207,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("CookedData", &CookedMeshShapeConfiguration::m_cookedData) diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index ac5fd902c2..65fafcf88b 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -45,6 +45,7 @@ ly_add_target( ${physx_dependency} AZ::AzCore AZ::AzFramework + AZ::AzToolsFramework Legacy::CryCommon Gem::LmbrCentral ) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp new file mode 100644 index 0000000000..d489ac2990 --- /dev/null +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -0,0 +1,126 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + + +namespace PhysX +{ + class PhysXColliderPrefabTest + : public ::testing::Test + { + protected: + void SetUp() override + { + + } + + void TearDown() override + { + + } + + + }; + + TEST_F(PhysXColliderPrefabTest, JsonStoreAndLoadPhysicsObjectsWithPrefabTest) + { + AzToolsFramework::Prefab::PrefabDom prefabDom; + + //material selection + Physics::MaterialSelection materialSelection; + AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Material Selection", prefabDom); + + Physics::MaterialSelection newSelection; + AZ::JsonSerialization::Load(newSelection, prefabDom); + + EXPECT_EQ(materialSelection.GetMaterialId(), newSelection.GetMaterialId()); + + //collider configuration + Physics::ColliderConfiguration colliderConfig; + AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + Physics::ColliderConfiguration newConfig; + AZ::JsonSerialization::Load(newConfig, prefabDom); + + EXPECT_EQ(colliderConfig.m_collisionLayer, newConfig.m_collisionLayer); + + //shared pointer - collider configuration - defaults only + auto colliderConfigPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + colliderConfigPtr = nullptr; + AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + + EXPECT_NE(nullptr, colliderConfigPtr); + + //shared pointer - collider configuration - non default + auto updatedColliderConfigPtr = AZStd::make_shared(); + updatedColliderConfigPtr->m_isTrigger = true; + AZ::JsonSerializationResult::ResultCode result2 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + updatedColliderConfigPtr = nullptr; + AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + + EXPECT_NE(nullptr, updatedColliderConfigPtr); + + //shared pointer - shape configuration - defaults only + auto shapeConfigPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result3 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + + shapeConfigPtr = nullptr; + AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); + + EXPECT_NE(nullptr, shapeConfigPtr); + + //shared pointer - shape configuration - non default + auto updatedShapeConfigPtr = AZStd::make_shared(); + updatedShapeConfigPtr->m_radius = 2.0f; + AZ::JsonSerializationResult::ResultCode result4 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + + updatedShapeConfigPtr = nullptr; + AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + + EXPECT_NE(nullptr, updatedColliderConfigPtr); + } +} diff --git a/Gems/PhysX/Code/physx_tests_files.cmake b/Gems/PhysX/Code/physx_tests_files.cmake index 406aed64a7..182ff6a625 100644 --- a/Gems/PhysX/Code/physx_tests_files.cmake +++ b/Gems/PhysX/Code/physx_tests_files.cmake @@ -25,6 +25,7 @@ set(FILES Tests/PhysXForceRegionTest.cpp Tests/PhysXMaterialLibraryTest.cpp Tests/PhysXCollisionFilteringTest.cpp + Tests/PhysXColliderPrefabTests.cpp Tests/PhysXJointsTest.cpp Tests/PhysXSceneTests.cpp Tests/PhysXSceneQueryTests.cpp From 73dca7e9e2e3d806f0b48355343df6a68a7e4e1f Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 10:07:44 -0700 Subject: [PATCH 021/112] Fix Editor crash when slices are deleted with prefabs enabled --- .../ComponentEntityEditorPlugin/SandboxIntegration.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..7a418a1f2e 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -302,17 +302,20 @@ void SandboxIntegrationManager::OnCatalogAssetAdded(const AZ::Data::AssetId& ass // operation writing to shared resource is queued on main thread. void SandboxIntegrationManager::OnCatalogAssetRemoved(const AZ::Data::AssetId& assetId, const AZ::Data::AssetInfo& assetInfo) { + bool isPrefabSystemEnabled = false; + AzFramework::ApplicationRequests::Bus::BroadcastResult(isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); + // Check to see if the removed slice asset has any instance in the level, then check if // those dangling instances are directly under the root slice (not sub-slices). If yes, // detach them and save necessary information so they can be restored when their slice asset // comes back. - if (assetInfo.m_assetType == AZ::AzTypeInfo::Uuid()) + if (!isPrefabSystemEnabled && assetInfo.m_assetType == AZ::AzTypeInfo::Uuid()) { AZ::SliceComponent* rootSlice = nullptr; AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(rootSlice, &AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Events::GetEditorRootSlice); - AZ_Assert(rootSlice, "Editor root slice missing!"); + AZ_Assert(rootSlice != nullptr, "Editor root slice missing!"); AZStd::vector entitiesToDetach; const AZ::SliceComponent::SliceList& subSlices = rootSlice->GetSlices(); From d8145d33e94118527de48a6d2e3b54904cfdd73e Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 10:13:55 -0700 Subject: [PATCH 022/112] Reverted an assert condition to its previous state --- .../Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 7a418a1f2e..724664b1dc 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -315,7 +315,7 @@ void SandboxIntegrationManager::OnCatalogAssetRemoved(const AZ::Data::AssetId& a AZ::SliceComponent* rootSlice = nullptr; AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(rootSlice, &AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Events::GetEditorRootSlice); - AZ_Assert(rootSlice != nullptr, "Editor root slice missing!"); + AZ_Assert(rootSlice, "Editor root slice missing!"); AZStd::vector entitiesToDetach; const AZ::SliceComponent::SliceList& subSlices = rootSlice->GetSlices(); From a7624bb98587372350549fe15c1c63250b4434ac Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 17:23:00 -0700 Subject: [PATCH 023/112] Removed returning AZ::Failure when AZ::Assert is thrown --- .../Prefab/PrefabPublicHandler.cpp | 57 ++++++------------- .../Prefab/PrefabPublicHandler.h | 3 +- 2 files changed, 17 insertions(+), 43 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1b4bf9f50c..475510c52f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -96,12 +96,7 @@ namespace AzToolsFramework // target templates of the other instances. for (auto& nestedInstance : instances) { - PrefabOperationResult removeLinkResult = RemoveLink( - nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); - if (!removeLinkResult.IsSuccess()) - { - return removeLinkResult; - } + RemoveLink(nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); } PrefabUndoHelpers::UpdatePrefabInstance( @@ -241,14 +236,9 @@ namespace AzToolsFramework // Retrieve the owning instance of the common root entity, which will be our new instance's parent instance. commonRootEntityOwningInstance = GetOwnerInstanceByEntityId(commonRootEntityId); - if (!commonRootEntityOwningInstance) - { - AZ_Assert( - false, - "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided"); - return AZ::Failure(AZStd::string( - "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided")); - } + AZ_Assert( + commonRootEntityOwningInstance.has_value(), + "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided"); return AZ::Success(); } @@ -290,47 +280,32 @@ namespace AzToolsFramework m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); } - PrefabOperationResult PrefabPublicHandler::RemoveLink( + void PrefabPublicHandler::RemoveLink( AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch) { LinkReference nestedInstanceLink = m_prefabSystemComponentInterface->FindLink(sourceInstance->GetLinkId()); - if (!nestedInstanceLink.has_value()) - { - AZ_Assert(false, "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); - return AZ::Failure( - AZStd::string("A valid link was not found for one of the instances provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLink.has_value(), + "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom(); - if (!nestedInstanceLinkDom.has_value()) - { - AZ_Assert( - false, - "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " - "CreatePrefab operation."); - return AZ::Failure(AZStd::string("A valid DOM was not found for the link corresponding to one of the instances " - "provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLinkDom.has_value(), + "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); PrefabDomValueReference nestedInstanceLinkPatches = PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName); - if (!nestedInstanceLinkPatches.has_value()) - { - AZ_Assert( - false, - "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " - "CreatePrefab operation."); - return AZ::Failure(AZStd::string("A valid DOM for patcheswas not found for the link corresponding to one of the instances " - "provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLinkPatches.has_value(), + "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); PrefabDom patchesCopyForUndoSupport; patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); PrefabUndoHelpers::RemoveLink( sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), patchesCopyForUndoSupport, undoBatch); - - return AZ::Success(); } PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 8d27603e8d..5ade666a40 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -88,9 +88,8 @@ namespace AzToolsFramework * \param sourceInstance The instance corresponding to the source template of the link to be removed. * \param targetTemplateId The id of the target template of the link to be removed. * \param undoBatch The undo batch to set as parent for this remove link action. - * \return PrefabOperationResult Indicates whether the removal of link was successful. */ - PrefabOperationResult RemoveLink( + void RemoveLink( AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch); /** From 03c219bd2dfa6d3d5f37a7bfe552e1dd04f4087e Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 21:31:06 -0500 Subject: [PATCH 024/112] Removed unused code --- Code/Sandbox/Editor/IconManager.cpp | 7 --- .../SandboxIntegration.cpp | 7 --- .../Code/Source/AtomBridgeEditorModule.cpp | 2 - .../Code/Source/BuilderComponent.cpp | 53 ------------------- .../AtomBridge/Code/Source/BuilderComponent.h | 36 ------------- .../Code/atombridge_editor_files.cmake | 2 - 6 files changed, 107 deletions(-) delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 3916ee7726..828a7cdfcc 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -114,13 +114,6 @@ int CIconManager::GetIconTexture(const char* iconName) return 0; } - ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; - if (texture) - { - id = texture->GetTextureID(); - m_textures[iconName] = id; - } - return id; } diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index b0dce80ec8..378bf3d4a1 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -161,13 +161,6 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); - // turn on the this debug display request bus implementation if no other implementation is active - if( !(AzFramework::DebugDisplayRequestBus::HasHandlers())) - { - m_debugDisplayBusImplementationActive = true; - AzFramework::DebugDisplayRequestBus::Handler::BusConnect( - AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); - } AzFramework::DisplayContextRequestBus::Handler::BusConnect(); SetupFileExtensionMap(); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp index c955523d09..f2c2a6f5aa 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include "./Editor/AssetCollectionAsyncLoaderTestComponent.h" @@ -33,7 +32,6 @@ namespace AZ { // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. m_descriptors.insert(m_descriptors.end(), { - BuilderComponent::CreateDescriptor(), AssetCollectionAsyncLoaderTestComponent::CreateDescriptor(), }); } diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp deleted file mode 100644 index 997b7c3b0c..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include - -#include - -#include - -namespace AZ -{ - namespace AtomBridge - { - void BuilderComponent::Reflect(AZ::ReflectContext* context) - { - if (auto* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })) - ; - } - } - - BuilderComponent::BuilderComponent() - { - } - - BuilderComponent::~BuilderComponent() - { - } - - void BuilderComponent::Activate() - { - } - - void BuilderComponent::Deactivate() - { - } - } // namespace RPI -} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h deleted file mode 100644 index d6c462cc43..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -namespace AZ -{ - namespace AtomBridge - { - class BuilderComponent final - : public AZ::Component - { - public: - AZ_COMPONENT(BuilderComponent, "{D1FE015B-8431-4155-8FD0-8197F246901A}"); - static void Reflect(AZ::ReflectContext* context); - - BuilderComponent(); - ~BuilderComponent() override; - - // AZ::Component overrides... - void Activate() override; - void Deactivate() override; - }; - } // namespace RPI -} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake index f2cf8c6c14..55ed9f28a0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake @@ -13,8 +13,6 @@ set(FILES Source/AtomBridgeEditorModule.cpp Source/AtomBridgeModule.cpp Source/AtomBridgeModule.h - Source/BuilderComponent.cpp - Source/BuilderComponent.h Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp Source/Editor/AssetCollectionAsyncLoaderTestComponent.h ) From 837458abf27a13e10ede29226bbe3aa30c3b9791 Mon Sep 17 00:00:00 2001 From: jiaweig Date: Mon, 3 May 2021 20:23:03 -0700 Subject: [PATCH 025/112] ATOM-15391 [RHI][Vulkan][Android] SSAO introduces horizontal lines on flat surfaces --- .../Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl index c1fa41991e..8294911b44 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl @@ -277,6 +277,8 @@ void MainCS(uint3 thread_id : SV_GroupThreadID, uint3 group_id : SV_GroupID, uin // Gather depth values float2 depthGatherUV = mad(float2(ldsPosition), GetPixelSize(), ldsOffsetUV); + // Gather on some GPUs will fall onto same pixels in adjacent coordinates due to rounding errors + depthGatherUV += GetHalfPixelSize(); float4 depthGather = PassSrg::m_linearDepth.Gather(PassSrg::PointSampler, depthGatherUV); WriteDepthGatherToLDS(ldsPosition, depthGather); From 80f692118bb15de792679c99597785911fb587e8 Mon Sep 17 00:00:00 2001 From: guthadam Date: Tue, 4 May 2021 01:27:12 -0500 Subject: [PATCH 026/112] ATOM-15451 always bring material editor and foreground when launching Bus, command line option, and handler to activate material editor window Made sure that material editor action in Ly tools menu is not checked/checkable Ly editor pushes command line option to use the same RHI https://jira.agscollab.com/browse/LYN-2610 https://jira.agscollab.com/browse/ATOM-15451 https://jira.agscollab.com/browse/ATOM-13742 --- .../Window/MaterialEditorWindowRequestBus.h | 3 +++ .../Code/Source/MaterialEditorApplication.cpp | 12 ++++++++++++ .../Source/Window/MaterialEditorWindow.cpp | 6 ++++++ .../Code/Source/Window/MaterialEditorWindow.h | 1 + .../Window/MaterialEditorWindowComponent.cpp | 1 + .../Material/EditorMaterialSystemComponent.cpp | 18 +++++++++++++++++- 6 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h index 538777b762..55e6ddac20 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h @@ -28,6 +28,9 @@ namespace MaterialEditor static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + //! Bring main window to foreground + virtual void ActivateWindow() = 0; + //! Add dockable widget in main window //! @param name title of the dockable window //! @param widget docked window content diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index ea82210814..3ffe2af1a6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -45,6 +45,7 @@ #include #include +#include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT @@ -309,6 +310,13 @@ namespace MaterialEditor void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { + const AZStd::string activateWindowSwitchName = "activatewindow"; + if (commandLine.HasSwitch(activateWindowSwitchName)) + { + MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( + &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); + } + const AZStd::string timeoputSwitchName = "timeout"; if (commandLine.HasSwitch(timeoputSwitchName)) { @@ -438,6 +446,10 @@ namespace MaterialEditor // Handle commmand line params from connected socket if (buffer.startsWith("ProcessCommandLine:")) { + // Bring the material editor to the foreground + MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( + &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); + // Remove header and parse commands AZStd::string params(buffer.data(), buffer.size()); params = params.substr(strlen("ProcessCommandLine:")); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 1e116b4a22..6e47de189c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -129,6 +129,12 @@ namespace MaterialEditor MaterialEditorWindowRequestBus::Handler::BusDisconnect(); } + void MaterialEditorWindow::ActivateWindow() + { + activateWindow(); + raise(); + } + bool MaterialEditorWindow::AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) { auto dockWidgetItr = m_dockWidgets.find(name); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 6bd6e6b165..778e11275f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -61,6 +61,7 @@ namespace MaterialEditor private: // MaterialEditorWindowRequestBus::Handler overrides... + void ActivateWindow() override; bool AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) override; void RemoveDockWidget(const AZStd::string& name) override; void SetDockWidgetVisible(const AZStd::string& name, bool visible) override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index a1ff8da635..820cee30f9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -50,6 +50,7 @@ namespace MaterialEditor ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") + ->Event("ActivateWindow", &MaterialEditorWindowRequestBus::Events::ActivateWindow) ->Event("SetDockWidgetVisible", &MaterialEditorWindowRequestBus::Events::SetDockWidgetVisible) ->Event("IsDockWidgetVisible", &MaterialEditorWindowRequestBus::Events::IsDockWidgetVisible) ->Event("GetDockWidgetNames", &MaterialEditorWindowRequestBus::Events::GetDockWidgetNames) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index c32f124456..4cf51e2f37 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -23,6 +23,8 @@ #include #include +#include + #include #include @@ -125,6 +127,17 @@ namespace AZ QStringList arguments; arguments.append(sourcePath.c_str()); + + // Bring the material editor to the foreground if running + arguments.append("--activatewindow"); + + // Use the same RHI as the main editor + AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); + if (!apiName.IsEmpty()) + { + arguments.append(QString("--rhi=%1").arg(apiName.GetCStr())); + } + AtomToolsFramework::LaunchTool("MaterialEditor", ".exe", arguments); } @@ -139,7 +152,10 @@ namespace AZ { m_openMaterialEditorAction = new QAction("Material Editor"); m_openMaterialEditorAction->setShortcut(QKeySequence(Qt::Key_M)); - QObject::connect(m_openMaterialEditorAction, &QAction::triggered, m_openMaterialEditorAction, [this]() + m_openMaterialEditorAction->setCheckable(false); + m_openMaterialEditorAction->setChecked(false); + QObject::connect( + m_openMaterialEditorAction, &QAction::triggered, m_openMaterialEditorAction, [this]() { OpenInMaterialEditor(""); } From 64f42ba1cba87fb6c47e2662350e3ee09539b805 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 4 May 2021 01:24:14 -0700 Subject: [PATCH 027/112] Removed the asset callback from the EditorReflectionProbeComponent, since the component may have been destroyed and recreated between the bake and the asset load. Replaced with an OnTick handler that polls the ReflectionProbeFeatureProcessor to determine when the asset is ready. --- .../ReflectionProbeFeatureProcessor.h | 13 +- ...ReflectionProbeFeatureProcessorInterface.h | 9 +- .../ReflectionProbe/ReflectionProbe.cpp | 3 +- .../Source/ReflectionProbe/ReflectionProbe.h | 5 +- .../ReflectionProbeFeatureProcessor.cpp | 72 +++--- .../EditorReflectionProbeComponent.cpp | 225 +++++++++--------- .../EditorReflectionProbeComponent.h | 6 + .../ReflectionProbeComponentController.cpp | 31 ++- .../ReflectionProbeComponentController.h | 2 +- 9 files changed, 210 insertions(+), 156 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h index a89875aaa6..ff84f77a3e 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h @@ -36,10 +36,11 @@ namespace AZ void RemoveProbe(ReflectionProbeHandle& probe) override; void SetProbeOuterExtents(const ReflectionProbeHandle& probe, const AZ::Vector3& outerExtents) override; void SetProbeInnerExtents(const ReflectionProbeHandle& probe, const AZ::Vector3& innerExtents) override; - void SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage) override; + void SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage, const AZStd::string& relativePath) override; void SetProbeTransform(const ReflectionProbeHandle& probe, const AZ::Transform& transform) override; - void BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback) override; - void NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) override; + void BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback, const AZStd::string& relativePath) override; + bool CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) override; + bool IsCubeMapReferenced(const AZStd::string& relativePath) override; bool IsValidProbeHandle(const ReflectionProbeHandle& probe) const override { return (probe.get() != nullptr); } void ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) override; @@ -72,10 +73,9 @@ namespace AZ // AssetBus::MultiHandler overrides... void OnAssetReady(Data::Asset asset) override; void OnAssetError(Data::Asset asset) override; - void OnAssetReloaded(Data::Asset asset) override; // notifies and removes the notification entry - void HandleAssetNotification(Data::Asset asset, CubeMapAssetNotificationType notificationTyp); + void HandleAssetNotification(Data::Asset asset, CubeMapAssetNotificationType notificationType); // list of reflection probes const size_t InitialProbeAllocationSize = 64; @@ -86,9 +86,8 @@ namespace AZ { AZStd::string m_relativePath; AZ::Data::AssetId m_assetId; - bool m_existingAsset = false; - NotifyCubeMapAssetReadyCallback m_callback; Data::Asset m_asset; + CubeMapAssetNotificationType m_notificationType = CubeMapAssetNotificationType::None; }; typedef AZStd::vector NotifyCubeMapAssetVector; NotifyCubeMapAssetVector m_notifyCubeMapAssets; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h index 8b277e97c8..03c44d0442 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h @@ -30,11 +30,11 @@ namespace AZ enum CubeMapAssetNotificationType { + None, Ready, Error, Reloaded }; - using NotifyCubeMapAssetReadyCallback = AZStd::function& cubeMapAsset, CubeMapAssetNotificationType notificationType)>; // ReflectionProbeFeatureProcessorInterface provides an interface to the feature processor for code outside of Atom class ReflectionProbeFeatureProcessorInterface @@ -47,10 +47,11 @@ namespace AZ virtual void RemoveProbe(ReflectionProbeHandle& handle) = 0; virtual void SetProbeOuterExtents(const ReflectionProbeHandle& handle, const AZ::Vector3& outerExtents) = 0; virtual void SetProbeInnerExtents(const ReflectionProbeHandle& handle, const AZ::Vector3& innerExtents) = 0; - virtual void SetProbeCubeMap(const ReflectionProbeHandle& handle, Data::Instance& cubeMapImage) = 0; + virtual void SetProbeCubeMap(const ReflectionProbeHandle& handle, Data::Instance& cubeMapImage, const AZStd::string& relativePath) = 0; virtual void SetProbeTransform(const ReflectionProbeHandle& handle, const AZ::Transform& transform) = 0; - virtual void BakeProbe(const ReflectionProbeHandle& handle, BuildCubeMapCallback callback) = 0; - virtual void NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) = 0; + virtual void BakeProbe(const ReflectionProbeHandle& handle, BuildCubeMapCallback callback, const AZStd::string& relativePath) = 0; + virtual bool CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) = 0; + virtual bool IsCubeMapReferenced(const AZStd::string& relativePath) = 0; virtual bool IsValidProbeHandle(const ReflectionProbeHandle& probe) const = 0; virtual void ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) = 0; }; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index cfce718146..e0b79e23aa 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -234,9 +234,10 @@ namespace AZ m_updateSrg = true; } - void ReflectionProbe::SetCubeMapImage(const Data::Instance& cubeMapImage) + void ReflectionProbe::SetCubeMapImage(const Data::Instance& cubeMapImage, const AZStd::string& relativePath) { m_cubeMapImage = cubeMapImage; + m_cubeMapRelativePath = relativePath; m_updateSrg = true; } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h index 42b3ff5c5a..ab0e7a81d3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h @@ -88,7 +88,9 @@ namespace AZ const Aabb& GetInnerAabbWs() const { return m_innerAabbWs; } const Data::Instance& GetCubeMapImage() const { return m_cubeMapImage; } - void SetCubeMapImage(const Data::Instance& cubeMapImage); + void SetCubeMapImage(const Data::Instance& cubeMapImage, const AZStd::string& relativePath); + + const AZStd::string& GetCubeMapRelativePath() const { return m_cubeMapRelativePath; } bool GetUseParallaxCorrection() const { return m_useParallaxCorrection; } void SetUseParallaxCorrection(bool useParallaxCorrection) { m_useParallaxCorrection = useParallaxCorrection; } @@ -135,6 +137,7 @@ namespace AZ // cubemap Data::Instance m_cubeMapImage; + AZStd::string m_cubeMapRelativePath; bool m_useParallaxCorrection = false; // probe visualization diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index a0d3e6ac51..740069fc6b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -178,9 +178,9 @@ namespace AZ if (assetId.IsValid()) { - Data::AssetBus::MultiHandler::BusConnect(assetId); notificationEntry.m_assetId = assetId; notificationEntry.m_asset.Create(assetId, true); + Data::AssetBus::MultiHandler::BusConnect(assetId); } } @@ -257,10 +257,10 @@ namespace AZ m_probeSortRequired = true; } - void ReflectionProbeFeatureProcessor::SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage) + void ReflectionProbeFeatureProcessor::SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage, const AZStd::string& relativePath) { AZ_Assert(probe.get(), "SetProbeCubeMap called with an invalid handle"); - probe->SetCubeMapImage(cubeMapImage); + probe->SetCubeMapImage(cubeMapImage, relativePath); } void ReflectionProbeFeatureProcessor::SetProbeTransform(const ReflectionProbeHandle& probe, const AZ::Transform& transform) @@ -270,14 +270,11 @@ namespace AZ m_probeSortRequired = true; } - void ReflectionProbeFeatureProcessor::BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback) + void ReflectionProbeFeatureProcessor::BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback, const AZStd::string& relativePath) { AZ_Assert(probe.get(), "BakeProbe called with an invalid handle"); probe->BuildCubeMap(callback); - } - void ReflectionProbeFeatureProcessor::NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) - { // check to see if this is an existing asset AZ::Data::AssetId assetId; AZ::Data::AssetCatalogRequestBus::BroadcastResult( @@ -287,15 +284,46 @@ namespace AZ azrtti_typeid(), false); - bool existingAsset = assetId.IsValid(); - m_notifyCubeMapAssets.push_back({ relativePath, assetId, existingAsset, callback }); - - if (existingAsset) + // we only track notifications for new cubemap assets, existing assets are automatically reloaded by the RPI + if (!assetId.IsValid()) { - Data::AssetBus::MultiHandler::BusConnect(assetId); + m_notifyCubeMapAssets.push_back({ relativePath, assetId }); } } + bool ReflectionProbeFeatureProcessor::CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) + { + for (NotifyCubeMapAssetVector::iterator itNotification = m_notifyCubeMapAssets.begin(); itNotification != m_notifyCubeMapAssets.end(); ++itNotification) + { + if (itNotification->m_relativePath == relativePath) + { + outNotificationType = itNotification->m_notificationType; + if (outNotificationType != CubeMapAssetNotificationType::None) + { + outCubeMapAsset = itNotification->m_asset; + m_notifyCubeMapAssets.erase(itNotification); + } + + return true; + } + } + + return false; + } + + bool ReflectionProbeFeatureProcessor::IsCubeMapReferenced(const AZStd::string& relativePath) + { + for (auto& reflectionProbe : m_reflectionProbes) + { + if (reflectionProbe->GetCubeMapRelativePath() == relativePath) + { + return true; + } + } + + return false; + } + void ReflectionProbeFeatureProcessor::ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) { AZ_Assert(probe.get(), "ShowProbeVisualization called with an invalid handle"); @@ -509,17 +537,9 @@ namespace AZ { if (itNotification->m_assetId == asset.GetId()) { - if (itNotification->m_existingAsset && notificationType == CubeMapAssetNotificationType::Ready) - { - // existing cubemap assets only notify on reload or error - break; - } - - // notify - itNotification->m_callback(Data::static_pointer_cast(asset), notificationType); - - // remove the entry from the list - m_notifyCubeMapAssets.erase(itNotification); + // store the cubemap asset + itNotification->m_asset = Data::static_pointer_cast(asset); + itNotification->m_notificationType = notificationType; // stop notifications on this asset Data::AssetBus::MultiHandler::BusDisconnect(itNotification->m_assetId); @@ -540,11 +560,5 @@ namespace AZ HandleAssetNotification(asset, CubeMapAssetNotificationType::Error); } - - void ReflectionProbeFeatureProcessor::OnAssetReloaded(Data::Asset asset) - { - HandleAssetNotification(asset, CubeMapAssetNotificationType::Reloaded); - } - } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp index 9d34553eba..735eab5368 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp @@ -133,23 +133,14 @@ namespace AZ AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(GetEntityId()); EditorReflectionProbeBus::Handler::BusConnect(GetEntityId()); + AZ::TickBus::Handler::BusConnect(); ReflectionProbeComponentConfig& configuration = m_controller.m_configuration; - // special handling is required if this component is being cloned in the editor: - // if the entityId in the configuration does not match this component's entityId it is being cloned - AZ::u64 entityId = (AZ::u64)GetEntityId(); - if (configuration.m_entityId != EntityId::InvalidEntityId - && configuration.m_entityId != entityId) - { - // clear the cubeMapRelativePath to prevent the newly cloned reflection probe - // from using the same cubemap path as the original reflection probe - configuration.m_bakedCubeMapRelativePath = ""; - } - // update UI cubemap path display m_bakedCubeMapRelativePath = configuration.m_bakedCubeMapRelativePath; + AZ::u64 entityId = (AZ::u64)GetEntityId(); configuration.m_entityId = entityId; } @@ -158,9 +149,55 @@ namespace AZ EditorReflectionProbeBus::Handler::BusDisconnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); BaseClass::Deactivate(); } + void EditorReflectionProbeComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + if (!m_controller.m_featureProcessor) + { + return; + } + + if (m_controller.m_configuration.m_useBakedCubemap) + { + AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath + ".streamingimage"; + Data::Asset cubeMapAsset; + CubeMapAssetNotificationType notificationType = CubeMapAssetNotificationType::None; + if (m_controller.m_featureProcessor->CheckCubeMapAssetNotification(cubeMapRelativePath, cubeMapAsset, notificationType)) + { + // a cubemap bake is in progress for this entity component + if (notificationType == CubeMapAssetNotificationType::Ready) + { + // bake is complete, update configuration with the new baked cubemap asset + m_controller.m_configuration.m_bakedCubeMapAsset = { cubeMapAsset.GetAs(), AZ::Data::AssetLoadBehavior::PreLoad }; + + // refresh the currently rendered cubemap + m_controller.UpdateCubeMap(); + + // update the UI + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); + } + else if (notificationType == CubeMapAssetNotificationType::Error) + { + // cubemap bake failed + QMessageBox::information( + QApplication::activeWindow(), + "Reflection Probe", + "Reflection Probe cubemap failed to bake, please check the Asset Processor for more information.", + QMessageBox::Ok); + + // clear relative path, this will allow the user to retry + m_controller.m_configuration.m_bakedCubeMapRelativePath.clear(); + + // update the UI + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); + } + } + } + } + void EditorReflectionProbeComponent::DisplayEntityViewport([[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { // only draw the bounds if selected @@ -276,122 +313,94 @@ namespace AZ return AZ::Edit::PropertyRefreshLevels::None; } - // callback from the EnvironmentCubeMapPass when the cubemap render is complete - BuildCubeMapCallback buildCubeMapCallback = [this](uint8_t* const* cubeMapFaceTextureData, const RHI::Format cubeMapTextureFormat) + char projectPath[AZ_MAX_PATH_LEN]; + AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); + + // retrieve the source cubemap path from the configuration + // we need to make sure to use the same source cubemap for each bake + AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath; + AZStd::string cubeMapFullPath; + + if (!cubeMapRelativePath.empty()) { - if (!m_bakeInProgress) + // test to see if the cubemap file is actually there, if it was removed we need to + // generate a new filename, otherwise it will cause an error in the asset system + AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); + + if (!AZ::IO::FileIOBase::GetInstance()->Exists(cubeMapFullPath.c_str())) { - // user canceled the bake - return; + // clear it to force the generation of a new filename + cubeMapRelativePath.clear(); } + } - char projectPath[AZ_MAX_PATH_LEN]; - AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); + // build a new cubemap path if necessary + if (cubeMapRelativePath.empty()) + { + // the file name is a combination of the entity name, a UUID, and the filemask + Entity* entity = GetEntity(); + AZ_Assert(entity, "ReflectionProbe entity is null"); - // retrieve the source cubemap path from the configuration - // we need to make sure to use the same source cubemap for each bake - AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath; - AZStd::string cubeMapFullPath; + AZ::Uuid uuid = AZ::Uuid::CreateRandom(); + AZStd::string uuidString; + uuid.ToString(uuidString); - if (!cubeMapRelativePath.empty()) + cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + "_iblspecularcm.dds"; + + // replace any invalid filename characters + auto invalidCharacters = [](char letter) { - // test to see if the cubemap file is actually there, if it was removed we need to - // generate a new filename, otherwise it will cause an error in the asset system - AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); + return + letter == ':' || letter == '"' || letter == '\'' || + letter == '{' || letter == '}' || + letter == '<' || letter == '>'; + }; + AZStd::replace_if(cubeMapRelativePath.begin(), cubeMapRelativePath.end(), invalidCharacters, '_'); - if (!AZ::IO::FileIOBase::GetInstance()->Exists(cubeMapFullPath.c_str())) - { - // clear it to force the generation of a new filename - cubeMapRelativePath.clear(); - } - } + // build the full source path + AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); + } - // build a new cubemap path if necessary - if (cubeMapRelativePath.empty()) - { - // the file name is a combination of the entity name, a UUID, and the filemask - Entity* entity = GetEntity(); - AZ_Assert(entity, "ReflectionProbe entity is null"); + // make sure the folder is created + AZStd::string reflectionProbeFolder; + AzFramework::StringFunc::Path::GetFolderPath(cubeMapFullPath.data(), reflectionProbeFolder); + AZ::IO::SystemFile::CreateDir(reflectionProbeFolder.c_str()); - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); + // check out the file in source control + bool checkedOutSuccessfully = false; + using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; + ApplicationBus::BroadcastResult( + checkedOutSuccessfully, + &ApplicationBus::Events::RequestEditForFileBlocking, + cubeMapFullPath.c_str(), + "Checking out for edit...", + ApplicationBus::Events::RequestEditProgressCallback()); - cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + "_iblspecularcm.dds"; + if (!checkedOutSuccessfully) + { + AZ_Error("ReflectionProbe", false, "Failed to write \"%s\", source control checkout failed", cubeMapFullPath.c_str()); + } - // replace any invalid filename characters - auto invalidCharacters = [](char letter) - { - return - letter == ':' || letter == '"' || letter == '\'' || - letter == '{' || letter == '}' || - letter == '<' || letter == '>'; - }; - AZStd::replace_if(cubeMapRelativePath.begin(), cubeMapRelativePath.end(), invalidCharacters, '_'); + // save the relative source path in the configuration + AzToolsFramework::ScopedUndoBatch undoBatch("Cubemap path changed."); + m_controller.m_configuration.m_bakedCubeMapRelativePath = cubeMapRelativePath; + SetDirty(); - // build the full source path - AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); - } - - // make sure the folder is created - AZStd::string reflectionProbeFolder; - AzFramework::StringFunc::Path::GetFolderPath(cubeMapFullPath.data(), reflectionProbeFolder); - AZ::IO::SystemFile::CreateDir(reflectionProbeFolder.c_str()); - - // check out the file in source control - bool checkedOutSuccessfully = false; - using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; - ApplicationBus::BroadcastResult( - checkedOutSuccessfully, - &ApplicationBus::Events::RequestEditForFileBlocking, - cubeMapFullPath.c_str(), - "Checking out for edit...", - ApplicationBus::Events::RequestEditProgressCallback()); - - if (!checkedOutSuccessfully) - { - AZ_Error("ReflectionProbe", false, "Failed to write \"%s\", source control checkout failed", cubeMapFullPath.c_str()); - } + // update UI cubemap path display + m_bakedCubeMapRelativePath = cubeMapRelativePath; + // callback from the EnvironmentCubeMapPass when the cubemap render is complete + BuildCubeMapCallback buildCubeMapCallback = [=](uint8_t* const* cubeMapFaceTextureData, const RHI::Format cubeMapTextureFormat) + { // write the cubemap data to the .dds file WriteOutputFile(cubeMapFullPath.c_str(), cubeMapFaceTextureData, cubeMapTextureFormat); - - // save the relative source path in the configuration - AzToolsFramework::ScopedUndoBatch undoBatch("Cubemap path changed."); - m_controller.m_configuration.m_bakedCubeMapRelativePath = cubeMapRelativePath; - SetDirty(); - - // update UI cubemap path display - m_bakedCubeMapRelativePath = cubeMapRelativePath; - - // call the feature processor to notify when the asset is created and ready - NotifyCubeMapAssetReadyCallback notifyCubeMapAssetReadyCallback = [this](const Data::Asset& cubeMapAsset, CubeMapAssetNotificationType notificationType) - { - // we only need to store the cubemap asset and update the cubemap image on the first bake of the probe, - // otherwise it is a hot-reload of an existing cubemap asset which is handled by the RPI - if (notificationType == CubeMapAssetNotificationType::Ready) - { - // update configuration with the new baked cubemap asset - m_controller.m_configuration.m_bakedCubeMapAsset = { cubeMapAsset.GetAs(), AZ::Data::AssetLoadBehavior::PreLoad }; - - // refresh the currently rendered cubemap - m_controller.UpdateCubeMap(); - - // update the UI - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); - } - - // signal completion - m_bakeInProgress = false; - }; - - AZStd::string cubeMapRelativeAssetPath = cubeMapRelativePath + ".streamingimage"; - m_controller.m_featureProcessor->NotifyCubeMapAssetReady(cubeMapRelativeAssetPath, notifyCubeMapAssetReadyCallback); + m_bakeInProgress = false; }; - // initiate the cubemap bake + // initiate the cubemap bake, this will invoke the buildCubeMapCallback when the cubemap data is ready m_bakeInProgress = true; - m_controller.BakeReflectionProbe(buildCubeMapCallback); + AZStd::string cubeMapRelativeAssetPath = cubeMapRelativePath + ".streamingimage"; + m_controller.BakeReflectionProbe(buildCubeMapCallback, cubeMapRelativeAssetPath); // show a dialog box letting the user know the probe is baking QProgressDialog bakeDialog; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h index eba9575ec4..23fd391818 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include #include #include @@ -29,6 +30,7 @@ namespace AZ , public EditorReflectionProbeBus::Handler , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler , private AzFramework::EntityDebugDisplayEventBus::Handler + , private AZ::TickBus::Handler { public: using BaseClass = EditorRenderComponentAdapter; @@ -45,8 +47,12 @@ namespace AZ // AzFramework::EntityDebugDisplayEventBus::Handler overrides void DisplayEntityViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + private: + // AZ::TickBus overrides + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + // validation AZ::Outcome OnUseBakedCubemapValidate(void* newValue, const AZ::Uuid& valueType); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index c7349adefa..59d1f7afa7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -111,6 +111,18 @@ namespace AZ m_boxShapeInterface = LmbrCentral::BoxShapeComponentRequestsBus::FindFirstHandler(m_entityId); AZ_Assert(m_boxShapeInterface, "ReflectionProbeComponentController was unable to find box shape component"); + // special handling is required if this component is being cloned in the editor: + // if this probe is using a baked cubemap, check to see if it is already referenced by another probe + if (m_configuration.m_useBakedCubemap) + { + if (m_featureProcessor->IsCubeMapReferenced(m_configuration.m_bakedCubeMapRelativePath)) + { + // clear the cubeMapRelativePath to prevent the newly cloned reflection probe + // from using the same cubemap path as the original reflection probe + m_configuration.m_bakedCubeMapRelativePath = ""; + } + } + // add this reflection probe to the feature processor const AZ::Transform& transform = m_transformInterface->GetWorldTM(); m_handle = m_featureProcessor->AddProbe(transform, m_configuration.m_useParallaxCorrection); @@ -130,12 +142,15 @@ namespace AZ m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapAsset : m_configuration.m_authoredCubeMapAsset; Data::AssetBus::MultiHandler::BusConnect(cubeMapAsset.GetId()); + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + if (cubeMapAsset.GetId().IsValid()) { if (cubeMapAsset.IsReady()) { Data::Instance image = RPI::StreamingImage::FindOrCreate(cubeMapAsset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } else { @@ -169,8 +184,11 @@ namespace AZ return; } + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + Data::Instance image = RPI::StreamingImage::FindOrCreate(asset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } void ReflectionProbeComponentController::SetConfiguration(const ReflectionProbeComponentConfig& config) @@ -188,8 +206,11 @@ namespace AZ Data::Asset& cubeMapAsset = m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapAsset : m_configuration.m_authoredCubeMapAsset; + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + Data::Instance image = RPI::StreamingImage::FindOrCreate(cubeMapAsset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } void ReflectionProbeComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) @@ -240,14 +261,14 @@ namespace AZ m_configuration.m_innerHeight = AZStd::min(m_configuration.m_innerHeight, m_configuration.m_outerHeight); } - void ReflectionProbeComponentController::BakeReflectionProbe(BuildCubeMapCallback callback) + void ReflectionProbeComponentController::BakeReflectionProbe(BuildCubeMapCallback callback, const AZStd::string& relativePath) { if (!m_featureProcessor) { return; } - m_featureProcessor->BakeProbe(m_handle, callback); + m_featureProcessor->BakeProbe(m_handle, callback, relativePath); } AZ::Aabb ReflectionProbeComponentController::GetAabb() const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h index 20d692145c..0a57fde882 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h @@ -79,7 +79,7 @@ namespace AZ AZ::Aabb GetAabb() const; // initiate the reflection probe bake, invokes callback when complete - void BakeReflectionProbe(BuildCubeMapCallback callback); + void BakeReflectionProbe(BuildCubeMapCallback callback, const AZStd::string& relativePath); // update the currently rendering cubemap asset for this probe void UpdateCubeMap(); From 3df5f53e5ee465cc3f8f580a9d18095300d8c9d1 Mon Sep 17 00:00:00 2001 From: balibhan Date: Tue, 4 May 2021 15:16:31 +0530 Subject: [PATCH 028/112] updating timeout --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 6d3727195e..2a8423bd5a 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -68,7 +68,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/scripting/TestSuite_Active.py - TIMEOUT 1500 + TIMEOUT 3000 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor From d705864f8882039492133cb1e3e29bb06bf303b8 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 13:09:23 +0100 Subject: [PATCH 029/112] fix for input being 'stuck' on --- .../AzFramework/Viewport/CameraInput.cpp | 13 ++++++------- .../AzFramework/AzFramework/Viewport/CameraInput.h | 5 +++++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 851522c701..069c9d5fc9 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -276,7 +276,7 @@ namespace AzFramework } else if (input->m_state == InputChannel::State::Ended) { - m_translation ^= translationFromKey(input->m_channelId); + m_translation &= ~(translationFromKey(input->m_channelId)); if (m_translation == TranslationType::Nil) { EndActivation(); @@ -521,20 +521,19 @@ namespace AzFramework return button == inputChannelId; }); - if (inputChannelId == InputDeviceMouse::SystemCursorPosition) + if (inputChannelId == InputDeviceMouse::Movement::X || inputChannelId == InputDeviceMouse::Movement::Y) { - AZ::Vector2 systemCursorPositionNormalized = AZ::Vector2::CreateZero(); - InputSystemCursorRequestBus::EventResult( - systemCursorPositionNormalized, inputDeviceId, &InputSystemCursorRequestBus::Events::GetSystemCursorPositionNormalized); + const auto* position = inputChannel.GetCustomData(); + AZ_Assert(position, "Expected PositionData2D but found nullptr"); return CursorMotionEvent{ScreenPoint( - systemCursorPositionNormalized.GetX() * windowSize.m_width, systemCursorPositionNormalized.GetY() * windowSize.m_height)}; + position->m_normalizedPosition.GetX() * windowSize.m_width, position->m_normalizedPosition.GetY() * windowSize.m_height)}; } else if (inputChannelId == InputDeviceMouse::Movement::Z) { return ScrollEvent{inputChannel.GetValue()}; } - else if ((InputDeviceMouse::IsMouseDevice(inputDeviceId) && wasMouseButton) || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) + else if (wasMouseButton || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) { return DiscreteInputEvent{inputChannelId, inputChannel.GetState()}; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 4c076b887d..dee8bcd600 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -372,6 +372,11 @@ namespace AzFramework return lhs; } + friend TranslationType operator~(const TranslationType lhs) + { + return static_cast(~static_cast>(lhs)); + } + static TranslationType translationFromKey(InputChannelId channelId); TranslationType m_translation = TranslationType::Nil; From 16b16706b5a9e60fc0196f1b63f0fe93f3143266 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 14:50:01 +0100 Subject: [PATCH 030/112] add logic to convert matrix3x3 to euler angles --- .../AzFramework/Viewport/CameraInput.cpp | 42 +++++++++++++++++++ .../AzFramework/Viewport/CameraInput.h | 5 +++ .../Editor/ModernViewportCameraController.cpp | 21 ++-------- 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 069c9d5fc9..46b2e48f81 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -24,6 +24,48 @@ AZ_CVAR( namespace AzFramework { + // Based on paper by David Eberly - https://www.geometrictools.com/Documentation/EulerAngles.pdf + AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation) + { + float x; + float y; + float z; + + // 2.4 Factor as RzRyRx + if (orientation.GetElement(2, 0) < 1.0f) + { + if (orientation.GetElement(2, 0) > -1.0f) + { + x = std::atan2(orientation.GetElement(2, 1), orientation.GetElement(2, 2)); + y = std::asin(-orientation.GetElement(2, 0)); + z = std::atan2(orientation.GetElement(1, 0), orientation.GetElement(0, 0)); + } + else + { + x = 0.0f; + y = AZ::Constants::Pi * 0.5f; + z = -std::atan2(-orientation.GetElement(2, 1), orientation.GetElement(1, 1)); + } + } + else + { + x = 0.0f; + y = -AZ::Constants::Pi * 0.5f; + z = std::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); + } + + return {x, y, z}; + } + + void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform) + { + const auto eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform)); + + camera.m_lookAt = transform.GetTranslation(); + camera.m_pitch = eulerAngles.GetX(); + camera.m_yaw = eulerAngles.GetZ(); + } + bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor_motion = AZStd::get_if(&event)) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index dee8bcd600..daad86ef81 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -43,6 +43,9 @@ namespace AzFramework using ModernViewportCameraControllerRequestBus = AZ::EBus; + // https://www.geometrictools.com/Documentation/EulerAngles.pdf + AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation); + struct Camera { AZ::Vector3 m_lookAt = AZ::Vector3::CreateZero(); //!< Position of camera when m_lookDist is zero, @@ -83,6 +86,8 @@ namespace AzFramework return Transform().GetTranslation(); } + void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform); + struct CursorMotionEvent { ScreenPoint m_position; diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index f94f067a21..06d8ad286d 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -20,8 +20,6 @@ #include #include -AZ_CVAR(bool, ed_newCameraSystemDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable debug drawing for the new camera system"); - namespace SandboxEditor { static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) @@ -68,16 +66,6 @@ namespace SandboxEditor m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); m_cameraSystem.m_cameras.AddCamera(orbitCamera); - if (const auto viewportContext = RetrieveViewportContext(viewportId)) - { - // set position but not orientation - m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); - - // LYN-2315 TODO https://www.geometrictools.com/Documentation/EulerAngles.pdf - - m_camera = m_targetCamera; - } - AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } @@ -111,15 +99,12 @@ namespace SandboxEditor void ModernViewportCameraControllerInstance::DisplayViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - if (ed_newCameraSystemDebug) - { - debugDisplay.SetColor(AZ::Colors::White); - debugDisplay.DrawWireSphere(m_targetCamera.m_lookAt, 0.5f); - } + debugDisplay.SetColor(1.0f, 1.0f, 1.0f, AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f)); + debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) { - m_targetCamera.m_lookAt = transform.GetTranslation(); + AzFramework::UpdateCameraFromTransform(m_targetCamera, transform); } } // namespace SandboxEditor From 9568cdd0f2cafb321b0a1a3bc3cf1407815ba584 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 16:15:55 +0100 Subject: [PATCH 031/112] fix color drawing --- Code/Sandbox/Editor/ModernViewportCameraController.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 06d8ad286d..1334dae20c 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -89,8 +89,7 @@ namespace SandboxEditor if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = - AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); viewportContext->SetCameraTransform(m_camera.Transform()); } @@ -99,8 +98,11 @@ namespace SandboxEditor void ModernViewportCameraControllerInstance::DisplayViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - debugDisplay.SetColor(1.0f, 1.0f, 1.0f, AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f)); - debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); + if (const float alpha = AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f); alpha > AZ::Constants::FloatEpsilon) + { + debugDisplay.SetColor(1.0f, 1.0f, 1.0f, alpha); + debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); + } } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) From 14fc356d6e1d35b319b868e9e500427f9381904a Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 17:23:07 +0100 Subject: [PATCH 032/112] add animation camera behaviour to new controller (WIP) --- .../Editor/ModernViewportCameraController.cpp | 74 ++++++++++++++++++- .../Editor/ModernViewportCameraController.h | 11 +++ 2 files changed, 82 insertions(+), 3 deletions(-) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 1334dae20c..571ae04997 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -22,6 +22,23 @@ namespace SandboxEditor { + static void DrawPreviewAxis( + AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) + { + display.SetColor(AZ::Colors::Red); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); + display.SetColor(AZ::Colors::Green); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); + display.SetColor(AZ::Colors::Blue); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); + } + static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) { auto viewportContextManager = AZ::Interface::Get(); @@ -81,6 +98,28 @@ namespace SandboxEditor AzFramework::WindowSize windowSize; AzFramework::WindowRequestBus::EventResult( windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); + + if (m_cameraMode == CameraMode::Control) + { + if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(event.m_inputChannel.GetInputDevice().GetInputDeviceId())) + { + if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceKeyboard::Key::AlphanumericR) + { + m_transformEnd = m_camera.Transform(); + + return true; + } + else if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceKeyboard::Key::AlphanumericP) + { + m_animationT = 0.0f; + m_cameraMode = CameraMode::Animation; + m_transformStart = m_camera.Transform(); + + return true; + } + } + } + return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); } @@ -88,10 +127,37 @@ namespace SandboxEditor { if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + if (m_cameraMode == CameraMode::Control) + { + m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); - viewportContext->SetCameraTransform(m_camera.Transform()); + viewportContext->SetCameraTransform(m_camera.Transform()); + } + else if (m_cameraMode == CameraMode::Animation) + { + const auto smootherStepFn = [](const float t) { return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; + const float transitionT = smootherStepFn(m_animationT); + + const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( + m_transformStart.GetRotation().Slerp(m_transformEnd.GetRotation(), transitionT), + m_transformStart.GetTranslation().Lerp(m_transformEnd.GetTranslation(), transitionT)); + + const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(current)); + m_camera.m_pitch = eulerAngles.GetX(); + m_camera.m_yaw = eulerAngles.GetZ(); + m_camera.m_lookAt = current.GetTranslation(); + m_targetCamera = m_camera; + + if (m_animationT >= 1.0f) + { + m_cameraMode = CameraMode::Control; + } + + m_animationT = AZ::GetClamp(m_animationT + event.m_deltaTime.count(), 0.0f, 1.0f); + + viewportContext->SetCameraTransform(current); + } } } @@ -103,6 +169,8 @@ namespace SandboxEditor debugDisplay.SetColor(1.0f, 1.0f, 1.0f, alpha); debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); } + + DrawPreviewAxis(debugDisplay, m_transformEnd, 2.0f); } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index a3d4f8cea6..cbdcf5cd22 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -37,10 +37,21 @@ namespace SandboxEditor void SetTargetCameraTransform(const AZ::Transform& transform) override; private: + enum class CameraMode + { + Control, + Animation + }; + AzFramework::Camera m_camera; AzFramework::Camera m_targetCamera; AzFramework::SmoothProps m_smoothProps; AzFramework::CameraSystem m_cameraSystem; + + AZ::Transform m_transformStart; + AZ::Transform m_transformEnd; + float m_animationT = 0.0f; + CameraMode m_cameraMode = CameraMode::Control; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From 36d502b560c0aa95409b796b0bfe95447e7d6a5b Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 13:53:18 +0100 Subject: [PATCH 033/112] update controls for camera and move settings to cfg file --- .../AzFramework/Viewport/CameraInput.cpp | 159 ++++++++++++++---- .../AzFramework/Viewport/CameraInput.h | 90 +++------- Code/Sandbox/Editor/CryEditDoc.cpp | 11 +- Code/Sandbox/Editor/EditorViewportWidget.cpp | 1 + .../Editor/ModernViewportCameraController.cpp | 62 ++++--- .../Editor/ModernViewportCameraController.h | 13 +- 6 files changed, 189 insertions(+), 147 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 46b2e48f81..e9dace3433 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -15,15 +15,104 @@ #include #include #include +#include #include #include -AZ_CVAR( - float, ed_newCameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, - "The default height of the ground plane to do intersection tests against when orbiting"); - namespace AzFramework { + AZ_CVAR( + float, ed_cameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + "The default height of the ground plane to do intersection tests against when orbiting"); + AZ_CVAR(float, ed_cameraSystemBoostMultiplier, 3.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemTranslateSpeed, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemOrbitDollyScrollSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemOrbitDollyCursorSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemScrollTranslateSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemDefaultOrbitDistance, 60.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 100.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemLookSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemTranslateSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemRotateSpeed, 0.005f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemPanSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(bool, ed_cameraSystemPanInvertX, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(bool, ed_cameraSystemPanInvertY, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateBackwardKey, "keyboard_key_alphanumeric_S", nullptr, AZ::ConsoleFunctorFlags::Null, + ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateLeftKey, "keyboard_key_alphanumeric_A", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateRightKey, "keyboard_key_alphanumeric_D", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemTranslateUpKey, "keyboard_key_alphanumeric_E", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateDownKey, "keyboard_key_alphanumeric_Q", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateBoostKey, "keyboard_key_modifier_shift_l", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitKey, "keyboard_key_modifier_alt_l", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemFreeLookButton, "mouse_button_right", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemFreePanButton, "mouse_button_middle", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitLookButton, "mouse_button_left", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitDollyButton, "mouse_button_right", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitPanButton, "mouse_button_middle", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + static InputChannelId CameraTranslateForwardId; + static InputChannelId CameraTranslateBackwardId; + static InputChannelId CameraTranslateLeftId; + static InputChannelId CameraTranslateRightId; + static InputChannelId CameraTranslateDownId; + static InputChannelId CameraTranslateUpId; + static InputChannelId CameraTranslateBoostId; + static InputChannelId CameraOrbitId; + + // externed elsewhere + InputChannelId CameraFreeLookButton; + InputChannelId CameraFreePanButton; + InputChannelId CameraOrbitLookButton; + InputChannelId CameraOrbitDollyButton; + InputChannelId CameraOrbitPanButton; + + void ReloadCameraKeyBindings() + { + const AZ::CVarFixedString& forward = ed_cameraSystemTranslateForwardKey; + CameraTranslateForwardId = InputChannelId(forward.c_str()); + const AZ::CVarFixedString& backward = ed_cameraSystemTranslateBackwardKey; + CameraTranslateBackwardId = InputChannelId(backward.c_str()); + const AZ::CVarFixedString& left = ed_cameraSystemTranslateLeftKey; + CameraTranslateLeftId = InputChannelId(left.c_str()); + const AZ::CVarFixedString& right = ed_cameraSystemTranslateRightKey; + CameraTranslateRightId = InputChannelId(right.c_str()); + const AZ::CVarFixedString& down = ed_cameraSystemTranslateDownKey; + CameraTranslateDownId = InputChannelId(down.c_str()); + const AZ::CVarFixedString& up = ed_cameraSystemTranslateUpKey; + CameraTranslateUpId = InputChannelId(up.c_str()); + const AZ::CVarFixedString& boost = ed_cameraSystemTranslateBoostKey; + CameraTranslateBoostId = InputChannelId(boost.c_str()); + const AZ::CVarFixedString& orbit = ed_cameraSystemOrbitKey; + CameraOrbitId = InputChannelId(orbit.c_str()); + const AZ::CVarFixedString& freeLook = ed_cameraSystemFreeLookButton; + CameraFreeLookButton = InputChannelId(freeLook.c_str()); + const AZ::CVarFixedString& freePan = ed_cameraSystemFreePanButton; + CameraFreePanButton = InputChannelId(freePan.c_str()); + const AZ::CVarFixedString& orbitLook = ed_cameraSystemOrbitLookButton; + CameraOrbitLookButton = InputChannelId(orbitLook.c_str()); + const AZ::CVarFixedString& orbitDolly = ed_cameraSystemOrbitDollyButton; + CameraOrbitDollyButton = InputChannelId(orbitDolly.c_str()); + const AZ::CVarFixedString& orbitPan = ed_cameraSystemOrbitPanButton; + CameraOrbitPanButton = InputChannelId(orbitPan.c_str()); + } + + static void ReloadCameraKeyBindingsConsole(const AZ::ConsoleCommandContainer&) + { + ReloadCameraKeyBindings(); + } + + AZ_CONSOLEFREEFUNC(ReloadCameraKeyBindingsConsole, AZ::ConsoleFunctorFlags::Null, "Reload keybindings for the modern camera system"); + // Based on paper by David Eberly - https://www.geometrictools.com/Documentation/EulerAngles.pdf AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation) { @@ -186,7 +275,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == m_channelId) + if (input->m_channelId == m_rotateChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -206,8 +295,8 @@ namespace AzFramework { Camera nextCamera = targetCamera; - nextCamera.m_pitch -= float(cursorDelta.m_y) * m_props.m_rotateSpeed; - nextCamera.m_yaw -= float(cursorDelta.m_x) * m_props.m_rotateSpeed; + nextCamera.m_pitch -= float(cursorDelta.m_y) * ed_cameraSystemRotateSpeed; + nextCamera.m_yaw -= float(cursorDelta.m_x) * ed_cameraSystemRotateSpeed; const auto clampRotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; @@ -222,7 +311,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceMouse::Button::Middle) + if (input->m_channelId == m_panChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -244,49 +333,48 @@ namespace AzFramework const auto panAxes = m_panAxesFn(nextCamera); - const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * m_props.m_panSpeed; - const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * m_props.m_panSpeed; + const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * ed_cameraSystemPanSpeed; + const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * ed_cameraSystemPanSpeed; const auto inv = [](const bool invert) { constexpr float Dir[] = {1.0f, -1.0f}; return Dir[static_cast(invert)]; }; - nextCamera.m_lookAt += deltaPanX * inv(m_props.m_panInvertX); - nextCamera.m_lookAt += deltaPanY * -inv(m_props.m_panInvertY); + nextCamera.m_lookAt += deltaPanX * inv(ed_cameraSystemPanInvertX); + nextCamera.m_lookAt += deltaPanY * -inv(ed_cameraSystemPanInvertY); return nextCamera; } TranslateCameraInput::TranslationType TranslateCameraInput::translationFromKey(InputChannelId channelId) { - // note: remove hard-coded InputDevice keys - if (channelId == InputDeviceKeyboard::Key::AlphanumericW) + if (channelId == CameraTranslateForwardId) { return TranslationType::Forward; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericS) + if (channelId == CameraTranslateBackwardId) { return TranslationType::Backward; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericA) + if (channelId == CameraTranslateLeftId) { return TranslationType::Left; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericD) + if (channelId == CameraTranslateRightId) { return TranslationType::Right; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericQ) + if (channelId == CameraTranslateDownId) { return TranslationType::Down; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericE) + if (channelId == CameraTranslateUpId) { return TranslationType::Up; } @@ -311,7 +399,7 @@ namespace AzFramework BeginActivation(); } - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierShiftL) + if (input->m_channelId == CameraTranslateBoostId) { m_boost = true; } @@ -323,7 +411,7 @@ namespace AzFramework { EndActivation(); } - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierShiftL) + if (input->m_channelId == CameraTranslateBoostId) { m_boost = false; } @@ -342,8 +430,8 @@ namespace AzFramework const auto axisY = translationBasis.GetBasisY(); const auto axisZ = translationBasis.GetBasisZ(); - const float speed = [boost = m_boost, props = m_props]() { - return props.m_translateSpeed * (boost ? props.m_boostMultiplier : 1.0f); + const float speed = [boost = m_boost]() { + return ed_cameraSystemTranslateSpeed * (boost ? ed_cameraSystemBoostMultiplier : 1.0f); }(); if ((m_translation & TranslationType::Forward) == TranslationType::Forward) @@ -394,7 +482,7 @@ namespace AzFramework { if (const auto* input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierAltL) + if (input->m_channelId == CameraOrbitId) { if (input->m_state == InputChannel::State::Began) { @@ -421,18 +509,17 @@ namespace AzFramework if (Beginning()) { float hit_distance = 0.0f; - if (AZ::Plane::CreateFromNormalAndPoint( - AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_newCameraSystemDefaultPlaneHeight)) + if (AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_cameraSystemDefaultPlaneHeight)) .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY(), hit_distance)) { - hit_distance = AZStd::min(hit_distance, m_props.m_maxOrbitDistance); + hit_distance = AZStd::min(hit_distance, ed_cameraSystemMaxOrbitDistance); nextCamera.m_lookDist = -hit_distance; nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * hit_distance; } else { - nextCamera.m_lookDist = -m_props.m_defaultOrbitDistance; - nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * m_props.m_defaultOrbitDistance; + nextCamera.m_lookDist = -ed_cameraSystemMaxOrbitDistance; + nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * ed_cameraSystemMaxOrbitDistance; } } @@ -465,7 +552,7 @@ namespace AzFramework [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; - nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + scrollDelta * m_props.m_dollySpeed, 0.0f); + nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + scrollDelta * ed_cameraSystemOrbitDollyScrollSpeed, 0.0f); EndActivation(); return nextCamera; } @@ -474,7 +561,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceMouse::Button::Right) + if (input->m_channelId == m_dollyChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -493,7 +580,7 @@ namespace AzFramework [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; - nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + float(cursorDelta.m_y) * m_props.m_dollySpeed, 0.0f); + nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + float(cursorDelta.m_y) * ed_cameraSystemOrbitDollyCursorSpeed, 0.0f); return nextCamera; } @@ -514,14 +601,14 @@ namespace AzFramework const auto translation_basis = LookTranslation(nextCamera); const auto axisY = translation_basis.GetBasisY(); - nextCamera.m_lookAt += axisY * scrollDelta * m_props.m_translateSpeed; + nextCamera.m_lookAt += axisY * scrollDelta * ed_cameraSystemScrollTranslateSpeed; EndActivation(); return nextCamera; } - Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const SmoothProps& props, const float deltaTime) + Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const float deltaTime) { const auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; @@ -542,11 +629,11 @@ namespace AzFramework Camera camera; // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php - const float lookRate = std::exp2(props.m_lookSmoothness); + const float lookRate = std::exp2(ed_cameraSystemLookSmoothness); const float lookT = std::exp2(-lookRate * deltaTime); camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookT); camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookT); - const float moveRate = std::exp2(props.m_moveSmoothness); + const float moveRate = std::exp2(ed_cameraSystemTranslateSmoothness); const float moveT = std::exp2(-moveRate * deltaTime); camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveT); camera.m_lookAt = targetCamera.m_lookAt.Lerp(currentCamera.m_lookAt, moveT); diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index daad86ef81..6ccd7c43eb 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -12,38 +12,20 @@ #pragma once -#include #include #include #include #include #include -#include -#include #include #include namespace AzFramework { - struct WindowSize; + //! Update camera key bindings that can be overridden with AZ console vars (invoke from console to update) + void ReloadCameraKeyBindings(); - // to be moved - class ModernViewportCameraControllerRequests : public AZ::EBusTraits - { - public: - using BusIdType = AzFramework::ViewportId; ///< ViewportId - used to address requests to this EBus. - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - - virtual void SetTargetCameraTransform(const AZ::Transform& transform) = 0; - - protected: - ~ModernViewportCameraControllerRequests() = default; - }; - - using ModernViewportCameraControllerRequestBus = AZ::EBus; - - // https://www.geometrictools.com/Documentation/EulerAngles.pdf + //! Return Euler angles (pitch, roll, yaw) for the incoming orientation. AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation); struct Camera @@ -182,13 +164,7 @@ namespace AzFramework Activation m_activation = Activation::Idle; }; - struct SmoothProps - { - float m_lookSmoothness = 5.0f; - float m_moveSmoothness = 5.0f; - }; - - Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const SmoothProps& props, float deltaTime); + Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, float deltaTime); class Cameras { @@ -220,19 +196,16 @@ namespace AzFramework class RotateCameraInput : public CameraInput { public: - explicit RotateCameraInput(const InputChannelId channelId) - : m_channelId(channelId) + explicit RotateCameraInput(const InputChannelId rotateChannelId) + : m_rotateChannelId(rotateChannelId) { } + void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - InputChannelId m_channelId; - - struct Props - { - float m_rotateSpeed = 0.005f; - } m_props; + private: + InputChannelId m_rotateChannelId; }; struct PanAxes @@ -265,22 +238,17 @@ namespace AzFramework class PanCameraInput : public CameraInput { public: - explicit PanCameraInput(PanAxesFn panAxesFn) + PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) : m_panAxesFn(AZStd::move(panAxesFn)) + , m_panChannelId(panChannelId) { } void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - struct Props - { - float m_panSpeed = 0.01f; - bool m_panInvertX = true; - bool m_panInvertY = true; - } m_props; - private: PanAxesFn m_panAxesFn; + InputChannelId m_panChannelId; }; using TranslationAxesFn = AZStd::function; @@ -321,12 +289,6 @@ namespace AzFramework Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; void ResetImpl() override; - struct Props - { - float m_translateSpeed = 10.0f; - float m_boostMultiplier = 3.0f; - } m_props; - private: enum class TranslationType { @@ -394,23 +356,19 @@ namespace AzFramework public: void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - - struct Props - { - float m_dollySpeed = 0.02f; - } m_props; }; class OrbitDollyCursorMoveCameraInput : public CameraInput { public: + explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) + : m_dollyChannelId(dollyChannelId) {} + void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - struct Props - { - float m_dollySpeed = 0.1f; - } m_props; + private: + InputChannelId m_dollyChannelId; }; class ScrollTranslationCameraInput : public CameraInput @@ -418,11 +376,6 @@ namespace AzFramework public: void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - - struct Props - { - float m_translateSpeed = 0.02f; - } m_props; }; class OrbitCameraInput : public CameraInput @@ -436,13 +389,10 @@ namespace AzFramework } Cameras m_orbitCameras; - - struct Props - { - float m_defaultOrbitDistance = 60.0f; - float m_maxOrbitDistance = 100.0f; - } m_props; }; + struct WindowSize; + + //! Map from a generic InputChannel event to a camera specific InputEvent. InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize); } // namespace AzFramework diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 86491c3e1d..ea40e3c1d6 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -652,21 +652,14 @@ void CCryEditDoc::SerializeViewSettings(CXmlArchive& xmlAr) CViewport* pVP = GetIEditor()->GetViewManager()->GetView(i); - Matrix34 tm = Matrix34::CreateRotationXYZ(va); - tm.SetTranslation(vp); if (pVP) { + Matrix34 tm = Matrix34::CreateRotationXYZ(va); + tm.SetTranslation(vp); pVP->SetViewTM(tm); } - if (auto viewportContext = AZ::Interface::Get()->GetDefaultViewportContext()) - { - AzFramework::ModernViewportCameraControllerRequestBus::Event( - viewportContext->GetId(), &AzFramework::ModernViewportCameraControllerRequestBus::Events::SetTargetCameraTransform, - LYTransformToAZTransform(tm)); - } - // Load grid. auto gridName = QString("Grid%1").arg(useOldViewFormat ? "" : QString::number(i)); XmlNodeRef gridNode = xmlAr.root->newChild(gridName.toUtf8().constData()); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 691d53ba3d..3c42b2db32 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -1234,6 +1234,7 @@ void EditorViewportWidget::SetViewportId(int id) if (ed_useNewCameraSystem) { + AzFramework::ReloadCameraKeyBindings(); m_renderViewport->GetControllerList()->Add(AZStd::make_shared()); } else diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 571ae04997..4725721f0e 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -16,27 +16,31 @@ #include #include #include +#include +#include #include #include #include +namespace AzFramework +{ + extern InputChannelId CameraFreeLookButton; + extern InputChannelId CameraFreePanButton; + extern InputChannelId CameraOrbitLookButton; + extern InputChannelId CameraOrbitDollyButton; + extern InputChannelId CameraOrbitPanButton; +} + namespace SandboxEditor { - static void DrawPreviewAxis( - AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) + static void DrawPreviewAxis(AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) { display.SetColor(AZ::Colors::Red); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); display.SetColor(AZ::Colors::Green); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); display.SetColor(AZ::Colors::Blue); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); } static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) @@ -60,17 +64,21 @@ namespace SandboxEditor : MultiViewportControllerInstanceInterface(viewportId) { // LYN-2315 TODO - move setup out of constructor, pass cameras in - auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Right); - auto firstPersonPanCamera = AZStd::make_shared(AzFramework::LookPan); + auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::CameraFreeLookButton); + auto firstPersonPanCamera = + AZStd::make_shared(AzFramework::CameraFreePanButton, AzFramework::LookPan); auto firstPersonTranslateCamera = AZStd::make_shared(AzFramework::LookTranslation); auto firstPersonWheelCamera = AZStd::make_shared(); auto orbitCamera = AZStd::make_shared(); - auto orbitRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Left); + auto orbitRotateCamera = AZStd::make_shared(AzFramework::CameraOrbitLookButton); auto orbitTranslateCamera = AZStd::make_shared(AzFramework::OrbitTranslation); auto orbitDollyWheelCamera = AZStd::make_shared(); - auto orbitDollyMoveCamera = AZStd::make_shared(); - auto orbitPanCamera = AZStd::make_shared(AzFramework::OrbitPan); + auto orbitDollyMoveCamera = + AZStd::make_shared(AzFramework::CameraOrbitDollyButton); + auto orbitPanCamera = + AZStd::make_shared(AzFramework::CameraOrbitPanButton, AzFramework::OrbitPan); + orbitCamera->m_orbitCameras.AddCamera(orbitRotateCamera); orbitCamera->m_orbitCameras.AddCamera(orbitTranslateCamera); orbitCamera->m_orbitCameras.AddCamera(orbitDollyWheelCamera); @@ -83,13 +91,24 @@ namespace SandboxEditor m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); m_cameraSystem.m_cameras.AddCamera(orbitCamera); + if (auto viewportContext = RetrieveViewportContext(GetViewportId())) + { + auto handleCameraChange = [this](const AZ::Matrix4x4& matrix) { + UpdateCameraFromTransform( + m_targetCamera, + AZ::Transform::CreateFromMatrix3x3AndTranslation(AZ::Matrix3x3::CreateFromMatrix4x4(matrix), matrix.GetTranslation())); + }; + + m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); + + viewportContext->ConnectViewMatrixChangedHandler(m_cameraViewMatrixChangeHandler); + } + AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); - AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } ModernViewportCameraControllerInstance::~ModernViewportCameraControllerInstance() { - AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusDisconnect(); AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect(); } @@ -130,7 +149,7 @@ namespace SandboxEditor if (m_cameraMode == CameraMode::Control) { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, event.m_deltaTime.count()); viewportContext->SetCameraTransform(m_camera.Transform()); } @@ -172,9 +191,4 @@ namespace SandboxEditor DrawPreviewAxis(debugDisplay, m_transformEnd, 2.0f); } - - void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) - { - AzFramework::UpdateCameraFromTransform(m_targetCamera, transform); - } } // namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index cbdcf5cd22..0bc8cea831 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -19,8 +19,7 @@ namespace SandboxEditor { class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface, - private AzFramework::ViewportDebugDisplayEventBus::Handler, - private AzFramework::ModernViewportCameraControllerRequestBus::Handler + private AzFramework::ViewportDebugDisplayEventBus::Handler { public: explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId); @@ -33,9 +32,6 @@ namespace SandboxEditor // AzFramework::ViewportDebugDisplayEventBus overrides ... void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - // ModernViewportCameraControllerRequestBus overrides ... - void SetTargetCameraTransform(const AZ::Transform& transform) override; - private: enum class CameraMode { @@ -45,13 +41,14 @@ namespace SandboxEditor AzFramework::Camera m_camera; AzFramework::Camera m_targetCamera; - AzFramework::SmoothProps m_smoothProps; AzFramework::CameraSystem m_cameraSystem; - AZ::Transform m_transformStart; - AZ::Transform m_transformEnd; + AZ::Transform m_transformStart = AZ::Transform::CreateIdentity(); + AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); float m_animationT = 0.0f; CameraMode m_cameraMode = CameraMode::Control; + + AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From 5df82caef68d104d35455c4b6974405570f747ee Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 09:04:18 -0500 Subject: [PATCH 034/112] [LYN-3464] Vegetation unit tests intermittently failed due to an AssetManager bug. Inside the AssetContainer, if the root asset finished loading during the container initialization, the CheckReady() call at the end of initialization would detect the loaded asset, but would skip sending out notifications because the initialized flag wasn't set yet. This would lead to an extra asset reference remaining in the AssetManager itself, would would then cause errors when the asset handler for that asset got removed. By setting the initialization flag before the CheckReady() call, the notifications get sent correctly, and no extra asset references remain. This checkin also includes a unit test for the AssetManager that specifically forces this condition to happen and validates that it works correctly. --- .../AzCore/AzCore/Asset/AssetContainer.cpp | 7 +- .../Asset/AssetManagerStreamingTests.cpp | 161 +++++++++++++++++- .../AzCore/Tests/Asset/TestAssetTypes.h | 7 + .../DynamicSliceInstanceSpawnerTests.cpp | 6 +- 4 files changed, 176 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp index 4e7a19c197..50c382d7da 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp @@ -239,8 +239,13 @@ namespace AZ return; } - CheckReady(); m_initComplete = true; + + // *After* setting initComplete to true, check to see if the assets are already ready. + // This check needs to wait until after setting initComplete because if they *are* ready, we want the final call to + // RemoveWaitingAsset to trigger the OnAssetContainer* event. If we call CheckReady() *before* setting initComplete, + // if all the assets are ready, the event will never get triggered. + CheckReady(); } bool AssetContainer::IsReady() const diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp index 807288ff82..f5e2a880d5 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp @@ -330,4 +330,163 @@ namespace UnitTest } } -} + // The AssetManagerStreamerImmediateCompletionTests class adjusts the asset loading to force it to complete immediately, + // while still within the callstack for GetAsset(). This can be used to test various conditions in which the load thread + // completes more rapidly than expected, and can expose subtle race conditions. + // There are a few key things that this class does to make this work: + // - The file I/O streamer is mocked + // - The asset stream data is mocked to a 0-byte length for the asset so that the stream load will bypass the I/O streamer and + // just immediately return completion. + // - The number of JobManager threads is set to 0, forcing jobs to execute synchronously inline when they are started. + // With these changes, GetAssetInternal() will queue the stream, which will immediately call the callback that creates LoadAssetJob, + // which immediately executes in-place to process the asset due to the synchronous JobManager. + // Note that if we just created the asset in a Ready state, most of the asset loading code is completely bypassed, and so we + // wouldn't be able to test for race conditions in the AssetContainer. + // + // This class also unregisters the catalog and asset handler before shutting down the asset manager. This is done to catch + // any outstanding asset references that exist due to loads not completing and cleaning up successfully. + struct AssetManagerStreamerImmediateCompletionTests : public BaseAssetManagerTest, + public AZ::Data::AssetCatalogRequestBus::Handler, + public AZ::Data::AssetHandler, + public AZ::Data::AssetCatalog + { + static inline const AZ::Uuid TestAssetId{"{E970B177-5F45-44EB-A2C4-9F29D9A0B2A2}"}; + static inline const char* TestAssetPath{"test"}; + + void SetUp() override + { + BaseAssetManagerTest::SetUp(); + AssetManager::Descriptor desc; + AssetManager::Create(desc); + + // Register the handler and catalog after creation, because we intend to destroy them before AssetManager destruction. + // The specific asset we load is irrelevant, so register EmptyAsset. + AZ::Data::AssetManager::Instance().RegisterHandler(this, AZ::AzTypeInfo::Uuid()); + AZ::Data::AssetManager::Instance().RegisterCatalog(this, AZ::AzTypeInfo::Uuid()); + + // Intercept messages for finding assets by name so that we can mock out the asset we're loading. + AZ::Data::AssetCatalogRequestBus::Handler::BusConnect(); + } + + void TearDown() override + { + // Unregister before destroying AssetManager. + // This will catch any assets that got stuck in a loading state without getting cleaned up. + AZ::Data::AssetManager::Instance().UnregisterCatalog(this); + AZ::Data::AssetManager::Instance().UnregisterHandler(this); + + AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect(); + + AssetManager::Destroy(); + BaseAssetManagerTest::TearDown(); + } + + size_t GetNumJobManagerThreads() const override + { + // Return 0 threads so that the Job Manager executes jobs synchronously inline. This lets us finish a load while still + // in the callstack that initiates the load. + return 0; + } + + // Create a mock streamer instead of a real one, since we don't really want to load an asset. + IO::IStreamer* CreateStreamer() override + { + m_mockStreamer = AZStd::make_unique(); + return &(m_mockStreamer->m_mockStreamer); + } + + void DestroyStreamer([[maybe_unused]] IO::IStreamer* streamer) override + { + m_mockStreamer = nullptr; + } + + // AssetHandler implementation + + // Minimalist mock to create a new EmptyAsset with the desired asset ID. + AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, [[maybe_unused]] const AZ::Data::AssetType& type) override + { + return new EmptyAsset(id); + } + + void DestroyAsset(AZ::Data::AssetPtr ptr) override + { + delete ptr; + } + + // The mocked-out Asset Catalog handles EmptyAsset types. + void GetHandledAssetTypes(AZStd::vector& assetTypes) override + { + assetTypes.push_back(AZ::AzTypeInfo::Uuid()); + } + + // This is a mocked-out load, so just immediately return completion without doing anything. + AZ::Data::AssetHandler::LoadResult LoadAssetData( + [[maybe_unused]] const AZ::Data::Asset& asset, + [[maybe_unused]] AZStd::shared_ptr stream, + [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB) + { + return AZ::Data::AssetHandler::LoadResult::LoadComplete; + } + + // AssetCatalogRequestBus implementation + + // Minimalist mocks to provide our desired asset path or asset id + AZStd::string GetAssetPathById([[maybe_unused]] const AZ::Data::AssetId& id) override + { + return TestAssetPath; + } + AZ::Data::AssetId GetAssetIdByPath( + [[maybe_unused]] const char* path, [[maybe_unused]] const AZ::Data::AssetType& typeToRegister, + [[maybe_unused]] bool autoRegisterIfNotFound) override + { + return TestAssetId; + } + + // Return the mocked-out information for our test asset + AZ::Data::AssetInfo GetAssetInfoById([[maybe_unused]] const AZ::Data::AssetId& id) override + { + AZ::Data::AssetInfo assetInfo; + assetInfo.m_assetId = TestAssetId; + assetInfo.m_assetType = AZ::AzTypeInfo::Uuid(); + assetInfo.m_relativePath = TestAssetPath; + return assetInfo; + } + + // AssetCatalog implementation + + // Set the mocked-out asset load to have a 0-byte length so that the load skips I/O and immediately returns success + AZ::Data::AssetStreamInfo GetStreamInfoForLoad( + [[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override + { + EXPECT_TRUE(type == AZ::AzTypeInfo::Uuid()); + AZ::Data::AssetStreamInfo info; + info.m_dataOffset = 0; + info.m_streamName = TestAssetPath; + info.m_dataLen = 0; + info.m_streamFlags = AZ::IO::OpenMode::ModeRead; + + return info; + } + + AZStd::unique_ptr m_mockStreamer; + }; + + // This test will verify that even if the asset loading stream/job returns immediately, all of the loading + // code works successfully. The test here is fairly simple - it just loads the asset and verifies that it + // loaded successfully. The bulk of the test is really in the setup class above, where the load is forced + // to complete immediately. Also, the true failure condition is caught in the setup class too, which is + // the presence of any assets at the point that the asset handler is unregistered. If they're present, then + // the immediate load wasn't truly successful, as it left around extra references to the asset that haven't + // been cleaned up. + TEST_F(AssetManagerStreamerImmediateCompletionTests, LoadAssetWithImmediateJobCompletion_WorksSuccessfully) + { + AZ::Data::AssetLoadParameters loadParams; + + auto testAsset = + AssetManager::Instance().GetAsset(TestAssetId, AZ::Data::AssetLoadBehavior::Default, loadParams); + + AZ::Data::AssetManager::Instance().DispatchEvents(); + EXPECT_TRUE(testAsset.IsReady()); + } + +} // namespace UnitTest diff --git a/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h b/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h index 83f3909676..d4267972ec 100644 --- a/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h +++ b/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h @@ -24,6 +24,13 @@ namespace UnitTest public: AZ_CLASS_ALLOCATOR(EmptyAsset, AZ::SystemAllocator, 0); AZ_RTTI(EmptyAsset, "{098E3F7F-13AC-414B-9B4E-49B5AD1BD7FE}", AZ::Data::AssetData); + + EmptyAsset( + const AZ::Data::AssetId& assetId = AZ::Data::AssetId(), + AZ::Data::AssetData::AssetStatus status = AZ::Data::AssetData::AssetStatus::NotLoaded) + : AZ::Data::AssetData(assetId, status) + { + } }; // EmptyAssetWithNoHandler: no data contained within, and no AssetHandler registered for this type diff --git a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp index ef2b52f05d..8c922359cf 100644 --- a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp +++ b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp @@ -275,7 +275,7 @@ namespace UnitTest } // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_DifferentSpawnersAreNotEqual) + TEST_F(DynamicSliceInstanceSpawnerTests, DifferentSpawnersAreNotEqual) { // Two spawners with different data should *not* be data-equivalent. @@ -291,7 +291,7 @@ namespace UnitTest // [LY-118267] This test intermittently fails on automated builds, so disabling temporarily until the root cause // can be identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_LoadAndUnloadAssets) + TEST_F(DynamicSliceInstanceSpawnerTests, LoadAndUnloadAssets) { // The spawner should successfully load/unload assets without errors. @@ -312,7 +312,7 @@ namespace UnitTest } // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_CreateAndDestroyInstance) + TEST_F(DynamicSliceInstanceSpawnerTests, CreateAndDestroyInstance) { // The spawner should successfully create and destroy an instance without errors. From 53a6e5ac6becd69d9c76ea63ae5e60b86ae4ad42 Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 10:08:59 -0500 Subject: [PATCH 035/112] Addressed feedback. --- Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp | 4 ++-- .../AzCore/Tests/Asset/AssetManagerStreamingTests.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp index 50c382d7da..2ff6143912 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp @@ -243,8 +243,8 @@ namespace AZ // *After* setting initComplete to true, check to see if the assets are already ready. // This check needs to wait until after setting initComplete because if they *are* ready, we want the final call to - // RemoveWaitingAsset to trigger the OnAssetContainer* event. If we call CheckReady() *before* setting initComplete, - // if all the assets are ready, the event will never get triggered. + // RemoveWaitingAsset to trigger the OnAssetContainerReady/Canceled event. If we call CheckReady() *before* setting + // initComplete, if all the assets are ready, the event will never get triggered. CheckReady(); } diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp index f5e2a880d5..c55a95cf2a 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp @@ -351,7 +351,7 @@ namespace UnitTest public AZ::Data::AssetCatalog { static inline const AZ::Uuid TestAssetId{"{E970B177-5F45-44EB-A2C4-9F29D9A0B2A2}"}; - static inline const char* TestAssetPath{"test"}; + static inline constexpr AZStd::string_view TestAssetPath = "test"; void SetUp() override { From 8686997deff782701801bb6861e9c0ab6fbb2c18 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 16:28:35 +0100 Subject: [PATCH 036/112] add missing include --- Code/Sandbox/Editor/ModernViewportCameraController.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index 0bc8cea831..56345ad0da 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -12,6 +12,7 @@ #pragma once +#include #include #include #include From 6b1f0c53a5193bc6b26a00ffb9058a0318f815c0 Mon Sep 17 00:00:00 2001 From: guthadam Date: Tue, 4 May 2021 10:30:27 -0500 Subject: [PATCH 037/112] Injecting --activateWindow every time new process sends command line Updated comments --- .../Code/Source/MaterialEditorApplication.cpp | 10 ++++++---- .../Source/Material/EditorMaterialSystemComponent.cpp | 3 --- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 3ffe2af1a6..1f32c2a66b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -432,10 +432,16 @@ namespace MaterialEditor // Forward commandline options to other application instance. QByteArray buffer; buffer.append("ProcessCommandLine:"); + + // Add the command line options from this process to the message, skipping the executable path for (int argi = 1; argi < m_argC; ++argi) { buffer.append(QString(m_argV[argi]).append("\n").toUtf8()); } + + // Inject command line option to always bring the main window to the foreground + buffer.append("--activatewindow\n"); + m_socket.Send(buffer); m_socket.Disconnect(); return false; @@ -446,10 +452,6 @@ namespace MaterialEditor // Handle commmand line params from connected socket if (buffer.startsWith("ProcessCommandLine:")) { - // Bring the material editor to the foreground - MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); - // Remove header and parse commands AZStd::string params(buffer.data(), buffer.size()); params = params.substr(strlen("ProcessCommandLine:")); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index 4cf51e2f37..e9a81f2e9f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -128,9 +128,6 @@ namespace AZ QStringList arguments; arguments.append(sourcePath.c_str()); - // Bring the material editor to the foreground if running - arguments.append("--activatewindow"); - // Use the same RHI as the main editor AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); if (!apiName.IsEmpty()) From 61840b5f861cc2e44718478977fdedff7e8d58ec Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 11:04:51 -0500 Subject: [PATCH 038/112] Removed outdated comments. --- .../Code/Tests/DynamicSliceInstanceSpawnerTests.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp index 8c922359cf..c3aa910b47 100644 --- a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp +++ b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp @@ -274,7 +274,6 @@ namespace UnitTest EXPECT_TRUE(instanceSpawner1 == instanceSpawner2); } - // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified TEST_F(DynamicSliceInstanceSpawnerTests, DifferentSpawnersAreNotEqual) { // Two spawners with different data should *not* be data-equivalent. @@ -289,8 +288,6 @@ namespace UnitTest EXPECT_TRUE(!(instanceSpawner1 == instanceSpawner2)); } - // [LY-118267] This test intermittently fails on automated builds, so disabling temporarily until the root cause - // can be identified TEST_F(DynamicSliceInstanceSpawnerTests, LoadAndUnloadAssets) { // The spawner should successfully load/unload assets without errors. @@ -311,7 +308,6 @@ namespace UnitTest Vegetation::DescriptorNotificationBus::Handler::BusDisconnect(); } - // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified TEST_F(DynamicSliceInstanceSpawnerTests, CreateAndDestroyInstance) { // The spawner should successfully create and destroy an instance without errors. From 0f6d57a2670cbb66f62f9492c79979d38e979628 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 4 May 2021 11:24:49 -0500 Subject: [PATCH 039/112] Fixed up a compile issue --- Code/Sandbox/Editor/CryEditDoc.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 04e82d3299..a84f2ea85e 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -62,6 +62,9 @@ #include "StatObjBus.h" // LmbrCentral +#include +#include +#include #include // for LmbrCentral::EditorLightComponentRequestBus From a206896074d29e93901e883805f486cf55b8a360 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 16:13:38 +0100 Subject: [PATCH 040/112] remove QPoint from lower-level interfaces, switch to use AzFramework::ScreenPoint --- .../ViewportInteraction.h | 7 +++-- .../Source/ViewportInteraction.cpp | 10 ++++--- .../Manipulators/EditorVertexSelection.cpp | 7 ++--- .../Manipulators/SurfaceManipulator.cpp | 9 ++---- .../Viewport/ViewportMessages.h | 12 ++++---- .../ViewportSelection/EditorHelpers.cpp | 10 +++---- .../ViewportSelection/EditorSelectionUtil.cpp | 4 +-- .../ViewportSelection/EditorSelectionUtil.h | 2 +- .../EditorTransformComponentSelection.cpp | 8 ++--- Code/Sandbox/Editor/EditorViewportWidget.cpp | 29 +++++++++--------- Code/Sandbox/Editor/EditorViewportWidget.h | 9 +++--- Code/Sandbox/Editor/RenderViewport.cpp | 13 ++++---- Code/Sandbox/Editor/RenderViewport.h | 17 +++++++---- .../Editor/ViewportManipulatorController.cpp | 3 +- .../Viewport/RenderViewportWidget.h | 7 +++-- .../Source/Viewport/RenderViewportWidget.cpp | 30 +++++++++---------- 16 files changed, 91 insertions(+), 86 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h index 56ff2010cd..884562d7e8 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h @@ -38,8 +38,9 @@ namespace AzManipulatorTestFramework void SetGridSize(float size) override; void SetAngularStep(float step) override; int GetViewportId() const override; - AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) override; private: // ViewportInteractionRequestBus ... bool GridSnappingEnabled(); @@ -47,7 +48,7 @@ namespace AzManipulatorTestFramework bool ShowGrid(); bool AngleSnappingEnabled(); float AngleStep(); - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); private: AZStd::unique_ptr m_nullDebugDisplayRequests; const int m_viewportId = 1234; // Arbitrary viewport id for manipulator tests diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index 11f2a32441..4ab36e58f5 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -66,10 +66,10 @@ namespace AzManipulatorTestFramework return m_angularStep; } - QPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) + AzFramework::ScreenPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { auto pos = AzFramework::WorldToScreen(worldPosition, m_cameraState); - return QPoint(pos.m_x, pos.m_y); + return AzFramework::ScreenPoint(pos.m_x, pos.m_y); } void ViewportInteraction::SetCameraState(const AzFramework::CameraState& cameraState) @@ -117,12 +117,14 @@ namespace AzManipulatorTestFramework return m_viewportId; } - AZStd::optional ViewportInteraction::ViewportScreenToWorld([[maybe_unused]]const QPoint& screenPosition, [[maybe_unused]]float depth) + AZStd::optional ViewportInteraction::ViewportScreenToWorld( + [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition, [[maybe_unused]] float depth) { return {}; } - AZStd::optional ViewportInteraction::ViewportScreenToWorldRay([[maybe_unused]]const QPoint& screenPosition) + AZStd::optional ViewportInteraction::ViewportScreenToWorldRay( + [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition) { return {}; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp index 089037bbf3..4d10a4c171 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp @@ -127,8 +127,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates)); + mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); AZ::Transform worldFromLocal; AZ::TransformBus::EventResult(worldFromLocal, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); @@ -402,10 +401,10 @@ namespace AzToolsFramework vertexIndex, localVertex); const AZ::Vector3 worldVertex = worldFromLocal.TransformPoint(AZ::AdaptVertexOut(localVertex)); - const QPoint screenPosition = GetScreenPosition(viewportId, worldVertex); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, worldVertex); // check if a vertex is inside the box select region - if (editorBoxSelect.BoxRegion()->contains(screenPosition)) + if (editorBoxSelect.BoxRegion()->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { // see if vertexIndex is in active selection auto vertexIt = AZStd::find( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp index e4d0cd59dd..f570c20a7e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp @@ -103,8 +103,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); m_startInternal = CalculateManipulationDataStart( worldFromLocalUniformScale, worldSurfacePosition, GetLocalPosition(), @@ -129,8 +128,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); @@ -150,8 +148,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index a9949d382e..6ceb175fe4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -21,8 +21,6 @@ #include #include -class QPoint; // LYN-2315 in-progress, remove this - namespace AzFramework { struct ScreenPoint; @@ -167,14 +165,14 @@ namespace AzToolsFramework /// Return the angle snapping/step size. virtual float AngleStep() = 0; /// Transform a point in world space to screen space coordinates. - virtual QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; + virtual AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; /// Transform a point in screen space coordinates to a vector in world space based on clip space depth. /// Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. /// Returns the world space position if successful. - virtual AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) = 0; + virtual AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) = 0; /// Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. /// Returns a ray containing the ray's origin and a direction normal, if successful. - virtual AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) = 0; + virtual AZStd::optional ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; protected: ~ViewportInteractionRequests() = default; @@ -207,9 +205,9 @@ namespace AzToolsFramework public: /// Given a point in screen space, return the picked entity (if any). /// Picked EntityId will be returned, InvalidEntityId will be returned on failure. - virtual AZ::EntityId PickEntity(const QPoint& point) = 0; + virtual AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) = 0; /// Given a point in screen space, return the terrain position in world space. - virtual AZ::Vector3 PickTerrain(const QPoint& point) = 0; + virtual AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) = 0; /// Return the terrain height given a world position in 2d (xy plane). virtual float TerrainHeight(const AZ::Vector2& position) = 0; /// Given the current view frustum (viewport) return all visible entities. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index f3abc70fba..68a5b43d73 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -141,16 +141,16 @@ namespace AzToolsFramework const AZ::Vector3& entityPosition = m_entityDataCache->GetVisibleEntityPosition(entityCacheIndex); // selecting based on 2d icon - should only do it when visible and not selected - const QPoint screenPosition = GetScreenPosition(viewportId, entityPosition); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, entityPosition); const float distSqFromCamera = cameraState.m_position.GetDistanceSq(entityPosition); const auto iconRange = static_cast(GetIconScale(distSqFromCamera) * s_iconSize * 0.5f); const auto screenCoords = mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates; - if ( screenCoords.m_x >= screenPosition.x() - iconRange - && screenCoords.m_x <= screenPosition.x() + iconRange - && screenCoords.m_y >= screenPosition.y() - iconRange - && screenCoords.m_y <= screenPosition.y() + iconRange) + if ( screenCoords.m_x >= screenPosition.m_x - iconRange + && screenCoords.m_x <= screenPosition.m_x + iconRange + && screenCoords.m_y >= screenPosition.m_y - iconRange + && screenCoords.m_y <= screenPosition.m_y + iconRange) { entityIdUnderCursor = entityId; break; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index 95095bd3c8..3be4bc9db2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -53,11 +53,11 @@ namespace AzToolsFramework return AZ::GetMax(projectedCameraDistance, cameraState.m_nearClip) / apparentDistance; } - QPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) + AzFramework::ScreenPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - QPoint screenPosition = QPoint(); + auto screenPosition = AzFramework::ScreenPoint(0, 0); ViewportInteraction::ViewportInteractionRequestBus::EventResult( screenPosition, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::ViewportWorldToScreen, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h index 65e0a99bfe..9936fb9afd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h @@ -45,7 +45,7 @@ namespace AzToolsFramework const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState); /// Map from world space to screen space. - QPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); + AzFramework::ScreenPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); /// Given a mouse interaction, determine if the pick ray from its position /// in screen space intersected an aabb in world space. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index ec22a2f7c8..9388f3f5f0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -316,14 +316,14 @@ namespace AzToolsFramework template static void BoxSelectAddRemoveToEntitySelection( - const AZStd::optional& boxSelect, const QPoint& screenPosition, const AZ::EntityId visibleEntityId, + const AZStd::optional& boxSelect, const AzFramework::ScreenPoint& screenPosition, const AZ::EntityId visibleEntityId, const EntityIdContainer& incomingEntityIds, EntityIdContainer& outgoingEntityIds, EditorTransformComponentSelection& entityTransformComponentSelection, EntitySelectFuncType selectFunc1, EntitySelectFuncType selectFunc2, Compare outgoingCheck) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - if (boxSelect->contains(screenPosition)) + if (boxSelect->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { const auto entityIt = incomingEntityIds.find(visibleEntityId); @@ -389,7 +389,7 @@ namespace AzToolsFramework const AZ::EntityId entityId = entityDataCache.GetVisibleEntityId(entityCacheIndex); const AZ::Vector3& entityPosition = entityDataCache.GetVisibleEntityPosition(entityCacheIndex); - const QPoint screenPosition = GetScreenPosition(viewportId, entityPosition); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, entityPosition); if (currentKeyboardModifiers.Ctrl()) { @@ -927,7 +927,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint(mouseInteraction.m_mousePick.m_screenCoordinates)); + mouseInteraction.m_mousePick.m_screenCoordinates); // convert to local space - snap if enabled const GridSnapParameters gridSnapParams = GridSnapSettings(viewportId); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 3c42b2db32..29b37e7d92 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -321,8 +321,8 @@ AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMous using namespace AzToolsFramework::ViewportInteraction; MousePick mousePick; - mousePick.m_screenCoordinates = AzFramework::ScreenPoint(point.x(), point.y()); - const auto& ray = m_renderViewport->ViewportScreenToWorldRay(point); + mousePick.m_screenCoordinates = ScreenPointFromQPoint(point); + const auto& ray = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); if (ray.has_value()) { mousePick.m_rayOrigin = ray.value().origin; @@ -1132,14 +1132,14 @@ float EditorViewportWidget::AngleStep() return GetViewManager()->GetGrid()->GetAngleSnap(); } -AZ::Vector3 EditorViewportWidget::PickTerrain(const QPoint& point) +AZ::Vector3 EditorViewportWidget::PickTerrain(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - return LYVec3ToAZVec3(ViewToWorld(point, nullptr, true)); + return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); } -AZ::EntityId EditorViewportWidget::PickEntity(const QPoint& point) +AZ::EntityId EditorViewportWidget::PickEntity(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); @@ -1148,7 +1148,7 @@ AZ::EntityId EditorViewportWidget::PickEntity(const QPoint& point) AZ::EntityId entityId; HitContext hitInfo; hitInfo.view = this; - if (HitTest(point, hitInfo)) + if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) { if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) { @@ -1174,7 +1174,7 @@ void EditorViewportWidget::FindVisibleEntities(AZStd::vector& visi visibleEntitiesOut.assign(m_entityVisibilityQuery.Begin(), m_entityVisibilityQuery.End()); } -QPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) +AzFramework::ScreenPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { return m_renderViewport->ViewportWorldToScreen(worldPosition); } @@ -2002,7 +2002,7 @@ Vec3 EditorViewportWidget::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nF ////////////////////////////////////////////////////////////////////////// QPoint EditorViewportWidget::WorldToView(const Vec3& wp) const { - return m_renderViewport->ViewportWorldToScreen(LYVec3ToAZVec3(wp)); + return AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(m_renderViewport->ViewportWorldToScreen(LYVec3ToAZVec3(wp))); } ////////////////////////////////////////////////////////////////////////// QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width, int height) const @@ -2024,7 +2024,8 @@ QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width } ////////////////////////////////////////////////////////////////////////// -Vec3 EditorViewportWidget::ViewToWorld(const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const +Vec3 EditorViewportWidget::ViewToWorld( + const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); @@ -2035,7 +2036,7 @@ Vec3 EditorViewportWidget::ViewToWorld(const QPoint& vp, bool* collideWithTerrai AZ_UNUSED(bSkipVegetation) AZ_UNUSED(collideWithObject) - auto ray = m_renderViewport->ViewportScreenToWorldRay(vp); + auto ray = m_renderViewport->ViewportScreenToWorldRay(AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(vp)); if (!ray.has_value()) { return Vec3(0, 0, 0); @@ -2152,7 +2153,7 @@ bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, c void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const { AZ::Vector3 wp; - wp = m_renderViewport->ViewportScreenToWorld({(int)sx, m_rcClient.bottom() - ((int)sy)}, sz).value_or(wp); + wp = m_renderViewport->ViewportScreenToWorld(AzFramework::ScreenPoint{(int)sx, m_rcClient.bottom() - ((int)sy)}, sz).value_or(wp); *px = wp.GetX(); *py = wp.GetY(); *pz = wp.GetZ(); @@ -2160,9 +2161,9 @@ void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, flo void EditorViewportWidget::ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const { - QPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); - *sx = screenPosition.x(); - *sy = screenPosition.y(); + AzFramework::ScreenPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); + *sx = screenPosition.m_x; + *sy = screenPosition.m_y; *sz = 0.f; } diff --git a/Code/Sandbox/Editor/EditorViewportWidget.h b/Code/Sandbox/Editor/EditorViewportWidget.h index 472f7e3c62..8673d258cc 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.h +++ b/Code/Sandbox/Editor/EditorViewportWidget.h @@ -196,15 +196,15 @@ public: bool ShowGrid(); bool AngleSnappingEnabled(); float AngleStep(); - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; void FreezeViewportInput(bool freeze) override; // AzToolsFramework::MainEditorViewportInteractionRequestBus - AZ::EntityId PickEntity(const QPoint& point) override; - AZ::Vector3 PickTerrain(const QPoint& point) override; + AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; + AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; void FindVisibleEntities(AZStd::vector& visibleEntitiesOut) override; bool ShowingWorldSpace() override; @@ -557,8 +557,7 @@ private: void PushDisableRendering(); void PopDisableRendering(); bool IsRenderingDisabled() const; - AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal( - const QPoint& point) const; + AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal(const QPoint& point) const; void RestoreViewportAfterGameMode(); void UpdateCameraFromViewportContext(); diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..08eda98cf6 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -2043,14 +2043,14 @@ float CRenderViewport::AngleStep() return GetViewManager()->GetGrid()->GetAngleSnap(); } -AZ::Vector3 CRenderViewport::PickTerrain(const QPoint& point) +AZ::Vector3 CRenderViewport::PickTerrain(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - return LYVec3ToAZVec3(ViewToWorld(point, nullptr, true)); + return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); } -AZ::EntityId CRenderViewport::PickEntity(const QPoint& point) +AZ::EntityId CRenderViewport::PickEntity(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); @@ -2059,7 +2059,7 @@ AZ::EntityId CRenderViewport::PickEntity(const QPoint& point) AZ::EntityId entityId; HitContext hitInfo; hitInfo.view = this; - if (HitTest(point, hitInfo)) + if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) { if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) { @@ -2100,12 +2100,13 @@ void CRenderViewport::FindVisibleEntities(AZStd::vector& visibleEn } } -QPoint CRenderViewport::ViewportWorldToScreen(const AZ::Vector3& worldPosition) +AzFramework::ScreenPoint CRenderViewport::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); PreWidgetRendering(); - const QPoint screenPosition = WorldToView(AZVec3ToLYVec3(worldPosition)); + const AzFramework::ScreenPoint screenPosition = + AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(WorldToView(AZVec3ToLYVec3(worldPosition))); PostWidgetRendering(); return screenPosition; diff --git a/Code/Sandbox/Editor/RenderViewport.h b/Code/Sandbox/Editor/RenderViewport.h index 2edbd86770..9985408d25 100644 --- a/Code/Sandbox/Editor/RenderViewport.h +++ b/Code/Sandbox/Editor/RenderViewport.h @@ -190,17 +190,24 @@ public: bool ShowGrid() override; bool AngleSnappingEnabled() override; float AngleStep() override; - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const QPoint&, float) override { return {}; } - AZStd::optional ViewportScreenToWorldRay(const QPoint&) override { return {}; } + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint&, float) override + { + return {}; + } + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint&) override + { + return {}; + } // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; void FreezeViewportInput(bool freeze) override; // AzToolsFramework::MainEditorViewportInteractionRequestBus - AZ::EntityId PickEntity(const QPoint& point) override; - AZ::Vector3 PickTerrain(const QPoint& point) override; + AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; + AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; void FindVisibleEntities(AZStd::vector& visibleEntitiesOut) override; bool ShowingWorldSpace() override; diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index fc376b27d0..43d2fb1f2c 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -112,8 +112,7 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram m_state.m_mousePick.m_screenCoordinates = screenPosition; AZStd::optional ray; ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, - QPoint(screenPosition.m_x, screenPosition.m_y)); + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); if (ray.has_value()) { 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 5dbbf04f1b..8e64c1467e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -94,9 +94,10 @@ namespace AtomToolsFramework bool ShowGrid() override; bool AngleSnappingEnabled() override; float AngleStep() override; - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) override; + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) override; // AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler ... void BeginCursorCapture() override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 483b4bc55b..5f3c553601 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -407,44 +407,43 @@ namespace AtomToolsFramework return 0.0f; } - QPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) + AzFramework::ScreenPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); - if (currentView == nullptr) + if (AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); + currentView == nullptr) { - return QPoint(); + return AzFramework::ScreenPoint(0, 0); } - AzFramework::ScreenPoint position = AzFramework::WorldToScreen( - worldPosition, - GetCameraState() - ); - return {position.m_x, position.m_y}; + + return AzFramework::WorldToScreen(worldPosition, GetCameraState()); } - AZStd::optional RenderViewportWidget::ViewportScreenToWorld(const QPoint& screenPosition, float depth) + AZStd::optional RenderViewportWidget::ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) { const auto& cameraProjection = m_viewportContext->GetCameraProjectionMatrix(); const auto& cameraView = m_viewportContext->GetCameraViewMatrix(); const AZ::Vector4 normalizedScreenPosition { - screenPosition.x() * 2.f / width() - 1.0f, - (height() - screenPosition.y()) * 2.f / height() - 1.0f, + screenPosition.m_x * 2.f / width() - 1.0f, + (height() - screenPosition.m_y) * 2.f / height() - 1.0f, 1.f - depth, // [GFX TODO] [ATOM-1501] Currently we always assume reverse depth 1.f }; + AZ::Matrix4x4 worldFromScreen = cameraProjection * cameraView; worldFromScreen.InvertFull(); - AZ::Vector4 projectedPosition = worldFromScreen * normalizedScreenPosition; - if (projectedPosition.GetW() == 0.f) + const AZ::Vector4 projectedPosition = worldFromScreen * normalizedScreenPosition; + if (projectedPosition.GetW() == 0.0f) { return {}; } + return projectedPosition.GetAsVector3() / projectedPosition.GetW(); } AZStd::optional RenderViewportWidget::ViewportScreenToWorldRay( - const QPoint& screenPosition) + const AzFramework::ScreenPoint& screenPosition) { auto pos0 = ViewportScreenToWorld(screenPosition, 0.f); auto pos1 = ViewportScreenToWorld(screenPosition, 1.f); @@ -457,6 +456,7 @@ namespace AtomToolsFramework AZ::Vector3 rayOrigin = pos0.value(); AZ::Vector3 rayDirection = pos1.value() - pos0.value(); rayDirection.Normalize(); + return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{rayOrigin, rayDirection}; } From 1474b56e12134f433d2a129d11fa9cb95254b1d0 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Tue, 4 May 2021 09:55:07 -0700 Subject: [PATCH 041/112] Deployment postprocessing should be enabled only for release builds --- cmake/Platform/iOS/LYWrappers_ios.cmake | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmake/Platform/iOS/LYWrappers_ios.cmake b/cmake/Platform/iOS/LYWrappers_ios.cmake index 53783e5c0a..97b7c70d35 100644 --- a/cmake/Platform/iOS/LYWrappers_ios.cmake +++ b/cmake/Platform/iOS/LYWrappers_ios.cmake @@ -16,7 +16,9 @@ function(ly_apply_platform_properties target) set_target_properties(${target} PROPERTIES - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING "YES" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES" ) if(${target_type} STREQUAL "SHARED_LIBRARY") From bb76bccc06249d2bb9db6863335d0ffdc81f1f73 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 17:55:09 +0100 Subject: [PATCH 042/112] remove unneeded temporary --- .../AzManipulatorTestFramework/Source/ViewportInteraction.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index 4ab36e58f5..ebef9dea30 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -68,8 +68,7 @@ namespace AzManipulatorTestFramework AzFramework::ScreenPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - auto pos = AzFramework::WorldToScreen(worldPosition, m_cameraState); - return AzFramework::ScreenPoint(pos.m_x, pos.m_y); + return AzFramework::WorldToScreen(worldPosition, m_cameraState); } void ViewportInteraction::SetCameraState(const AzFramework::CameraState& cameraState) From 524652ee177e1f241f988fb98fcb8f4a3da0e604 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 4 May 2021 18:01:34 +0100 Subject: [PATCH 043/112] fixed C18243589_Joints_BallSoftLimitsConstrained test failure --- ...243589_Joints_BallSoftLimitsConstrained.py | 35 ++++++++++++++++--- .../Gem/PythonTests/physics/JointsHelper.py | 7 ++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py index e038b33043..b7bc8439e4 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py @@ -57,6 +57,7 @@ def C18243589_Joints_BallSoftLimitsConstrained(): """ import os import sys + import math import ImportPathHelper as imports @@ -95,13 +96,38 @@ def C18243589_Joints_BallSoftLimitsConstrained(): Report.info_vector3(follower.position, "follower initial position:") leadInitialPosition = lead.position followerInitialPosition = follower.position + + followerMovedAboveJoint = False + #calculate the start vector from follower and lead positions + normalizedStartPos = JointsHelper.getRelativeVector(lead.position, follower.position) + normalizedStartPos = normalizedStartPos.GetNormalizedSafe() + #the targeted angle to reach between the initial vector and the current follower-lead vector + targetAngleDeg = 45 + targetAngle = math.radians(targetAngleDeg) - # 4) Wait for several seconds - general.idle_wait(1.0) # wait for lead and follower to move + maxTotalWaitTime = 2.0 #seconds + waitTime = 0.0 + waitStep = 0.2 + angleAchieved = 0.0 + while waitTime < maxTotalWaitTime: + waitTime = waitTime + waitStep + general.idle_wait(waitStep) # wait for lead and follower to move + + #calculate the current follower-lead vector + normalVec = JointsHelper.getRelativeVector(lead.position, follower.position) + normalVec = normalVec.GetNormalizedSafe() + #dot product + acos to get the angle + angleAchieved = math.acos(normalizedStartPos.Dot(normalVec)) + #is it above target? + if angleAchieved > targetAngle: + followerMovedAboveJoint = True + break # 5) Check to see if lead and follower behaved as expected - Report.info_vector3(lead.position, "lead position after 1 second:") - Report.info_vector3(follower.position, "follower position after 1 second:") + Report.info_vector3(lead.position, "lead position after {:.2f} second:".format(waitTime)) + Report.info_vector3(follower.position, "follower position after {:.2f} second:".format(waitTime)) + angleAchievedDeg = math.degrees(angleAchieved) + Report.info("Angle achieved {:.2f} Target {:.2f}".format(angleAchievedDeg, targetAngleDeg)) leadPositionDelta = lead.position.Subtract(leadInitialPosition) leadRemainedStill = JointsHelper.vector3SmallerThanScalar(leadPositionDelta, FLOAT_EPSILON) @@ -111,7 +137,6 @@ def C18243589_Joints_BallSoftLimitsConstrained(): followerMovedinXYZ = JointsHelper.vector3LargerThanScalar(followerPositionDelta, FLOAT_EPSILON) Report.critical_result(Tests.check_follower_position, followerMovedinXYZ) - followerMovedAboveJoint = follower.position.z > (followerInitialPosition.z + 2.5) # (followerInitialPosition.z + 2.5) is the z position past the 45 degree limit. This is to show that the follower swinged past the 45 degree cone limit, above the joint position. Report.critical_result(Tests.check_follower_above_joint, followerMovedAboveJoint) # 6) Exit Game Mode diff --git a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py index e61118ef5b..476c1df237 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py +++ b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py @@ -27,6 +27,13 @@ def vector3LargerThanScalar(vec3Value, scalarValue): vec3Value.y > scalarValue and vec3Value.z > scalarValue) +def getRelativeVector(vecA, vecB): + relativeVec = vecA + relativeVec.x = relativeVec.x - vecB.x + relativeVec.y = relativeVec.y - vecB.y + relativeVec.z = relativeVec.z - vecB.z + return relativeVec + # Entity class for joints tests class JointEntity: From b99d0fb36ad590cf27f1d4794bec3c13b4c46b93 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Tue, 4 May 2021 10:20:51 -0700 Subject: [PATCH 044/112] Move symbol stripping attributes to iOS configuration file --- cmake/Platform/iOS/Configurations_ios.cmake | 5 +++++ cmake/Platform/iOS/LYWrappers_ios.cmake | 7 ------- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/cmake/Platform/iOS/Configurations_ios.cmake b/cmake/Platform/iOS/Configurations_ios.cmake index aa935c853f..6522c6a098 100644 --- a/cmake/Platform/iOS/Configurations_ios.cmake +++ b/cmake/Platform/iOS/Configurations_ios.cmake @@ -41,6 +41,11 @@ endif() # Signing ly_set(CMAKE_XCODE_ATTRIBUTE_OTHER_CODE_SIGN_FLAGS --deep) +# Symbol Stripping +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO") +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO") +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES") + # Generate scheme files for Xcode ly_set(CMAKE_XCODE_GENERATE_SCHEME TRUE) diff --git a/cmake/Platform/iOS/LYWrappers_ios.cmake b/cmake/Platform/iOS/LYWrappers_ios.cmake index 97b7c70d35..8da421ad5c 100644 --- a/cmake/Platform/iOS/LYWrappers_ios.cmake +++ b/cmake/Platform/iOS/LYWrappers_ios.cmake @@ -14,13 +14,6 @@ include(cmake/Platform/Common/LYWrappers_default.cmake) function(ly_apply_platform_properties target) get_target_property(target_type ${target} TYPE) - set_target_properties(${target} - PROPERTIES - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO" - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO" - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES" - ) - if(${target_type} STREQUAL "SHARED_LIBRARY") # Some projects use an "_" in their target name which is not allowed in a bundle identifier get_target_property(target_name ${target} NAME) From 8b1251c9f79d5b7f52781f78c339a13e96f11c8d Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Tue, 4 May 2021 12:55:47 -0500 Subject: [PATCH 045/112] {LYN-2185} Helios - Added GraphObjectProxy::GetMethodList() function (#392) * {LYN-2185} Helios - Added GraphObjectProxy::GetMethodList() function * Updated the EditorPythonConsoleInterface to get Python type name info * Added PythonBehaviorInfo to the GraphObjectProxy object to reflect abstract calls that can be invoked * removed SCENE_DATA_API from Reflect() function Jira: https://jira.agscollab.com/browse/LYN-2185 Tests: Added tests GraphObjectProxy_GetClassInfo_Loads & GraphObjectProxy_GetClassInfo_CorrectFormats to regress test * fix compile error * etchPythonTypeName() returns AZStd::string * put None into a const char --- .../API/EditorPythonConsoleBus.h | 8 + .../SceneCore/Containers/GraphObjectProxy.cpp | 141 ++++++++++++++++++ .../SceneCore/Containers/GraphObjectProxy.h | 6 + .../Tests/Containers/SceneBehaviorTests.cpp | 62 ++++++++ .../SceneData/GraphData/BlendShapeData.h | 2 +- .../Code/Source/PythonLogSymbolsComponent.cpp | 10 +- .../Code/Source/PythonLogSymbolsComponent.h | 2 +- .../Tests/PythonLogSymbolsComponentTests.cpp | 4 +- 8 files changed, 226 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h index 4f5a349518..de4ff396b2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h @@ -13,6 +13,12 @@ #include #include +#include + +namespace AZ +{ + struct BehaviorParameter; +} namespace AzToolsFramework { @@ -40,6 +46,8 @@ namespace AzToolsFramework }; using GlobalFunctionCollection = AZStd::vector; virtual void GetGlobalFunctionList(GlobalFunctionCollection& globalFunctionCollection) const = 0; + + virtual AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) = 0; }; //! Interface to signal the phases for the Python virtual machine diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp index f2fda63ec4..989eccd526 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp @@ -13,9 +13,135 @@ #include #include #include +#include +#include +#include namespace AZ { + namespace Python + { + static const char* const None = "None"; + + class PythonBehaviorInfo final + { + public: + AZ_RTTI(PythonBehaviorInfo, "{8055BD03-5B3B-490D-AEC5-1B1E2616D529}"); + AZ_CLASS_ALLOCATOR(PythonBehaviorInfo, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + PythonBehaviorInfo(const AZ::BehaviorClass* behaviorClass); + PythonBehaviorInfo() = delete; + + protected: + bool IsMemberLike(const AZ::BehaviorMethod& method, const AZ::TypeId& typeId) const; + AZStd::string FetchPythonType(const AZ::BehaviorParameter& param) const; + void WriteMethod(AZStd::string_view methodName, const AZ::BehaviorMethod& behaviorMethod); + + private: + const AZ::BehaviorClass* m_behaviorClass = nullptr; + AZStd::vector m_methodList; + }; + + PythonBehaviorInfo::PythonBehaviorInfo(const AZ::BehaviorClass* behaviorClass) + : m_behaviorClass(behaviorClass) + { + AZ_Assert(m_behaviorClass, "PythonBehaviorInfo requires a valid behaviorClass pointer"); + for (const auto& entry : behaviorClass->m_methods) + { + WriteMethod(entry.first, *entry.second); + } + } + + void PythonBehaviorInfo::Reflect(AZ::ReflectContext* context) + { + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->Class() + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Module, "scene.graph") + ->Property("className", [](const PythonBehaviorInfo& self) + { return self.m_behaviorClass->m_name; }, nullptr) + ->Property("classUuid", [](const PythonBehaviorInfo& self) + { return self.m_behaviorClass->m_typeId.ToString(); }, nullptr) + ->Property("methodList", BehaviorValueGetter(&PythonBehaviorInfo::m_methodList), nullptr); + } + } + + bool PythonBehaviorInfo::IsMemberLike(const AZ::BehaviorMethod& method, const AZ::TypeId& typeId) const + { + return method.IsMember() || (method.GetNumArguments() > 0 && method.GetArgument(0)->m_typeId == typeId); + } + + AZStd::string PythonBehaviorInfo::FetchPythonType(const AZ::BehaviorParameter& param) const + { + using namespace AzToolsFramework; + EditorPythonConsoleInterface* editorPythonConsoleInterface = AZ::Interface::Get(); + if (editorPythonConsoleInterface) + { + return editorPythonConsoleInterface->FetchPythonTypeName(param); + } + return None; + } + + void PythonBehaviorInfo::WriteMethod(AZStd::string_view methodName, const AZ::BehaviorMethod& behaviorMethod) + { + // if the method is a static method then it is not a part of the abstract class + const bool isMemberLike = IsMemberLike(behaviorMethod, m_behaviorClass->m_typeId); + if (isMemberLike == false) + { + return; + } + + AZStd::string buffer; + AZStd::vector pythonArgs; + + AzFramework::StringFunc::Append(buffer, "def "); + AzFramework::StringFunc::Append(buffer, methodName.data()); + AzFramework::StringFunc::Append(buffer, "("); + + pythonArgs.emplace_back("self"); + + AZStd::string bufferArg; + for (size_t argIndex = 1; argIndex < behaviorMethod.GetNumArguments(); ++argIndex) + { + const AZStd::string* name = behaviorMethod.GetArgumentName(argIndex); + if (!name || name->empty()) + { + bufferArg = AZStd::string::format(" arg%zu", argIndex); + } + else + { + bufferArg = *name; + } + + AZStd::string_view type = FetchPythonType(*behaviorMethod.GetArgument(argIndex)); + if (!type.empty()) + { + AzFramework::StringFunc::Append(bufferArg, ": "); + AzFramework::StringFunc::Append(bufferArg, type.data()); + } + + pythonArgs.push_back(bufferArg); + bufferArg.clear(); + } + + AZStd::string resultValue{ None }; + if (behaviorMethod.HasResult() && behaviorMethod.GetResult()) + { + resultValue = FetchPythonType(*behaviorMethod.GetResult()); + } + + AZStd::string argsList; + AzFramework::StringFunc::Join(buffer, pythonArgs.begin(), pythonArgs.end(), ","); + AzFramework::StringFunc::Append(buffer, ") -> "); + AzFramework::StringFunc::Append(buffer, resultValue.c_str()); + m_methodList.emplace_back(buffer); + } + } + namespace SceneAPI { namespace Containers @@ -25,6 +151,8 @@ namespace AZ AZ::BehaviorContext* behaviorContext = azrtti_cast(context); if (behaviorContext) { + Python::PythonBehaviorInfo::Reflect(context); + behaviorContext->Class(); behaviorContext->Class() @@ -33,6 +161,19 @@ namespace AZ ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) ->Method("CastWithTypeName", &GraphObjectProxy::CastWithTypeName) ->Method("Invoke", &GraphObjectProxy::Invoke) + ->Method("GetClassInfo", [](GraphObjectProxy& self) -> Python::PythonBehaviorInfo* + { + if (self.m_pythonBehaviorInfo) + { + return self.m_pythonBehaviorInfo.get(); + } + if (self.m_behaviorClass) + { + self.m_pythonBehaviorInfo = AZStd::make_shared(self.m_behaviorClass); + return self.m_pythonBehaviorInfo.get(); + } + return nullptr; + }) ; } } diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h index 094b896364..d83a147e5f 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h +++ b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h @@ -16,6 +16,11 @@ namespace AZ { + namespace Python + { + class PythonBehaviorInfo; + } + namespace SceneAPI { namespace Containers @@ -44,6 +49,7 @@ namespace AZ private: AZStd::shared_ptr m_graphObject; const AZ::BehaviorClass* m_behaviorClass = nullptr; + AZStd::shared_ptr m_pythonBehaviorInfo; }; } // Containers diff --git a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp index cb23e73b0e..8d7fb63baf 100644 --- a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -378,6 +379,25 @@ namespace AZ MOCK_CONST_METHOD1(QueryApplicationType, void(AZ::ApplicationTypeQuery&)); }; + class MockEditorPythonConsoleInterface final + : public AzToolsFramework::EditorPythonConsoleInterface + { + public: + MockEditorPythonConsoleInterface() + { + AZ::Interface::Register(this); + } + + ~MockEditorPythonConsoleInterface() + { + AZ::Interface::Unregister(this); + } + + MOCK_CONST_METHOD1(GetModuleList, void(AZStd::vector&)); + MOCK_CONST_METHOD1(GetGlobalFunctionList, void(GlobalFunctionCollection&)); + MOCK_METHOD1(FetchPythonTypeName, AZStd::string(const AZ::BehaviorParameter&)); + }; + // // SceneGraphBehaviorScriptTest // @@ -386,6 +406,7 @@ namespace AZ { public: AZStd::unique_ptr m_componentApplication; + AZStd::unique_ptr m_editorPythonConsoleInterface; AZStd::unique_ptr m_scriptContext; AZStd::unique_ptr m_behaviorContext; AZStd::unique_ptr m_serializeContext; @@ -454,6 +475,15 @@ namespace AZ { return this->m_serializeContext.get(); })); + + m_editorPythonConsoleInterface = AZStd::make_unique(); + } + + void SetupEditorPythonConsoleInterface() + { + EXPECT_CALL(*m_editorPythonConsoleInterface, FetchPythonTypeName(::testing::_)) + .Times(4) + .WillRepeatedly(::testing::Invoke([](const AZ::BehaviorParameter&) {return "int"; })); } void TearDown() override @@ -562,6 +592,38 @@ namespace AZ ExpectExecute("TestExpectEquals(value, 17)"); } + TEST_F(SceneGraphBehaviorScriptTest, GraphObjectProxy_GetClassInfo_Loads) + { + SetupEditorPythonConsoleInterface(); + + ExpectExecute("builder = MockBuilder()"); + ExpectExecute("builder:BuildSceneGraph()"); + ExpectExecute("scene = builder:GetScene()"); + ExpectExecute("nodeG = scene.graph:FindWithPath('A.C.E.G')"); + ExpectExecute("proxy = scene.graph:GetNodeContent(nodeG)"); + ExpectExecute("TestExpectTrue(proxy:CastWithTypeName('MockIGraphObject'))"); + ExpectExecute("info = proxy:GetClassInfo()"); + ExpectExecute("TestExpectTrue(info ~= nil)"); + } + + TEST_F(SceneGraphBehaviorScriptTest, GraphObjectProxy_GetClassInfo_CorrectFormats) + { + SetupEditorPythonConsoleInterface(); + + ExpectExecute("builder = MockBuilder()"); + ExpectExecute("builder:BuildSceneGraph()"); + ExpectExecute("scene = builder:GetScene()"); + ExpectExecute("nodeG = scene.graph:FindWithPath('A.C.E.G')"); + ExpectExecute("proxy = scene.graph:GetNodeContent(nodeG)"); + ExpectExecute("TestExpectTrue(proxy:CastWithTypeName('MockIGraphObject'))"); + ExpectExecute("info = proxy:GetClassInfo()"); + ExpectExecute("TestExpectTrue(info.className == 'MockIGraphObject')"); + ExpectExecute("TestExpectTrue(info.classUuid == '{66A082CC-851D-4E1F-ABBD-45B58A216CFA}')"); + ExpectExecute("TestExpectTrue(info.methodList[1] == 'def GetId(self) -> int')"); + ExpectExecute("TestExpectTrue(info.methodList[2] == 'def SetId(self, arg1: int) -> None')"); + ExpectExecute("TestExpectTrue(info.methodList[3] == 'def AddAndSet(self, arg1: int, arg2: int) -> None')"); + } + // // SceneManifestBehaviorScriptTest is meant to test the script abilities of the SceneManifest // diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h b/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h index 9ae287da46..403ab867f2 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h +++ b/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h @@ -31,7 +31,7 @@ namespace AZ public: AZ_RTTI(BlendShapeData, "{FF875C22-2E4F-4CE3-BA49-09BF78C70A09}", SceneAPI::DataTypes::IBlendShapeData) - SCENE_DATA_API static void Reflect(ReflectContext* context); + static void Reflect(ReflectContext* context); // Maximum number of color sets matches limitation set in assImp (AI_MAX_NUMBER_OF_COLOR_SETS) static constexpr AZ::u8 MaxNumColorSets = 8; diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp index 2b7676e4db..a22064cfe2 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp @@ -161,7 +161,7 @@ namespace EditorPythonBindings bufferArg = *name; } - AZStd::string_view type = FetchPythonType(*behaviorMethod.GetArgument(argIndex)); + AZStd::string type = FetchPythonTypeName(*behaviorMethod.GetArgument(argIndex)); if (!type.empty()) { AzFramework::StringFunc::Append(bufferArg, ": "); @@ -289,7 +289,7 @@ namespace EditorPythonBindings bool isBroadcast = false; if (sender.m_event) { - AZStd::string_view addressType = FetchPythonType(behaviorEBus->m_idParam); + AZStd::string addressType = FetchPythonTypeName(behaviorEBus->m_idParam); if (addressType.empty()) { AzFramework::StringFunc::Append(buffer, "(busCallType: int, busEventName: str, address: Any, args: Tuple[Any])"); @@ -338,7 +338,7 @@ namespace EditorPythonBindings } const AZ::BehaviorParameter* resultParam = behaviorMethod->GetResult(); - AZStd::string_view returnType = FetchPythonType(*resultParam); + AZStd::string returnType = FetchPythonTypeName(*resultParam); AZStd::string returnTypeStr = AZStd::string::format(") -> " AZ_STRING_FORMAT" \n", AZ_STRING_ARG(returnType)); AzFramework::StringFunc::Append(inOutStrBuffer, returnTypeStr.c_str()); }; @@ -664,9 +664,9 @@ namespace EditorPythonBindings return m_typeCache[typeId]; } - AZStd::string_view PythonLogSymbolsComponent::FetchPythonType(const AZ::BehaviorParameter& param) + AZStd::string PythonLogSymbolsComponent::FetchPythonTypeName(const AZ::BehaviorParameter& param) { - AZStd::string_view pythonType = FetchPythonTypeAndTraits(param.m_typeId, param.m_traits); + AZStd::string pythonType = FetchPythonTypeAndTraits(param.m_typeId, param.m_traits); if (pythonType.empty()) { diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h index 2972e3c9e0..e52cb00570 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h @@ -62,6 +62,7 @@ namespace EditorPythonBindings void LogGlobalMethod(AZStd::string_view moduleName, AZStd::string_view methodName, AZ::BehaviorMethod* behaviorMethod) override; void LogGlobalProperty(AZStd::string_view moduleName, AZStd::string_view propertyName, AZ::BehaviorProperty* behaviorProperty) override; void Finalize() override; + AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) override; //////////////////////////////////////////////////////////////////////// // EditorPythonConsoleInterface @@ -71,7 +72,6 @@ namespace EditorPythonBindings //////////////////////////////////////////////////////////////////////// // Python type deduction AZStd::string_view FetchPythonTypeAndTraits(const AZ::TypeId& typeId, AZ::u32 traits); - AZStd::string_view FetchPythonType(const AZ::BehaviorParameter& param); private: using ModuleSet = AZStd::unordered_set; diff --git a/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp b/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp index 97f4dd02d0..8297bad094 100644 --- a/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp +++ b/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp @@ -41,9 +41,9 @@ namespace UnitTest return FetchPythonTypeAndTraits(typeId, traits); } - AZStd::string_view FetchPythonTypeWrapper(const AZ::BehaviorParameter& param) + AZStd::string FetchPythonTypeWrapper(const AZ::BehaviorParameter& param) { - return FetchPythonType(param); + return FetchPythonTypeName(param); } }; From 1f6ec22e6e3040e3d1abcfc88d3adc6eeb845bf0 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Tue, 4 May 2021 12:59:49 -0500 Subject: [PATCH 046/112] Removed deprecated assets (GeomCache files) --- Assets/Editor/Presets/GeomCache/game.cbc | 1 - Assets/Editor/Presets/GeomCache/game_lz4hc.cbc | 1 - Assets/Editor/Presets/GeomCache/game_z_up.cbc | 1 - .../Presets/GeomCache/game_z_up_lz4hc.cbc | 1 - Assets/Editor/Presets/GeomCache/prerendered.cbc | 1 - .../Presets/GeomCache/prerendered_z_up.cbc | 1 - Assets/Editor/Presets/GeomCache/rigids_only.cbc | 1 - .../Presets/GeomCache/rigids_only_z_up.cbc | 1 - .../Editor/Presets/GeomCache/uncompressed.cbc | 1 - .../Presets/GeomCache/uncompressed_z_up.cbc | 1 - .../GeomCaches/defaultGeomCache.abc | 3 --- .../GeomCaches/defaultGeomCache.cbc | 1 - .../EngineAssets/GeomCaches/defaultGeomCache.ma | 3 --- .../GeomCaches/defaultGeomCache.mtl | 17 ----------------- 14 files changed, 34 deletions(-) delete mode 100644 Assets/Editor/Presets/GeomCache/game.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_lz4hc.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/prerendered.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/rigids_only.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/uncompressed.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl diff --git a/Assets/Editor/Presets/GeomCache/game.cbc b/Assets/Editor/Presets/GeomCache/game.cbc deleted file mode 100644 index 9b98f3460f..0000000000 --- a/Assets/Editor/Presets/GeomCache/game.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc deleted file mode 100644 index dbd0499175..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_z_up.cbc b/Assets/Editor/Presets/GeomCache/game_z_up.cbc deleted file mode 100644 index ec2555a3e3..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc deleted file mode 100644 index c2e30a6386..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/prerendered.cbc b/Assets/Editor/Presets/GeomCache/prerendered.cbc deleted file mode 100644 index c09785111d..0000000000 --- a/Assets/Editor/Presets/GeomCache/prerendered.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc b/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc deleted file mode 100644 index e42a915e58..0000000000 --- a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/rigids_only.cbc b/Assets/Editor/Presets/GeomCache/rigids_only.cbc deleted file mode 100644 index e8620bc11e..0000000000 --- a/Assets/Editor/Presets/GeomCache/rigids_only.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc b/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc deleted file mode 100644 index d1f8bc2db3..0000000000 --- a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/uncompressed.cbc b/Assets/Editor/Presets/GeomCache/uncompressed.cbc deleted file mode 100644 index e21d52d9d1..0000000000 --- a/Assets/Editor/Presets/GeomCache/uncompressed.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc b/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc deleted file mode 100644 index 273ce1fbb1..0000000000 --- a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc deleted file mode 100644 index 8ca759d342..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9c36d7bc993ddf616f478115a123efabda5b4b833a4e6524312f43c228ae0902 -size 487003 diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc deleted file mode 100644 index 3c99ab1627..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma deleted file mode 100644 index 65aade11a0..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:96a21446422b834ea90a5d38eaaca309fdee31dc3cc03c0e9c094b39ec3a459d -size 4715164 diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl deleted file mode 100644 index 05dfe70b09..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - From 11b79f567af12658b6f6958d8d89a32e925b40ce Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 4 May 2021 11:10:46 -0700 Subject: [PATCH 047/112] Smart and raw pointer support in Json Serialization now behave similarly. The behavior of smart pointers was not updated after the changes to raw pointers, in particular with how default JSON Objects were handled. They both now treat an empty JSON Object (a.k.a. the id for default instances) as meaning to create a default instance on the pointer even if the default is a nullptr. To have a nullptr a JSON Null has to be explicitly written. --- .../Serialization/Json/JsonDeserializer.cpp | 38 +++-- .../Serialization/Json/JsonSerialization.h | 11 ++ .../Json/SmartPointerSerializer.cpp | 15 +- .../Json/BaseJsonSerializerTests.cpp | 105 +++++++++++++- .../Json/SmartPointerSerializerTests.cpp | 134 ++++++++++++++---- 5 files changed, 242 insertions(+), 61 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index f2e9bb866f..8d0da9e54a 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -97,7 +97,8 @@ namespace AZ return context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, AZStd::string::format("Failed to retrieve rtti information for %s.", classData->m_name)); } - AZ_Assert(classData->m_azRtti->GetTypeId() == typeId, "Type id mismatch during deserialization of a json file. (%s vs %s)"); + AZ_Assert(classData->m_azRtti->GetTypeId() == typeId, "Type id mismatch during deserialization of a json file. (%s vs %s)", + classData->m_azRtti->GetTypeId().ToString().c_str(), typeId.ToString().c_str()); void** objectPtr = reinterpret_cast(object); bool isNull = *objectPtr == nullptr; @@ -512,27 +513,24 @@ namespace AZ if (*object) { const AZ::Uuid& actualClassId = rtti.GetActualUuid(*object); - if (actualClassId != objectType) + const SerializeContext::ClassData* actualClassData = context.GetSerializeContext()->FindClassData(actualClassId); + if (!actualClassData) { - const SerializeContext::ClassData* actualClassData = context.GetSerializeContext()->FindClassData(actualClassId); - if (!actualClassData) - { - status = context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, - AZStd::string::format("Unable to find serialization information for type %s.", actualClassId.ToString().c_str())); - return ResolvePointerResult::FullyProcessed; - } + status = context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, + AZStd::string::format("Unable to find serialization information for type %s.", actualClassId.ToString().c_str())); + return ResolvePointerResult::FullyProcessed; + } - if (actualClassData->m_factory) - { - actualClassData->m_factory->Destroy(*object); - *object = nullptr; - } - else - { - status = context.Report(Tasks::RetrieveInfo, Outcomes::Catastrophic, - "Unable to find the factory needed to clear out the default value."); - return ResolvePointerResult::FullyProcessed; - } + if (actualClassData->m_factory) + { + actualClassData->m_factory->Destroy(*object); + *object = nullptr; + } + else + { + status = context.Report(Tasks::RetrieveInfo, Outcomes::Catastrophic, + "Unable to find the factory needed to clear out the default value."); + return ResolvePointerResult::FullyProcessed; } } status = ResultCode(Tasks::ReadField, Outcomes::Success); diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h index 5746005832..b92eae7d6b 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h @@ -38,6 +38,17 @@ namespace AZ }; //! Core class to handle serialization to and from json documents. + //! The Json Serialization works by taking a default constructed object and then apply the information found in the JSON document + //! on top of that object. This allows the Json Serialization to avoid storing default values and helps guarantee that the final + //! object is in a valid state even if non-fatal issues are encountered. + //! Note on containers: Containers such as vector or map are always considered to be empty even if there's entries in the provided + //! default object. During deserialization entries will be appended to any existing values. A flag is provided to automatically + //! clear containers during deserialization. + //! Note on maps: If the key for map containers such as unordered_map can be interpret as a string the Json Serialization will use + //! a JSON Object to store the data in instead of an array with key/value objects. + //! Note on pointers: The Json Serialization assumes that are always constructed, so a default JSON value of "{}" is interpret as + //! creating a new default instance even if the default value is a null pointer. A JSON Null needs to be explicitly stored in + //! the JSON Document in order to default or explicitly set a pointer to null. class JsonSerialization final { public: diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp index 0180e99592..9e707f8644 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp @@ -23,13 +23,6 @@ namespace AZ { namespace JSR = JsonSerializationResult; - if (IsExplicitDefault(inputValue)) - { - // Do nothing if the input is an explicit default. - return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::DefaultsUsed, - "Default value for smart pointer requested so no change was made."); - } - const SerializeContext::ClassData* containerClass = context.GetSerializeContext()->FindClassData(outputValueTypeId); if (!containerClass) { @@ -153,8 +146,7 @@ namespace AZ if (defaultValue) { - bool typesMatch = false; - auto defaultInputCallback = [&defaultValue, &inputPtrType, &typesMatch] + auto defaultInputCallback = [&defaultValue] (void* elementPtr, const Uuid&, const SerializeContext::ClassData*, const SerializeContext::ClassElement*) { defaultValue = elementPtr; @@ -164,11 +156,6 @@ namespace AZ } JSR::ResultCode result = ContinueStoring(outputValue, inputValue, defaultValue, inputPtrType, context, Flags::ResolvePointer); - if (result.GetOutcome() == JSR::Outcomes::DefaultsUsed) - { - outputValue = GetExplicitDefault(); - return context.Report(result, "Smart pointer used all defaults."); - } return context.Report(result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully processed smart pointer." : "A problem occurred while processing a smart pointer."); } diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp index 417cb10c8c..62622ef7ab 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp @@ -110,7 +110,7 @@ namespace JsonSerializationTests EXPECT_EQ(42, value); } - TEST_F(BaseJsonSerializerTests, ContinueLoading_PointerInstance_ValueLoadedCorrectly) + TEST_F(BaseJsonSerializerTests, ContinueLoading_ToPointerInstance_ValueLoadedCorrectly) { using namespace AZ::JsonSerializationResult; @@ -126,6 +126,51 @@ namespace JsonSerializationTests EXPECT_EQ(42, value); } + TEST_F(BaseJsonSerializerTests, ContinueLoading_ToNullPointer_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json; + json.Set(42); + int* ptrValue = nullptr; + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_NE(nullptr, ptrValue); + EXPECT_EQ(42, *ptrValue); + + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + } + + TEST_F(BaseJsonSerializerTests, ContinueLoading_DefaultToNullPointer_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json(rapidjson::kObjectType); + int* ptrValue = nullptr; + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_NE(nullptr, ptrValue); + + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + } + + TEST_F(BaseJsonSerializerTests, ContinueLoading_NullDeletesObject_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json(rapidjson::kNullType); + int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), AZStd::alignment_of::value, AZ::SystemAllocator)); + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_EQ(nullptr, ptrValue); + } + // // ContinueStoring // @@ -156,6 +201,64 @@ namespace JsonSerializationTests Expect_DocStrEq("42"); } + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToFullDefaultedInstance_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int value = 42; + int* ptrValue = &value; + int value2 = 42; + int* defaultPtrValue = &value2; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("{}"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptr_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + + ResultCode result = ContinueStoring( + *m_jsonDocument, &ptrValue, nullptr, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptrWithValueDefault_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + int value2 = 42; + int* defaultPtrValue = &value2; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptrWithNullPtrDefault_NullPtrIsStored) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + int* defaultPtrValue = nullptr; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + TEST_F(BaseJsonSerializerTests, ContinueStoring_ReplaceDefault_ValueStoredCorrectly) { using namespace AZ::JsonSerializationResult; diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp index df340a2e61..2fc131aae2 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp @@ -32,11 +32,6 @@ namespace JsonSerializationTests return AZStd::make_shared(); } - AZStd::shared_ptr CreateDefaultInstance() override - { - return AZStd::make_shared(); - } - void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -51,6 +46,13 @@ namespace JsonSerializationTests using SmartPointer = T; using Base = SmartPointerBaseTestDescription; + AZStd::shared_ptr CreateDefaultInstance() override + { + auto result = AZStd::make_shared(); + *result = SmartPointer(aznew SimpleClass()); + return result; + } + AZStd::shared_ptr CreateFullySetInstance() override { auto result = AZStd::make_shared(); @@ -106,21 +108,6 @@ namespace JsonSerializationTests } }; - template class T> - class SmartPointerSimpleClassWithInstanceTestDescription : - public SmartPointerSimpleClassTestDescription - { - public: - using SmartPointer = typename SmartPointerSimpleClassTestDescription::SmartPointer; - - AZStd::shared_ptr CreateDefaultInstance() override - { - auto result = AZStd::make_shared(); - *result = SmartPointer(aznew SimpleClass()); - return result; - } - }; - template class T> class SmartPointerSimpleDerivedClassTestDescription : public SmartPointerBaseTestDescription> @@ -129,6 +116,13 @@ namespace JsonSerializationTests using SmartPointer = T; using Base = SmartPointerBaseTestDescription; + AZStd::shared_ptr CreateDefaultInstance() override + { + auto result = AZStd::make_shared(); + *result = SmartPointer(aznew BaseClass()); + return result; + } + AZStd::shared_ptr CreateFullySetInstance() override { auto* instance = aznew SimpleInheritence(); @@ -272,6 +266,13 @@ namespace JsonSerializationTests using SmartPointer = T; using Base = SmartPointerBaseTestDescription; + AZStd::shared_ptr CreateDefaultInstance() override + { + auto result = AZStd::make_shared(); + *result = SmartPointer(aznew BaseClass2()); + return result; + } + AZStd::shared_ptr CreateFullySetInstance() override { auto* instance = aznew MultipleInheritence(); @@ -424,9 +425,6 @@ namespace JsonSerializationTests SmartPointerSimpleClassTestDescription, SmartPointerSimpleClassTestDescription, SmartPointerSimpleClassTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, // Simple derived class, include single inheritance. SmartPointerSimpleDerivedClassTestDescription, SmartPointerSimpleDerivedClassTestDescription, @@ -551,6 +549,37 @@ namespace JsonSerializationTests EXPECT_EQ(nullptr, *instance); } + TEST_F(JsonSmartPointerSerializerTests, Load_DefaultInstanceToNullptr_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + AZStd::shared_ptr compare = m_description.CreateDefaultInstance(); + m_jsonDocument->SetObject(); + + JSR::ResultCode result = + m_serializer.Load(&instance, azrtti_typeid(), *m_jsonDocument, *m_jsonDeserializationContext); + + EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, instance); + EXPECT_TRUE(m_description.AreEqual(instance, *compare)); + } + + TEST_F(JsonSmartPointerSerializerTests, Load_DefaultObjectDoesNotUpdateInstance_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateFullySetInstance(); + AZStd::shared_ptr compare = m_description.CreateFullySetInstance(); + m_jsonDocument->SetObject(); + + JSR::ResultCode result = + m_serializer.Load(instance.get(), azrtti_typeid(), *m_jsonDocument, *m_jsonDeserializationContext); + + EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); + EXPECT_TRUE(m_description.AreEqual(*instance, *compare)); + } + TEST_F(JsonSmartPointerSerializerTests, Load_InstanceBeingReplacedWithDifferentType_ReturnsSuccess) { namespace JSR = AZ::JsonSerializationResult; @@ -720,13 +749,66 @@ namespace JsonSerializationTests namespace JSR = AZ::JsonSerializationResult; AZStd::shared_ptr instance = m_description.CreateFullySetInstance(); - SmartPointer nullPtr; - JSR::ResultCode result = m_serializer.Store(*m_jsonDocument, instance.get(), &nullPtr, + SmartPointer defaultInstance; + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, instance.get(), &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); EXPECT_EQ(JSR::Outcomes::Success, result.GetOutcome()); } + TEST_F(JsonSmartPointerSerializerTests, Store_ValuePointerIsNullPtr_ReturnsSuccessAndStoresNull) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + AZStd::shared_ptr defaultInstance = m_description.CreateFullySetInstance(); + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, &instance, defaultInstance.get(), azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::Success, result.GetOutcome()); + EXPECT_TRUE(m_jsonDocument->IsNull()); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueAndDefaultPointersAreNullPtr_ReturnsSuccessAndStoresNull) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + SmartPointer defaultInstance; + JSR::ResultCode result = + m_serializer.Store(*m_jsonDocument, &instance, &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + EXPECT_TRUE(m_jsonDocument->IsNull()); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueAndDefaultPointersAreBothDefault_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateDefaultInstance(); + AZStd::shared_ptr defaultInstance = m_description.CreateDefaultInstance(); + JSR::ResultCode result = + m_serializer.Store(*m_jsonDocument, instance.get(), defaultInstance.get(), azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + Expect_ExplicitDefault(*m_jsonDocument); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueHasDefaultValuesAndDefaultHasNullPointer_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateDefaultInstance(); + SmartPointer defaultInstance; + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, instance.get(), &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + Expect_ExplicitDefault(*m_jsonDocument); + } + TEST_F(JsonSmartPointerSerializerTests, Store_DefaultPointerIsOtherClass_CompletesButDoesNotReturnDefaults) { namespace JSR = AZ::JsonSerializationResult; @@ -749,7 +831,7 @@ namespace JsonSerializationTests EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); } - TEST_F(JsonSmartPointerSerializerTests, Store_SaveAnClassThatIsNotReflected_ReturnsUnknown) + TEST_F(JsonSmartPointerSerializerTests, Store_ClassThatIsNotReflected_ReturnsUnknown) { namespace JSR = AZ::JsonSerializationResult; From 937d0ac726f43733b4018390d7479787055e5f72 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 4 May 2021 19:11:40 +0100 Subject: [PATCH 048/112] bump inter-test timeout by 1 sec for C5932042_PhysXForceRegion_LinearDamping --- .../physics/C5932042_PhysXForceRegion_LinearDamping.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py index 04cecd45b2..21d386954d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py @@ -135,7 +135,7 @@ def C5932042_PhysXForceRegion_LinearDamping(): # Constants CLOSE_ENOUGH = 0.001 - TIME_OUT = 2.0 + TIME_OUT = 3.0 INITIAL_VELOCITY = azmath.Vector3(0.0, 0.0, -10.0) # 1) Open level / Enter game mode From f770e4aa7a8efcc26d1540bb7b221129726c2eb6 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Tue, 4 May 2021 19:12:01 +0100 Subject: [PATCH 049/112] Unifying operators in Matrix3x3, Matrix3x4 and Matrix4x4 - Add operators +, -, * and / too all matrix classes - Add RetrieveScaleSq and GetReciprocalScaled to all matrix classes - Add unit tests to all matrix classes - Fix a bug that causes release configuration not to compile. --- Code/Framework/AzCore/AzCore/Math/Matrix3x3.h | 51 +++-- .../AzCore/AzCore/Math/Matrix3x3.inl | 141 ++++++++----- Code/Framework/AzCore/AzCore/Math/Matrix3x4.h | 41 +++- .../AzCore/AzCore/Math/Matrix3x4.inl | 99 +++++++-- Code/Framework/AzCore/AzCore/Math/Matrix4x4.h | 44 +++- .../AzCore/AzCore/Math/Matrix4x4.inl | 107 ++++++++-- .../AzCore/Tests/Math/Matrix3x3Tests.cpp | 131 +++++++----- .../AzCore/Tests/Math/Matrix3x4Tests.cpp | 163 +++++++++++---- .../AzCore/Tests/Math/Matrix4x4Tests.cpp | 194 ++++++++++++++++-- .../ValuePointerReferenceExample.cpp | 2 +- 10 files changed, 746 insertions(+), 227 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h index e1736e1444..973bb52df3 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h @@ -142,27 +142,44 @@ namespace AZ void SetBasis(const Vector3& basisX, const Vector3& basisY, const Vector3& basisZ); //! @} - Matrix3x3 operator*(const Matrix3x3& rhs) const; - //! Calculates (this->GetTranspose() * rhs). Matrix3x3 TransposedMultiply(const Matrix3x3& rhs) const; //! Post-multiplies the matrix by a vector. Vector3 operator*(const Vector3& rhs) const; - Matrix3x3 operator+(const Matrix3x3& rhs) const; - Matrix3x3 operator-(const Matrix3x3& rhs) const; - - Matrix3x3 operator*(float multiplier) const; - Matrix3x3 operator/(float divisor) const; - - Matrix3x3 operator-() const; - - Matrix3x3& operator*=(const Matrix3x3& rhs); + //! Operator for matrix-matrix addition. + //! @{ + [[nodiscard]] Matrix3x3 operator+(const Matrix3x3& rhs) const; Matrix3x3& operator+=(const Matrix3x3& rhs); + //! @} + + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix3x3 operator-(const Matrix3x3& rhs) const; Matrix3x3& operator-=(const Matrix3x3& rhs); + //! @} + + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix3x3 operator*(const Matrix3x3& rhs) const; + Matrix3x3& operator*=(const Matrix3x3& rhs); + //! @} + + //! Operator for multiplying all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x3 operator*(float multiplier) const; Matrix3x3& operator*=(float multiplier); + //! @} + + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x3 operator/(float divisor) const; Matrix3x3& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix3x3 operator-() const; bool operator==(const Matrix3x3& rhs) const; bool operator!=(const Matrix3x3& rhs) const; @@ -187,7 +204,10 @@ namespace AZ //! @} //! Gets the scale part of the transformation, i.e. the length of the scale components. - Vector3 RetrieveScale() const; + [[nodiscard]] Vector3 RetrieveScale() const; + + //! Gets the squared scale part of the transformation (the squared length of the basis vectors). + [[nodiscard]] Vector3 RetrieveScaleSq() const; //! Gets the scale part of the transformation as in RetrieveScale, and also removes this scaling from the matrix. Vector3 ExtractScale(); @@ -195,6 +215,9 @@ namespace AZ //! Quick multiplication by a scale matrix, equivalent to m*=Matrix3x3::CreateScale(scale). void MultiplyByScale(const Vector3& scale); + //! Returns a matrix with the reciprocal scale, keeping the same rotation and translation. + [[nodiscard]] Matrix3x3 GetReciprocalScaled() const; + //! Polar decomposition, M=U*H, U is orthogonal (unitary) and H is symmetric (hermitian). //! This function returns the orthogonal part only Matrix3x3 GetPolarDecomposition() const; @@ -241,7 +264,9 @@ namespace AZ //! Note that this is not the usual multiplication order for transformations. Vector3& operator*=(Vector3& lhs, const Matrix3x3& rhs); + //! Pre-multiplies the matrix by a scalar. Matrix3x3 operator*(float lhs, const Matrix3x3& rhs); -} + +} // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl index ff92da1398..6b4dccf3c1 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl @@ -392,14 +392,6 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(const Matrix3x3& rhs) const - { - Matrix3x3 result; - Simd::Vec3::Mat3x3Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); - return result; - } - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::TransposedMultiply(const Matrix3x3& rhs) const { Matrix3x3 result; @@ -416,51 +408,12 @@ namespace AZ AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator+(const Matrix3x3& rhs) const { - return Matrix3x3(Simd::Vec3::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec3::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec3::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue())); - } - - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-(const Matrix3x3& rhs) const - { - return Matrix3x3(Simd::Vec3::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec3::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec3::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue())); - } - - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(float multiplier) const - { - const Simd::Vec3::FloatType mulVec = Simd::Vec3::Splat(multiplier); - return Matrix3x3(Simd::Vec3::Mul(m_rows[0].GetSimdValue(), mulVec) - , Simd::Vec3::Mul(m_rows[1].GetSimdValue(), mulVec) - , Simd::Vec3::Mul(m_rows[2].GetSimdValue(), mulVec)); - } - - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator/(float divisor) const - { - const Simd::Vec3::FloatType divVec = Simd::Vec3::Splat(divisor); - return Matrix3x3(Simd::Vec3::Div(m_rows[0].GetSimdValue(), divVec) - , Simd::Vec3::Div(m_rows[1].GetSimdValue(), divVec) - , Simd::Vec3::Div(m_rows[2].GetSimdValue(), divVec)); - } - - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-() const - { - const Simd::Vec3::FloatType zeroVec = Simd::Vec3::ZeroFloat(); - return Matrix3x3(Simd::Vec3::Sub(zeroVec, m_rows[0].GetSimdValue()) - , Simd::Vec3::Sub(zeroVec, m_rows[1].GetSimdValue()) - , Simd::Vec3::Sub(zeroVec, m_rows[2].GetSimdValue())); - } - - - AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator*=(const Matrix3x3& rhs) - { - *this = *this * rhs; - return *this; + return Matrix3x3 + ( + Simd::Vec3::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec3::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec3::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); } @@ -471,6 +424,17 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-(const Matrix3x3& rhs) const + { + return Matrix3x3 + ( + Simd::Vec3::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec3::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec3::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); + } + + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator-=(const Matrix3x3& rhs) { *this = *this - rhs; @@ -478,6 +442,33 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(const Matrix3x3& rhs) const + { + Matrix3x3 result; + Simd::Vec3::Mat3x3Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); + return result; + } + + + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator*=(const Matrix3x3& rhs) + { + *this = *this * rhs; + return *this; + } + + + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(float multiplier) const + { + const Simd::Vec3::FloatType mulVec = Simd::Vec3::Splat(multiplier); + return Matrix3x3 + ( + Simd::Vec3::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec3::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec3::Mul(m_rows[2].GetSimdValue(), mulVec) + ); + } + + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator*=(float multiplier) { *this = *this * multiplier; @@ -485,6 +476,18 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator/(float divisor) const + { + const Simd::Vec3::FloatType divVec = Simd::Vec3::Splat(divisor); + return Matrix3x3 + ( + Simd::Vec3::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec3::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec3::Div(m_rows[2].GetSimdValue(), divVec) + ); + } + + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator/=(float divisor) { *this = *this / divisor; @@ -492,6 +495,18 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-() const + { + const Simd::Vec3::FloatType zeroVec = Simd::Vec3::ZeroFloat(); + return Matrix3x3 + ( + Simd::Vec3::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec3::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec3::Sub(zeroVec, m_rows[2].GetSimdValue()) + ); + } + + AZ_MATH_INLINE bool Matrix3x3::operator==(const Matrix3x3& rhs) const { return (Simd::Vec3::CmpAllEq(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) @@ -552,6 +567,12 @@ namespace AZ } + AZ_MATH_INLINE Vector3 Matrix3x3::RetrieveScaleSq() const + { + return Vector3(GetBasisX().GetLengthSq(), GetBasisY().GetLengthSq(), GetBasisZ().GetLengthSq()); + } + + AZ_MATH_INLINE Vector3 Matrix3x3::ExtractScale() { const Vector3 x = GetBasisX(); @@ -584,6 +605,14 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::GetReciprocalScaled() const + { + Matrix3x3 result = *this; + result.MultiplyByScale(RetrieveScaleSq().GetReciprocal()); + return result; + } + + AZ_MATH_INLINE void Matrix3x3::GetPolarDecomposition(Matrix3x3* orthogonalOut, Matrix3x3* symmetricOut) const { *orthogonalOut = GetPolarDecomposition(); @@ -679,8 +708,6 @@ namespace AZ AZ_MATH_INLINE Matrix3x3 operator*(float lhs, const Matrix3x3& rhs) { - const Simd::Vec3::FloatType lhsVec = Simd::Vec3::Splat(lhs); - const Simd::Vec3::FloatType* rows = rhs.GetSimdValues(); - return Matrix3x3(Simd::Vec3::Mul(lhsVec, rows[0]), Simd::Vec3::Mul(lhsVec, rows[1]), Simd::Vec3::Mul(lhsVec, rows[2])); + return rhs * lhs; } -} +} // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h index 09f443c1cf..a18f1e7565 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h @@ -225,23 +225,38 @@ namespace AZ //! Sets the three basis vectors and the translation. void SetBasisAndTranslation(const Vector3& basisX, const Vector3& basisY, const Vector3& basisZ, const Vector3& translation); - //! Operator for matrix-matrix multiplication. - [[nodiscard]] Matrix3x4 operator*(const Matrix3x4& rhs) const; - - //! Compound assignment operator for matrix-matrix multiplication. - Matrix3x4& operator*=(const Matrix3x4& rhs); - //! Operator for matrix-matrix addition. + //! @{ [[nodiscard]] Matrix3x4 operator+(const Matrix3x4& rhs) const; - - //! Compound assignment operator for matrix-matrix addition. Matrix3x4& operator+=(const Matrix3x4& rhs); + //! @} + + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix3x4 operator-(const Matrix3x4& rhs) const; + Matrix3x4& operator-=(const Matrix3x4& rhs); + //! @} + + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix3x4 operator*(const Matrix3x4& rhs) const; + Matrix3x4& operator*=(const Matrix3x4& rhs); + //! @} //! Operator for multiplying all matrix's elements with a scalar - [[nodiscard]] Matrix3x4 operator*(float scalar) const; + //! @{ + [[nodiscard]] Matrix3x4 operator*(float multiplier) const; + Matrix3x4& operator*=(float multiplier); + //! @} - //! Compound assignment operator for multiplying all matrix's elements with a scalar - Matrix3x4& operator*=(float scalar); + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x4 operator/(float divisor) const; + Matrix3x4& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix3x4 operator-() const; //! Operator for transforming a Vector3. [[nodiscard]] Vector3 operator*(const Vector3& rhs) const; @@ -353,6 +368,10 @@ namespace AZ Vector4 m_rows[RowCount]; }; + + //! Pre-multiplies the matrix by a scalar. + Matrix3x4 operator*(float lhs, const Matrix3x4& rhs); + } // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl index 232e8a5b30..781dcf9b66 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl @@ -472,21 +472,6 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(const Matrix3x4& rhs) const - { - Matrix3x4 result; - Simd::Vec4::Mat3x4Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); - return result; - } - - - AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(const Matrix3x4& rhs) - { - *this = *this * rhs; - return *this; - } - - AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator+(const Matrix3x4& rhs) const { return Matrix3x4 @@ -505,25 +490,89 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(float scalar) const + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator-(const Matrix3x4& rhs) const { - const Vector4 vector4Scalar(scalar); return Matrix3x4 ( - Simd::Vec4::Mul(m_rows[0].GetSimdValue(), vector4Scalar.GetSimdValue()), - Simd::Vec4::Mul(m_rows[1].GetSimdValue(), vector4Scalar.GetSimdValue()), - Simd::Vec4::Mul(m_rows[2].GetSimdValue(), vector4Scalar.GetSimdValue()) + Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) ); } - AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(float scalar) + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator-=(const Matrix3x4& rhs) { - *this = *this * scalar; + *this = *this - rhs; return *this; } + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(const Matrix3x4& rhs) const + { + Matrix3x4 result; + Simd::Vec4::Mat3x4Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); + return result; + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(const Matrix3x4& rhs) + { + *this = *this * rhs; + return *this; + } + + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(float multiplier) const + { + const Simd::Vec4::FloatType mulVec = Simd::Vec4::Splat(multiplier); + return Matrix3x4 + ( + Simd::Vec4::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[2].GetSimdValue(), mulVec) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(float multiplier) + { + *this = *this * multiplier; + return *this; + } + + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator/(float divisor) const + { + const Simd::Vec4::FloatType divVec = Simd::Vec4::Splat(divisor); + return Matrix3x4 + ( + Simd::Vec4::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[2].GetSimdValue(), divVec) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator/=(float divisor) + { + *this = *this / divisor; + return *this; + } + + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator-() const + { + const Simd::Vec4::FloatType zeroVec = Simd::Vec4::ZeroFloat(); + return Matrix3x4 + ( + Simd::Vec4::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[2].GetSimdValue()) + ); + } + + AZ_MATH_INLINE Vector3 Matrix3x4::operator*(const Vector3& rhs) const { return Vector3 @@ -711,4 +760,10 @@ namespace AZ { return reinterpret_cast(m_rows); } + + + AZ_MATH_INLINE Matrix3x4 operator*(float lhs, const Matrix3x4& rhs) + { + return rhs * lhs; + } } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h index 1612f8c962..a94b3c7ae2 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h @@ -171,14 +171,38 @@ namespace AZ void SetTranslation(const Vector3& v); //! @} - Matrix4x4 operator+(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix addition. + //! @{ + [[nodiscard]] Matrix4x4 operator+(const Matrix4x4& rhs) const; Matrix4x4& operator+=(const Matrix4x4& rhs); + //! @} - Matrix4x4 operator-(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix4x4 operator-(const Matrix4x4& rhs) const; Matrix4x4& operator-=(const Matrix4x4& rhs); + //! @} - Matrix4x4 operator*(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix4x4 operator*(const Matrix4x4& rhs) const; Matrix4x4& operator*=(const Matrix4x4& rhs); + //! @} + + //! Operator for multiplying all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix4x4 operator*(float multiplier) const; + Matrix4x4& operator*=(float multiplier); + //! @} + + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix4x4 operator/(float divisor) const; + Matrix4x4& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix4x4 operator-() const; //! Post-multiplies the matrix by a vector. //! Assumes that the w-component of the Vector3 is 1.0. @@ -222,7 +246,10 @@ namespace AZ //! @} //! Gets the scale part of the transformation, i.e. the length of the scale components. - Vector3 RetrieveScale() const; + [[nodiscard]] Vector3 RetrieveScale() const; + + //! Gets the squared scale part of the transformation (the squared length of the basis vectors). + [[nodiscard]] Vector3 RetrieveScaleSq() const; //! Gets the scale part of the transformation as in RetrieveScale, and also removes this scaling from the matrix. Vector3 ExtractScale(); @@ -230,6 +257,9 @@ namespace AZ //! Quick multiplication by a scale matrix, equivalent to m*=Matrix4x4::CreateScale(scale). void MultiplyByScale(const Vector3& scale); + //! Returns a matrix with the reciprocal scale, keeping the same rotation and translation. + [[nodiscard]] Matrix4x4 GetReciprocalScaled() const; + bool IsClose(const Matrix4x4& rhs, float tolerance = Constants::Tolerance) const; bool operator==(const Matrix4x4& rhs) const; @@ -270,6 +300,10 @@ namespace AZ //! Pre-multiplies the matrix by a vector in-place. //! Note that this is not the usual multiplication order for transformations. Vector4& operator*=(Vector4& lhs, const Matrix4x4& rhs); -} + + //! Pre-multiplies the matrix by a scalar. + Matrix4x4 operator*(float lhs, const Matrix4x4& rhs); + +} // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl index 3c4572accd..e32ebe31af 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl @@ -480,20 +480,12 @@ namespace AZ AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator+(const Matrix4x4& rhs) const { return Matrix4x4 - ( Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) - , Simd::Vec4::Add(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue())); - } - - - AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-(const Matrix4x4& rhs) const - { - return Matrix4x4 - ( Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue())); + ( + Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()), + Simd::Vec4::Add(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue()) + ); } AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator+=(const Matrix4x4& rhs) @@ -502,6 +494,18 @@ namespace AZ return *this; } + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-(const Matrix4x4& rhs) const + { + return Matrix4x4 + ( + Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()), + Simd::Vec4::Sub(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue()) + ); + } + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator-=(const Matrix4x4& rhs) { *this = *this - rhs; @@ -523,6 +527,59 @@ namespace AZ } + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator*(float multiplier) const + { + const Simd::Vec4::FloatType mulVec = Simd::Vec4::Splat(multiplier); + return Matrix4x4 + ( + Simd::Vec4::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[2].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[3].GetSimdValue(), mulVec) + ); + } + + + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator*=(float multiplier) + { + *this = *this * multiplier; + return *this; + } + + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator/(float divisor) const + { + const Simd::Vec4::FloatType divVec = Simd::Vec4::Splat(divisor); + return Matrix4x4 + ( + Simd::Vec4::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[2].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[3].GetSimdValue(), divVec) + ); + } + + + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator/=(float divisor) + { + *this = *this / divisor; + return *this; + } + + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-() const + { + const Simd::Vec4::FloatType zeroVec = Simd::Vec4::ZeroFloat(); + return Matrix4x4 + ( + Simd::Vec4::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[2].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[3].GetSimdValue()) + ); + } + + AZ_MATH_INLINE Vector3 Matrix4x4::operator*(const Vector3& rhs) const { return Vector3(Simd::Vec4::Mat4x4TransformPoint3(GetSimdValues(), rhs.GetSimdValue())); @@ -595,6 +652,12 @@ namespace AZ } + AZ_MATH_INLINE Vector3 Matrix4x4::RetrieveScaleSq() const + { + return Vector3(GetBasisX().GetLengthSq(), GetBasisY().GetLengthSq(), GetBasisZ().GetLengthSq()); + } + + AZ_MATH_INLINE Vector3 Matrix4x4::ExtractScale() { Vector4 x = GetBasisX(); @@ -619,6 +682,14 @@ namespace AZ } + AZ_MATH_INLINE Matrix4x4 Matrix4x4::GetReciprocalScaled() const + { + Matrix4x4 result = *this; + result.MultiplyByScale(RetrieveScaleSq().GetReciprocal()); + return result; + } + + AZ_MATH_INLINE bool Matrix4x4::IsClose(const Matrix4x4& rhs, float tolerance) const { const Simd::Vec4::FloatType vecTolerance = Simd::Vec4::Splat(tolerance); @@ -702,4 +773,10 @@ namespace AZ lhs = lhs * rhs; return lhs; } -} + + + AZ_MATH_INLINE Matrix4x4 operator*(float lhs, const Matrix4x4& rhs) + { + return rhs * lhs; + } +} // namespace AZ diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp index a849cfdaab..efa0ee531c 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include using namespace AZ; @@ -251,19 +252,19 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(66.0f, 72.0f, 78.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(156.0f, 171.0f, 186.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(246.0f, 270.0f, 294.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); Matrix3x3 m4 = m1; m4 *= m2; - AZ_TEST_ASSERT(m4.GetRow(0).IsClose(Vector3(66.0f, 72.0f, 78.0f))); - AZ_TEST_ASSERT(m4.GetRow(1).IsClose(Vector3(156.0f, 171.0f, 186.0f))); - AZ_TEST_ASSERT(m4.GetRow(2).IsClose(Vector3(246.0f, 270.0f, 294.0f))); + EXPECT_THAT(m4.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); m3 = m1.TransposedMultiply(m2); - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(138.0f, 150.0f, 162.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(168.0f, 183.0f, 198.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(198.0f, 216.0f, 234.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(138.0f, 150.0f, 162.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(168.0f, 183.0f, 198.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(198.0f, 216.0f, 234.0f))); } TEST(MATH_Matrix3x3, TestVectorMultiplication) @@ -277,11 +278,11 @@ namespace UnitTest m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); - AZ_TEST_ASSERT((m1 * Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(14.0f, 32.0f, 50.0f))); + EXPECT_THAT((m1 * Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(14.0f, 32.0f, 50.0f))); Vector3 v1(1.0f, 2.0f, 3.0f); - AZ_TEST_ASSERT((v1 * m1).IsClose(Vector3(30.0f, 36.0f, 42.0f))); + EXPECT_THAT((v1 * m1), IsClose(Vector3(30.0f, 36.0f, 42.0f))); v1 *= m1; - AZ_TEST_ASSERT(v1.IsClose(Vector3(30.0f, 36.0f, 42.0f))); + EXPECT_THAT(v1, IsClose(Vector3(30.0f, 36.0f, 42.0f))); } TEST(MATH_Matrix3x3, TestSum) @@ -296,15 +297,15 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 + m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); m3 = m1; m3 += m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); } TEST(MATH_Matrix3x3, TestDifference) @@ -319,14 +320,14 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 - m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); m3 = m1; m3 -= m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); } TEST(MATH_Matrix3x3, TestScalarMultiplication) @@ -341,18 +342,18 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * 2.0f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 *= 2.0f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = 2.0f * m1; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestScalarDivision) @@ -367,18 +368,32 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 / 0.5f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 /= 0.5f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - m3 = -m1; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-1.0f, -2.0f, -3.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-4.0f, -5.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-7.0f, -8.0f, -9.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + } + + TEST(MATH_Matrix3x3, TestNegation) + { + Matrix3x3 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f); + m1.SetRow(1, 4.0f, 5.0f, 6.0f); + m1.SetRow(2, 7.0f, 8.0f, 9.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-Matrix3x3::CreateZero(), IsClose(Matrix3x3::CreateZero())); + + Matrix3x3 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(Vector3(-1.0f, -2.0f, -3.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(Vector3(-4.0f, -5.0f, -6.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(Vector3(-7.0f, -8.0f, -9.0f))); + + Matrix3x3 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(Matrix3x3::CreateZero())); } TEST(MATH_Matrix3x3, TestTranspose) @@ -425,11 +440,33 @@ namespace UnitTest TEST(MATH_Matrix3x3, TestScaleAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3(2.0f, 3.0f, 4.0f))); - AZ_TEST_ASSERT(m1.ExtractScale().IsClose(Vector3(2.0f, 3.0f, 4.0f))); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3::CreateOne())); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.ExtractScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3::CreateOne())); m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3(3.0f, 4.0f, 5.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(3.0f, 4.0f, 5.0f))); + } + + TEST(MATH_Matrix3x3, TestScaleSqAccess) + { + Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(4.0f, 9.0f, 16.0f))); + m1.ExtractScale(); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(9.0f, 16.0f, 25.0f))); + } + + TEST(MATH_Matrix3x3, TestReciprocalScaled) + { + Matrix3x3 orthogonalMatrix = Matrix3x3::CreateRotationX(DegToRad(40.0f)); + EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix3x3 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + AZ::Matrix3x3 reciprocalScaledMatrix = orthogonalMatrix; + reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); + EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); } TEST(MATH_Matrix3x3, TestPolarDecomposition) diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp index 353b46874b..0bb64411e6 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp @@ -467,53 +467,136 @@ namespace UnitTest EXPECT_THAT(matrix.Multiply3x3(axisDirection), IsClose(forwardDirection)); } - TEST(MATH_Matrix3x4, MultiplyByMatrix3x4) + TEST(MATH_Matrix3x4, TestMatrixMultiplication) { - const AZ::Matrix3x4 matrix1 = AZ::Matrix3x4::CreateFromValue(1.2f); - const AZ::Matrix3x4 matrix2 = AZ::Matrix3x4::CreateDiagonal(AZ::Vector3(1.3f, 1.5f, 0.4f)); - const AZ::Matrix3x4 matrix3 = AZ::Matrix3x4::CreateFromQuaternionAndTranslation( - AZ::Quaternion(0.42f, 0.46f, -0.66f, 0.42f), AZ::Vector3(2.8f, -3.7f, 1.6f)); - const AZ::Matrix3x4 matrix4 = AZ::Matrix3x4::CreateRotationX(-0.7f) * AZ::Matrix3x4::CreateScale(AZ::Vector3(0.6f, 1.3f, 0.7f)); - AZ::Matrix3x4 matrix5 = matrix1; - matrix5 *= matrix4; - const AZ::Vector3 vector(1.9f, 2.3f, 0.2f); - EXPECT_TRUE((matrix1 * (matrix2 * matrix3)).IsClose((matrix1 * matrix2) * matrix3)); - EXPECT_THAT((matrix3 * matrix4) * vector, IsClose(matrix3 * (matrix4 * vector))); - EXPECT_TRUE((matrix2 * AZ::Matrix3x4::Identity()).IsClose(matrix2)); - EXPECT_TRUE((matrix3 * AZ::Matrix3x4::Identity()).IsClose(AZ::Matrix3x4::Identity() * matrix3)); - EXPECT_TRUE(matrix5.IsClose(matrix1 * matrix4)); + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + AZ::Matrix3x4 m3 = m1 * m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(74.0f, 80.0f, 86.0f, 96.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(206.0f, 224.0f, 242.0f, 268.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(338.0f, 368.0f, 398.0f, 440.0f))); + AZ::Matrix3x4 m4 = m1; + m4 *= m2; + EXPECT_THAT(m4.GetRow(0), IsClose(AZ::Vector4(74.0f, 80.0f, 86.0f, 96.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(AZ::Vector4(206.0f, 224.0f, 242.0f, 268.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(AZ::Vector4(338.0f, 368.0f, 398.0f, 440.0f))); } - TEST(MATH_Matrix3x4, AddMatrix3x4) + TEST(MATH_Matrix3x4, TestSum) { - const AZ::Matrix3x4 matrix1 = AZ::Matrix3x4::CreateFromValue(1.2f); - const AZ::Matrix3x4 matrix2 = AZ::Matrix3x4::CreateDiagonal(AZ::Vector3(1.3f, 1.5f, 0.4f)); - const AZ::Matrix3x4 matrix3 = AZ::Matrix3x4::CreateFromQuaternionAndTranslation( - AZ::Quaternion(0.42f, 0.46f, -0.66f, 0.42f), AZ::Vector3(2.8f, -3.7f, 1.6f)); - const AZ::Matrix3x4 matrix4 = AZ::Matrix3x4::CreateRotationX(-0.7f) * AZ::Matrix3x4::CreateScale(AZ::Vector3(0.6f, 1.3f, 0.7f)); - AZ::Matrix3x4 matrix5 = matrix1; - matrix5 += matrix4; - EXPECT_THAT(matrix1 + (matrix2 + matrix3), IsClose((matrix1 + matrix2) + matrix3)); - EXPECT_THAT(matrix2 + AZ::Matrix3x4::CreateZero(), IsClose(matrix2)); - EXPECT_THAT(matrix3 + AZ::Matrix3x4::CreateZero(), IsClose(AZ::Matrix3x4::CreateZero() + matrix3)); - EXPECT_THAT(matrix3 + matrix3, IsClose(matrix3 * 2.0f)); - EXPECT_THAT(matrix5, IsClose(matrix1 + matrix4)); + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 + m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + + m3 = m1; + m3 += m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(24.0f, 26.0f, 28.0f, 30.0f))); } - TEST(MATH_Matrix3x4, MultiplyByScalar) + TEST(MATH_Matrix3x4, TestDifference) { - const AZ::Vector4 row0(1.488f, 2.56f, 0.096f, 2.3f); - const AZ::Vector4 row1(0.384f, -1.92f, 0.428f, -1.6f); - const AZ::Vector4 row2(1.28f, -2.4f, -0.24f, 3.7f); - const float scalar = 3.2f; - const AZ::Vector4 row0Result = row0 * scalar; - const AZ::Vector4 row1Result = row1 * scalar; - const AZ::Vector4 row2Result = row2 * scalar; - AZ::Matrix3x4 matrix = AZ::Matrix3x4::CreateFromRows(row0, row1, row2); - EXPECT_THAT(matrix * 0.0f, IsClose(AZ::Matrix3x4::CreateZero())); - EXPECT_THAT(matrix * 1.0f, IsClose(matrix)); - EXPECT_THAT(matrix * scalar, IsClose(AZ::Matrix3x4::CreateFromRows(row0Result, row1Result, row2Result))); - EXPECT_THAT(matrix * 2.0f, IsClose(matrix + matrix)); + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 - m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + m3 = m1; + m3 -= m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + } + + TEST(MATH_Matrix3x4, TestScalarMultiplication) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 * 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = m1; + m3 *= 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = 2.0f * m1; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + } + + TEST(MATH_Matrix3x4, TestScalarDivision) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 / 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = m1; + m3 /= 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + } + + TEST(MATH_Matrix3x4, TestNegation) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-AZ::Matrix3x4::CreateZero(), IsClose(AZ::Matrix3x4::CreateZero())); + + AZ::Matrix3x4 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(AZ::Vector4(-1.0f, -2.0f, -3.0f, -4.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(AZ::Vector4(-5.0f, -6.0f, -7.0f, -8.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(AZ::Vector4(-9.0f, -10.0f, -11.0f, -12.0f))); + + AZ::Matrix3x4 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(AZ::Matrix3x4::CreateZero())); } TEST(MATH_Matrix3x4, MultiplyByVector3) diff --git a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp index 851de490d0..a9baa3ddea 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp @@ -246,16 +246,16 @@ namespace UnitTest m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); Matrix4x4 m3 = m1 * m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); - AZ_TEST_ASSERT(m3.GetRow(3).IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); Matrix4x4 m4 = m1; m4 *= m2; - AZ_TEST_ASSERT(m4.GetRow(0).IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); - AZ_TEST_ASSERT(m4.GetRow(1).IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); - AZ_TEST_ASSERT(m4.GetRow(2).IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); - AZ_TEST_ASSERT(m4.GetRow(3).IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); + EXPECT_THAT(m4.GetRow(0), IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); + EXPECT_THAT(m4.GetRow(3), IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); } TEST(MATH_Matrix4x4, TestVectorMultiplication) @@ -265,18 +265,148 @@ namespace UnitTest m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); - AZ_TEST_ASSERT((m1 * Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(18.0f, 46.0f, 74.0f))); - AZ_TEST_ASSERT((m1 * Vector4(1.0f, 2.0f, 3.0f, 4.0f)).IsClose(Vector4(30.0f, 70.0f, 110.0f, 150.0f))); - AZ_TEST_ASSERT(m1.TransposedMultiply3x3(Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(38.0f, 44.0f, 50.0f))); - AZ_TEST_ASSERT(m1.Multiply3x3(Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(14.0f, 38.0f, 62.0f))); + EXPECT_THAT((m1 * Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(18.0f, 46.0f, 74.0f))); + EXPECT_THAT((m1 * Vector4(1.0f, 2.0f, 3.0f, 4.0f)), IsClose(Vector4(30.0f, 70.0f, 110.0f, 150.0f))); + EXPECT_THAT(m1.TransposedMultiply3x3(Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(38.0f, 44.0f, 50.0f))); + EXPECT_THAT(m1.Multiply3x3(Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(14.0f, 38.0f, 62.0f))); Vector3 v1(1.0f, 2.0f, 3.0f); - AZ_TEST_ASSERT((v1 * m1).IsClose(Vector3(51.0f, 58.0f, 65.0f))); + EXPECT_THAT((v1 * m1), IsClose(Vector3(51.0f, 58.0f, 65.0f))); v1 *= m1; - AZ_TEST_ASSERT(v1.IsClose(Vector3(51.0f, 58.0f, 65.0f))); + EXPECT_THAT(v1, IsClose(Vector3(51.0f, 58.0f, 65.0f))); Vector4 v2(1.0f, 2.0f, 3.0f, 4.0f); - AZ_TEST_ASSERT((v2 * m1).IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + EXPECT_THAT((v2 * m1), IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); v2 *= m1; - AZ_TEST_ASSERT(v2.IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + EXPECT_THAT(v2, IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + } + + TEST(MATH_Matrix4x4, TestSum) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 + m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(32.0f, 34.0f, 36.0f, 38.0f))); + + m3 = m1; + m3 += m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(32.0f, 34.0f, 36.0f, 38.0f))); + } + + TEST(MATH_Matrix4x4, TestDifference) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 - m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + m3 = m1; + m3 -= m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + } + + TEST(MATH_Matrix4x4, TestScalarMultiplication) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 * 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = m1; + m3 *= 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = 2.0f * m1; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + } + + TEST(MATH_Matrix4x4, TestScalarDivision) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 / 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = m1; + m3 /= 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + } + + TEST(MATH_Matrix4x4, TestNegation) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-Matrix4x4::CreateZero(), IsClose(Matrix4x4::CreateZero())); + + Matrix4x4 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(Vector4(-1.0f, -2.0f, -3.0f, -4.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(Vector4(-5.0f, -6.0f, -7.0f, -8.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(Vector4(-9.0f, -10.0f, -11.0f, -12.0f))); + EXPECT_THAT(m2.GetRow(3), IsClose(Vector4(-13.0f, -14.0f, -15.0f, -16.0f))); + + Matrix4x4 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(Matrix4x4::CreateZero())); } TEST(MATH_Matrix4x4, TestTranspose) @@ -368,4 +498,36 @@ namespace UnitTest m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); AZ_TEST_ASSERT(m1.GetDiagonal() == Vector4(1.0f, 6.0f, 11.0f, 16.0f)); } + + TEST(MATH_Matrix4x4, TestScaleAccess) + { + Matrix4x4 m1 = Matrix4x4::CreateRotationX(DegToRad(40.0f)) * Matrix4x4::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.ExtractScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(3.0f, 4.0f, 5.0f))); + } + + TEST(MATH_Matrix4x4, TestScaleSqAccess) + { + Matrix4x4 m1 = Matrix4x4::CreateRotationX(DegToRad(40.0f)) * Matrix4x4::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(4.0f, 9.0f, 16.0f))); + m1.ExtractScale(); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(9.0f, 16.0f, 25.0f))); + } + + TEST(MATH_Matrix4x4, TestReciprocalScaled) + { + Matrix4x4 orthogonalMatrix = Matrix4x4::CreateRotationX(DegToRad(40.0f)); + EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix4x4 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + AZ::Matrix4x4 reciprocalScaledMatrix = orthogonalMatrix; + reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); + EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); + } } diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp index 35fa1136f9..e2e425fb57 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp @@ -69,7 +69,7 @@ namespace ScriptCanvasTesting void PropertyExample::In() { - for (auto& num : Numbers) + for ([[maybe_unused]] auto& num : Numbers) { AZ_TracePrintf("ScriptCanvas", "%f", num); } From 5a60cb15fc018ad3d4102ada557bee835687e6cf Mon Sep 17 00:00:00 2001 From: hnusrath <82476875+hnusrath@users.noreply.github.com> Date: Tue, 4 May 2021 19:15:36 +0100 Subject: [PATCH 050/112] Spec-5799 Add PhysX tests to Main Suite to run under 3 min (#368) * Spec-5799 Add PhysX tests to Main Suite to run under 3 min Adding 12 tests to Main Suite from Periodic Suite. Moved 1 test case to Sandbox Suite as it was failing and needs to be investigated. Run results on local : 12 passed, 1 warning in 172.31s (0:02:52) Test Case list in Main suite: test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies test_C4044459_Material_DynamicFriction test_C15425929_Undo_Redo test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers test_C14654881_CharacterController_SwitchLevels test_C17411467_AddPhysxRagdollComponent test_C12712453_ScriptCanvas_MultipleRaycastNode test_C4982593_PhysXCollider_CollisionLayerTest test_C18243586_Joints_HingeLeadFollowerCollide test_C19578021_ShapeCollider_CanBeAdded test_C4982803_Enable_PxMesh_Option Test moved to Sandbox Suite : test_C13895144_Ragdoll_ChangeLevel * Delete .gitignore * Revert "Delete .gitignore" This reverts commit 9540e000c85e2a2015fbb8251f0a3248494349b0. Revert the modification of adding the buildoutput folder. * Spec-5799:Fixing Cyclinder ShapeCollider test and adding it to Main Suite Changes : 1. Fixed and Added test C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain to TestSuite_Main.py and updated the level for the test. 2. Removed test test_C19578021_ShapeCollider_CanBeAdded from Main suite back to Periodic Suite * Update TestSuite_Periodic.py Adding xfail to test case test_C13895144_Ragdoll_ChangeLevel as the previous change had overridden Sean Cove's change with commit 95a44c481ad42f059f926f21072cedbc12210a3c * Update TestSuite_Sandbox.py Removing test case test_C13895144_Ragdoll_ChangeLevel and moving it to Periodic Suite as the previous change had overridden Sean Cove's change with commit 95a44c481ad42f059f926f21072cedbc12210a3c Co-authored-by: amzn-sean <75276488+amzn-sean@users.noreply.github.com> --- ...rShapeCollider_CollidesWithPhysXTerrain.py | 53 ++++++--- .../Gem/PythonTests/physics/TestSuite_Main.py | 57 +++++++++ .../PythonTests/physics/TestSuite_Periodic.py | 112 ++++++------------ .../PythonTests/physics/TestSuite_Sandbox.py | 98 +++++++-------- ...rShapeCollider_CollidesWithPhysXTerrain.ly | 4 +- 5 files changed, 179 insertions(+), 145 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py index d8e0a6769c..60fa9dc44d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py @@ -20,7 +20,10 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. class Tests(): enter_game_mode = ("Entered game mode", "Failed to enter game mode") find_cylinder = ("Cylinder entity found", "Cylinder entity not found") - find_terrain = ("Terrain found", "Terrain not found") + create_terrain = ("Terrain entity created successfully", "Failed to create Terrain Entity") + find_terrain = ("Terrain entity found", "Terrain entity not found") + add_physx_shape_collider = ("Added PhysX Shape Collider", "Failed to add PhysX Shape Collider") + add_box_shape = ("Added Box Shape", "Failed to add Box Shape") cylinder_above_terrain = ("Cylinder position above ground", "Cylinder is not above the ground") time_out = ("No time out occurred", "A time out occurred, please validate level setup") touched_ground = ("Touched ground before time out", "Did not touch ground before time out") @@ -40,11 +43,12 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): Once game mode is entered, the cylinder should fall toward and collide with the terrain. Steps: - 1) Open level and enter game mode - 2) Retrieve entities and positions - 3) Wait for cylinder to collide with terrain OR time out - 4) Exit game mode - 5) Close the editor + 1) Open level and create terrain Entity. + 2) Enter Game Mode. + 3) Retrieve entities and positions + 4) Wait for cylinder to collide with terrain OR time out + 5) Exit game mode + 6) Close the editor :return: """ @@ -54,29 +58,48 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): import ImportPathHelper as imports imports.init() - + from editor_python_test_tools.editor_entity_utils import EditorEntity import azlmbr.legacy.general as general import azlmbr.bus + import azlmbr.math as math from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper # Global time out TIME_OUT = 1.0 - # 1) Open level / Enter game mode + # 1) Open level helper.init_idle() helper.open_level("Physics", "C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain") + + # Create terrain entity + terrain = EditorEntity.create_editor_entity_at([30.0, 30.0, 33.96], "Terrain") + Report.result(Tests.create_terrain, terrain.id.IsValid()) + + terrain.add_component("PhysX Shape Collider") + Report.result(Tests.add_physx_shape_collider, terrain.has_component("PhysX Shape Collider")) + + box_shape_component = terrain.add_component("Box Shape") + Report.result(Tests.add_box_shape, terrain.has_component("Box Shape")) + + box_shape_component.set_component_property_value("Box Shape|Box Configuration|Dimensions", + math.Vector3(1024.0, 1024.0, 0.01)) + + # 2)Enter game mode helper.enter_game_mode(Tests.enter_game_mode) - # 2) Retrieve entities and positions + # 3) Retrieve entities and positions cylinder_id = general.find_game_entity("PhysX_Cylinder") Report.critical_result(Tests.find_cylinder, cylinder_id.IsValid()) + + + terrain_id = general.find_game_entity("Terrain") + Report.critical_result(Tests.find_terrain, terrain_id.IsValid()) - terrain_id = general.find_game_entity("PhysX_Terrain") - Report.critical_result(Tests.find_terrain, terrain_id.IsValid()) - cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", cylinder_id).GetPosition() - terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", terrain_id).GetPosition() + cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", cylinder_id) + #Cylinder position is 64,84,35 + terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", terrain_id) Report.info_vector3(cylinder_pos, "Cylinder:") Report.info_vector3(terrain_pos, "Terrain:") Report.critical_result( @@ -104,13 +127,13 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): handler.connect(cylinder_id) handler.add_callback("OnCollisionBegin", on_collision_begin) - # 3) Wait for the cylinder to hit the ground OR time out + # 4) Wait for the cylinder to hit the ground OR time out test_completed = helper.wait_for_condition((lambda: TouchGround.value), TIME_OUT) Report.critical_result(Tests.time_out, test_completed) Report.result(Tests.touched_ground, TouchGround.value) - # 4) Exit game mode + # 5) Exit game mode helper.exit_game_mode(Tests.exit_game_mode) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py index 67e855a00e..f81445fe03 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py @@ -34,4 +34,61 @@ class TestAutomation(TestAutomationBase): def test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC(self, request, workspace, editor, launcher_platform): from . import C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform): + from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform): + from . import C4044459_Material_DynamicFriction as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform): + from . import C15425929_Undo_Redo as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor, + launcher_platform): + from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform): + from . import C14654881_CharacterController_SwitchLevels as test_module + self._run_test(request, workspace, editor, test_module) + + def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform): + from . import C17411467_AddPhysxRagdollComponent as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform): + from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module + # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry') + def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform): + from . import C4982593_PhysXCollider_CollisionLayerTest as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform): + from . import C18243586_Joints_HingeLeadFollowerCollide as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform): + from . import C4982803_Enable_PxMesh_Option as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(self, request, workspace, editor, launcher_platform): + from . import C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain as test_module self._run_test(request, workspace, editor, test_module) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py index 39ed85a65a..4f91f539ee 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py @@ -52,11 +52,6 @@ class TestAutomation(TestAutomationBase): from . import C4976207_PhysXRigidBodies_KinematicBehavior as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform): - from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5932042_PhysXForceRegion_LinearDamping(self, request, workspace, editor, launcher_platform): from . import C5932042_PhysXForceRegion_LinearDamping as test_module @@ -92,11 +87,6 @@ class TestAutomation(TestAutomationBase): from . import C4976194_RigidBody_PhysXComponentIsValid as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform): - from . import C4044459_Material_DynamicFriction as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5932045_ForceRegion_Spline(self, request, workspace, editor, launcher_platform): from . import C5932045_ForceRegion_Spline as test_module @@ -208,26 +198,11 @@ class TestAutomation(TestAutomationBase): from . import C18981526_Material_RestitutionCombinePriority as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform): - from . import C15425929_Undo_Redo as test_module - self._run_test(request, workspace, editor, test_module) - - @revert_physics_config - def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform): - from . import C15308217_NoCrash_LevelSwitch as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C12868580_ForceRegion_SplineModifiedTransform(self, request, workspace, editor, launcher_platform): from . import C12868580_ForceRegion_SplineModifiedTransform as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor, launcher_platform): - from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C12712455_ScriptCanvas_ShapeCastVerification(self, request, workspace, editor, launcher_platform): from . import C12712455_ScriptCanvas_ShapeCastVerification as test_module @@ -248,17 +223,6 @@ class TestAutomation(TestAutomationBase): from . import C6131473_StaticSlice_OnDynamicSliceSpawn as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform): - from . import C4982798_Collider_ColliderRotationOffset as test_module - self._run_test(request, workspace, editor, test_module) - - @revert_physics_config - def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform): - from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module - # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5959808_ForceRegion_PositionOffset(self, request, workspace, editor, launcher_platform): from . import C5959808_ForceRegion_PositionOffset as test_module @@ -275,7 +239,7 @@ class TestAutomation(TestAutomationBase): def test_C13895144_Ragdoll_ChangeLevel(self, request, workspace, editor, launcher_platform): from . import C13895144_Ragdoll_ChangeLevel as test_module self._run_test(request, workspace, editor, test_module) - + @revert_physics_config def test_C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody(self, request, workspace, editor, launcher_platform): from . import C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody as test_module @@ -305,11 +269,6 @@ class TestAutomation(TestAutomationBase): from . import C5296614_PhysXMaterial_ColliderShape as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform): - from . import C6090547_ForceRegion_ParentChildForceRegions as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C4982595_Collider_TriggerDisablesCollision(self, request, workspace, editor, launcher_platform): from . import C4982595_Collider_TriggerDisablesCollision as test_module @@ -320,11 +279,6 @@ class TestAutomation(TestAutomationBase): from . import C14976307_Gravity_SetGravityWorks as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform): - from . import C14654881_CharacterController_SwitchLevels as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C15556261_PhysXMaterials_CharacterControllerMaterialAssignment(self, request, workspace, editor, launcher_platform): from . import C15556261_PhysXMaterials_CharacterControllerMaterialAssignment as test_module @@ -374,18 +328,6 @@ class TestAutomation(TestAutomationBase): from . import C4044461_Material_Restitution as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry') - def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform): - from . import C4982593_PhysXCollider_CollisionLayerTest as test_module - self._run_test(request, workspace, editor, test_module) - - @revert_physics_config - @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry') - def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform): - from . import C3510644_Collider_CollisionGroups as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config @fm.file_override('physxdefaultsceneconfiguration.setreg','C14902097_ScriptCanvas_PreUpdateEvent.setreg', 'AutomatedTesting/Registry') def test_C14902097_ScriptCanvas_PreUpdateEvent(self, request, workspace, editor, launcher_platform): @@ -415,11 +357,6 @@ class TestAutomation(TestAutomationBase): from . import C18243589_Joints_BallSoftLimitsConstrained as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform): - from . import C18243586_Joints_HingeLeadFollowerCollide as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C18243591_Joints_BallLeadFollowerCollide(self, request, workspace, editor, launcher_platform): from . import C18243591_Joints_BallLeadFollowerCollide as test_module @@ -441,21 +378,11 @@ class TestAutomation(TestAutomationBase): from . import C14861500_DefaultSetting_ColliderShape as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform): - from . import C19578021_ShapeCollider_CanBeAdded as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C19723164_ShapeCollider_WontCrashEditor(self, request, workspace, editor, launcher_platform): from . import C19723164_ShapeColliders_WontCrashEditor as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform): - from . import C4982803_Enable_PxMesh_Option as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C4982800_PhysXColliderShape_CanBeSelected(self, request, workspace, editor, launcher_platform): from . import C4982800_PhysXColliderShape_CanBeSelected as test_module @@ -471,10 +398,6 @@ class TestAutomation(TestAutomationBase): from . import C4982802_PhysXColliderShape_CanBeSelected as test_module self._run_test(request, workspace, editor, test_module) - def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform): - from . import C17411467_AddPhysxRagdollComponent as test_module - self._run_test(request, workspace, editor, test_module) - def test_C12905528_ForceRegion_WithNonTriggerCollider(self, request, workspace, editor, launcher_platform): from . import C12905528_ForceRegion_WithNonTriggerCollider as test_module # Fixme: expected_lines = ["[Warning] (PhysX Force Region) - Please ensure collider component marked as trigger exists in entity"] @@ -522,4 +445,35 @@ class TestAutomation(TestAutomationBase): def test_C100000_RigidBody_EnablingGravityWorksPoC(self, request, workspace, editor, launcher_platform): from . import C100000_RigidBody_EnablingGravityWorksPoC as test_module - self._run_test(request, workspace, editor, test_module) \ No newline at end of file + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry') + def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform): + from . import C3510644_Collider_CollisionGroups as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform): + from . import C4982798_Collider_ColliderRotationOffset as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform): + from . import C15308217_NoCrash_LevelSwitch as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform): + from . import C6090547_ForceRegion_ParentChildForceRegions as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform): + from . import C19578021_ShapeCollider_CanBeAdded as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform): + from . import C15425929_Undo_Redo as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py index 39bc4c8188..e829726ba9 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py @@ -1,49 +1,49 @@ -""" -All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -its licensors. - -For complete copyright and license terms please see the LICENSE at the root of this -distribution (the "License"). All use of this software is governed by the License, -or, if provided, by the license below or the license accompanying this file. Do not -remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -""" - -# This suite consists of all test cases that are passing and have been verified. - -import pytest -import os -import sys - -from .FileManagement import FileManagement as fm -from ly_test_tools import LAUNCHERS - -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - -from base import TestAutomationBase - - -revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry') - - -@pytest.mark.SUITE_sandbox -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -class TestAutomation(TestAutomationBase): - - ## Seems to be flaky, need to investigate - def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform): - from . import C19536274_GetCollisionName_PrintsName as test_module - # Fixme: expected_lines=["Layer Name: Right"] - self._run_test(request, workspace, editor, test_module) - - ## Seems to be flaky, need to investigate - def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform): - from . import C19536277_GetCollisionName_PrintsNothing as test_module - # All groups present in the PhysX Collider that could show up in test - # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"] - # Fixme: for group in collision_groups: - # Fixme: unexpected_lines.append(f"GroupName: {group}") - # Fixme: expected_lines=["GroupName: "] - self._run_test(request, workspace, editor, test_module) \ No newline at end of file +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +""" + +# This suite consists of all test cases that are passing and have been verified. + +import pytest +import os +import sys + +from .FileManagement import FileManagement as fm +from ly_test_tools import LAUNCHERS + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') + +from base import TestAutomationBase + + +revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry') + + +@pytest.mark.SUITE_sandbox +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + ## Seems to be flaky, need to investigate + def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform): + from . import C19536274_GetCollisionName_PrintsName as test_module + # Fixme: expected_lines=["Layer Name: Right"] + self._run_test(request, workspace, editor, test_module) + + ## Seems to be flaky, need to investigate + def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform): + from . import C19536277_GetCollisionName_PrintsNothing as test_module + # All groups present in the PhysX Collider that could show up in test + # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"] + # Fixme: for group in collision_groups: + # Fixme: unexpected_lines.append(f"GroupName: {group}") + # Fixme: expected_lines=["GroupName: "] + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly index ba141251d5..d618bf1873 100644 --- a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly +++ b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:231d5ac32c95334eeb1cbf77ea0bceae1d8010de3290dfdbd991abb46d18bae6 -size 6844 +oid sha256:83af66a6db4ff2b4df7212099b661a96668cfb326d8984e41b16506ec0062141 +size 5844 From 593528532ff13f4050e15dce3bf23d4d06c0f626 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 4 May 2021 14:36:48 -0500 Subject: [PATCH 051/112] Move g_mainViewportEntityDebugDisplayId from AzToolsFramework to AzFramework and rename it to g_defaultSceneEntityDebugDisplayId --- .../AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h | 2 ++ .../AzToolsFramework/Viewport/ViewportTypes.cpp | 2 -- .../AzToolsFramework/Viewport/ViewportTypes.h | 4 ---- Code/Sandbox/Editor/RenderViewport.cpp | 6 +++--- .../Objects/ComponentEntityObject.cpp | 2 +- .../ComponentEntityEditorPlugin/SandboxIntegration.cpp | 2 +- 6 files changed, 7 insertions(+), 11 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index f84f0276e1..776c7893ca 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -34,6 +34,8 @@ class ITexture; namespace AzFramework { + static constexpr const AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene + /// DebugDisplayRequests provides a debug draw api to be used by components and viewport features. class DebugDisplayRequests : public AZ::EBusTraits diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp index 12a0d6a8ab..8d26054562 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp @@ -19,8 +19,6 @@ namespace AzToolsFramework { namespace ViewportInteraction { - const AZ::s32 g_mainViewportEntityDebugDisplayId = AZ_CRC("MainViewportEntityDebugDisplayId", 0x58ae7fe8); - void ViewportInteractionReflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h index 161ca2d79f..d59044e68f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h @@ -256,9 +256,5 @@ namespace AzToolsFramework /// Reflect all viewport related types. void ViewportInteractionReflect(AZ::ReflectContext* context); - - /// The Id the main DebugDisplayRequestBus will be connected on. - extern const AZ::s32 g_mainViewportEntityDebugDisplayId; - } // namespace ViewportInteraction } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..29386a46b4 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -1105,7 +1105,7 @@ void CRenderViewport::Update() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = @@ -1535,7 +1535,7 @@ void CRenderViewport::OnRender() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = @@ -1681,7 +1681,7 @@ void CRenderViewport::RenderAll() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index 8f695c39ab..2357ba8561 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -907,7 +907,7 @@ void CComponentEntityObject::Display(DisplayContext& dc) AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..79d5fadf6c 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -167,7 +167,7 @@ void SandboxIntegrationManager::Setup() { m_debugDisplayBusImplementationActive = true; AzFramework::DebugDisplayRequestBus::Handler::BusConnect( - AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + AzFramework::g_defaultSceneEntityDebugDisplayId); } AzFramework::DisplayContextRequestBus::Handler::BusConnect(); From bba4867f718583954315d872331549537f17f294 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Tue, 4 May 2021 13:37:41 -0700 Subject: [PATCH 052/112] For got to add 012_Parallax_POM_Cutout.material --- .../012_Parallax_POM_Cutout.material | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material new file mode 100644 index 0000000000..fb862dc5d3 --- /dev/null +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material @@ -0,0 +1,26 @@ +{ + "description": "", + "materialType": "Materials/Types/StandardPBR.materialtype", + "parentMaterial": "", + "propertyLayoutVersion": 3, + "properties": { + "baseColor": { + "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_bc.png" + }, + "opacity": { + "alphaSource": "Split", + "mode": "Cutout", + "textureMap": "TestData/Textures/checker8x8_512.png" + }, + "parallax": { + "algorithm": "POM", + "enable": true, + "factor": 0.10000000149011612, + "quality": "High", + "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_disp.png" + }, + "uv": { + "scale": 0.5 + } + } +} \ No newline at end of file From afcbe4e02b64b5a4820f99a01d843a6f8a27f570 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 4 May 2021 13:51:08 -0700 Subject: [PATCH 053/112] Small updates based on PR feedback. --- .../AzCore/AzCore/Serialization/Json/JsonSerialization.h | 3 +++ .../Tests/Serialization/Json/BaseJsonSerializerTests.cpp | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h index b92eae7d6b..cf73d8dc56 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h @@ -49,6 +49,9 @@ namespace AZ //! Note on pointers: The Json Serialization assumes that are always constructed, so a default JSON value of "{}" is interpret as //! creating a new default instance even if the default value is a null pointer. A JSON Null needs to be explicitly stored in //! the JSON Document in order to default or explicitly set a pointer to null. + //! Note on pointer memory: Objects created/destroyed by the Json Serialization for pointers require that the AZ_CLASS_ALLOCATOR is + //! declared and the object is created using aznew or memory is allocated using azmalloc. Without these the application may + //! crash if the Json Serialization tries to create or destroy an object pointed to by a pointer. class JsonSerialization final { public: diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp index 62622ef7ab..08de21b54f 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp @@ -140,7 +140,7 @@ namespace JsonSerializationTests ASSERT_NE(nullptr, ptrValue); EXPECT_EQ(42, *ptrValue); - azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), alignof(int)); } TEST_F(BaseJsonSerializerTests, ContinueLoading_DefaultToNullPointer_ValueLoadedCorrectly) @@ -155,7 +155,7 @@ namespace JsonSerializationTests EXPECT_EQ(Processing::Completed, result.GetProcessing()); ASSERT_NE(nullptr, ptrValue); - azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), alignof(int)); } TEST_F(BaseJsonSerializerTests, ContinueLoading_NullDeletesObject_ValueLoadedCorrectly) @@ -163,7 +163,7 @@ namespace JsonSerializationTests using namespace AZ::JsonSerializationResult; rapidjson::Value json(rapidjson::kNullType); - int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), AZStd::alignment_of::value, AZ::SystemAllocator)); + int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), alignof(int), AZ::SystemAllocator)); ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); From 9e105fb7694b4fb8722b3a826919e409baab939f Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Tue, 4 May 2021 16:52:36 -0500 Subject: [PATCH 054/112] [LYN-3347] Removed some unused references to CSelectionGroup. --- Code/Sandbox/Editor/CryEdit.cpp | 54 -------------------- Code/Sandbox/Editor/CryEdit.h | 1 - Code/Sandbox/Editor/Export/ExportManager.cpp | 35 +------------ Code/Sandbox/Editor/Export/ExportManager.h | 4 -- Code/Sandbox/Editor/Grid.cpp | 21 -------- Code/Sandbox/Editor/GridSettingsDialog.cpp | 35 ------------- Code/Sandbox/Editor/GridSettingsDialog.h | 2 - Code/Sandbox/Editor/IEditorImpl.cpp | 23 --------- Code/Sandbox/Editor/MainWindow.cpp | 3 -- Code/Sandbox/Editor/RenderViewport.cpp | 17 ------ Code/Sandbox/Editor/Resource.h | 1 - 11 files changed, 1 insertion(+), 195 deletions(-) diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index abffd1f995..aa255e185d 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -451,7 +451,6 @@ void CCryEditApp::RegisterActionHandlers() #endif ON_COMMAND(ID_DISPLAY_GOTOPOSITION, OnDisplayGotoPosition) ON_COMMAND(ID_SNAPANGLE, OnSnapangle) - ON_COMMAND(ID_EDIT_RENAMEOBJECT, OnEditRenameobject) ON_COMMAND(ID_CHANGEMOVESPEED_INCREASE, OnChangemovespeedIncrease) ON_COMMAND(ID_CHANGEMOVESPEED_DECREASE, OnChangemovespeedDecrease) ON_COMMAND(ID_CHANGEMOVESPEED_CHANGESTEP, OnChangemovespeedChangestep) @@ -3824,59 +3823,6 @@ void CCryEditApp::OnUpdateSnapangle(QAction* action) action->setChecked(gSettings.pGrid->IsAngleSnapEnabled()); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnEditRenameobject() -{ - CSelectionGroup* pSelection = GetIEditor()->GetSelection(); - if (pSelection->IsEmpty()) - { - QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("No Selected Objects!")); - return; - } - - IObjectManager* pObjMan = GetIEditor()->GetObjectManager(); - - if (!pObjMan) - { - return; - } - - StringDlg dlg(QObject::tr("Rename Object(s)")); - if (dlg.exec() == QDialog::Accepted) - { - CUndo undo("Rename Objects"); - QString newName; - QString str = dlg.GetString(); - int num = 0; - - for (int i = 0; i < pSelection->GetCount(); ++i) - { - CBaseObject* pObject = pSelection->GetObject(i); - - if (pObject) - { - if (pObjMan->IsDuplicateObjectName(str)) - { - pObjMan->ShowDuplicationMsgWarning(pObject, str, true); - return; - } - } - } - - for (int i = 0; i < pSelection->GetCount(); ++i) - { - newName = QStringLiteral("%1%2").arg(str).arg(num); - ++num; - CBaseObject* pObject = pSelection->GetObject(i); - - if (pObject) - { - pObjMan->ChangeObjectName(pObject, newName); - } - } - } -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnChangemovespeedIncrease() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index bce7f0c90d..6faa167146 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -413,7 +413,6 @@ private: void OnDisplayGotoPosition(); void OnSnapangle(); void OnUpdateSnapangle(QAction* action); - void OnEditRenameobject(); void OnChangemovespeedIncrease(); void OnChangemovespeedDecrease(); void OnChangemovespeedChangestep(); diff --git a/Code/Sandbox/Editor/Export/ExportManager.cpp b/Code/Sandbox/Editor/Export/ExportManager.cpp index 638977b191..ddb8a38870 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.cpp +++ b/Code/Sandbox/Editor/Export/ExportManager.cpp @@ -1091,35 +1091,6 @@ bool CExportManager::AddSelectedEntityObjects() return true; } - -bool CExportManager::AddSelectedObjects() -{ - CSelectionGroup* pSelection = GetIEditor()->GetSelection(); - - int numObjects = pSelection->GetCount(); - if (numObjects > m_data.m_objects.size()) - { - m_data.m_objects.reserve(numObjects + 1); // +1 for terrain - } - // First run pipeline to precache geometry - m_isPrecaching = true; - for (int i = 0; i < numObjects; i++) - { - AddObject(pSelection->GetObject(i)); - } - - GetIEditor()->Get3DEngine()->ProposeContentPrecache(); - - // Repeat pipeline to collect geometry - m_isPrecaching = false; - for (int i = 0; i < numObjects; i++) - { - AddObject(pSelection->GetObject(i)); - } - - return true; -} - bool CExportManager::AddSelectedRegionObjects() { AABB box; @@ -1185,7 +1156,7 @@ bool CExportManager::ExportToFile(const char* filename, bool bClearDataAfterExpo } -bool CExportManager::Export(const char* defaultName, const char* defaultExt, const char* defaultPath, bool isSelectedObjects, bool isSelectedRegionObjects, bool isOccluder, bool bAnimationExport) +bool CExportManager::Export(const char* defaultName, const char* defaultExt, const char* defaultPath, [[maybe_unused]] bool isSelectedObjects, bool isSelectedRegionObjects, bool isOccluder, bool bAnimationExport) { m_bAnimationExport = bAnimationExport; @@ -1229,10 +1200,6 @@ bool CExportManager::Export(const char* defaultName, const char* defaultExt, con if (m_bAnimationExport || CFileUtil::SelectSaveFile(filters, defaultExt, defaultPath, newFilename)) { WaitCursor wait; - if (isSelectedObjects) - { - AddSelectedObjects(); - } if (isSelectedRegionObjects) { AddSelectedRegionObjects(); diff --git a/Code/Sandbox/Editor/Export/ExportManager.h b/Code/Sandbox/Editor/Export/ExportManager.h index a27e54b085..04ee5f73ca 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.h +++ b/Code/Sandbox/Editor/Export/ExportManager.h @@ -128,10 +128,6 @@ public: bool Export(const char* defaultName, const char* defaultExt = "", const char* defaultPath = "", bool isSelectedObjects = true, bool isSelectedRegionObjects = false, bool isOccluder = false, bool bAnimationExport = false); - //! Add to Export Data geometry from selected objects - //! return true if succeed, otherwise false - bool AddSelectedObjects(); - bool AddSelectedEntityObjects(); //! Add to Export Data geometry from objects inside selected region volume diff --git a/Code/Sandbox/Editor/Grid.cpp b/Code/Sandbox/Editor/Grid.cpp index aa9e980069..50702f8cb2 100644 --- a/Code/Sandbox/Editor/Grid.cpp +++ b/Code/Sandbox/Editor/Grid.cpp @@ -136,31 +136,10 @@ Matrix34 CGrid::GetMatrix() const Ang3 angles = Ang3(rotationAngles.x * gf_PI / 180.0, rotationAngles.y * gf_PI / 180.0, rotationAngles.z * gf_PI / 180.0); tm = Matrix33::CreateRotationXYZ(angles); - - if (gSettings.snap.bGridGetFromSelected) - { - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } - } } else if (GetIEditor()->GetReferenceCoordSys() == COORDS_LOCAL) { tm.SetIdentity(); - - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } } else { diff --git a/Code/Sandbox/Editor/GridSettingsDialog.cpp b/Code/Sandbox/Editor/GridSettingsDialog.cpp index b16dbe4197..ecabdc4e6a 100644 --- a/Code/Sandbox/Editor/GridSettingsDialog.cpp +++ b/Code/Sandbox/Editor/GridSettingsDialog.cpp @@ -39,8 +39,6 @@ CGridSettingsDialog::CGridSettingsDialog(QWidget* pParent /*=NULL*/) connect(ui->m_userDefined, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnUserDefined); connect(ui->m_getFromObject, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnGetFromObject); - connect(ui->m_getAnglesFromObject, &QPushButton::clicked, this, &CGridSettingsDialog::OnBnGetAngles); - connect(ui->m_getTranslationFromObject, &QPushButton::clicked, this, &CGridSettingsDialog::OnBnGetTranslation); auto doubleSpinBoxValueChanged = static_cast(&QDoubleSpinBox::valueChanged); @@ -115,39 +113,6 @@ void CGridSettingsDialog::OnBnGetFromObject() EnableGridPropertyControls(ui->m_userDefined->isChecked(), ui->m_getFromObject->isChecked()); } -void CGridSettingsDialog::OnBnGetAngles() -{ - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - Matrix34 tm = obj->GetWorldTM(); - AffineParts ap; - ap.SpectralDecompose(tm); - - Vec3 rotation = Vec3(RAD2DEG(Ang3::GetAnglesXYZ(Matrix33(ap.rot)))); - - ui->m_angleX->setValue(rotation.x); - ui->m_angleY->setValue(rotation.y); - ui->m_angleZ->setValue(rotation.z); - } -} - -void CGridSettingsDialog::OnBnGetTranslation() -{ - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - Matrix34 tm = obj->GetWorldTM(); - Vec3 translation = tm.GetTranslation(); - - ui->m_translationX->setValue(translation.x); - ui->m_translationY->setValue(translation.y); - ui->m_translationZ->setValue(translation.z); - } -} - void CGridSettingsDialog::EnableGridPropertyControls(const bool isUserDefined, const bool isGetFromObject) { ui->m_getFromObject->setEnabled(isUserDefined == true); diff --git a/Code/Sandbox/Editor/GridSettingsDialog.h b/Code/Sandbox/Editor/GridSettingsDialog.h index f82278ccb7..fe5934ec7e 100644 --- a/Code/Sandbox/Editor/GridSettingsDialog.h +++ b/Code/Sandbox/Editor/GridSettingsDialog.h @@ -51,8 +51,6 @@ private slots: void accept() override; void OnBnUserDefined(); void OnBnGetFromObject(); - void OnBnGetAngles(); - void OnBnGetTranslation(); void OnValueUpdate(); private: diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 61d24db90c..ff9ece339a 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -116,29 +116,6 @@ static CCryEditDoc * theDocument; #undef GetCommandLine -namespace -{ - bool SelectionContainsComponentEntities() - { - bool result = false; - CSelectionGroup* pSelection = GetIEditor()->GetObjectManager()->GetSelection(); - if (pSelection) - { - CBaseObject* selectedObj = nullptr; - for (int selectionCounter = 0; selectionCounter < pSelection->GetCount(); ++selectionCounter) - { - selectedObj = pSelection->GetObject(selectionCounter); - if (selectedObj->GetType() == OBJTYPE_AZENTITY) - { - result = true; - break; - } - } - } - return result; - } -} - const char* CEditorImpl::m_crashLogFileName = "SessionStatus/editor_statuses.json"; CEditorImpl::CEditorImpl() diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c266d37282..c54c31c5d5 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -884,9 +884,6 @@ void MainWindow::InitActions() .SetStatusTip(tr("Restore saved state (Fetch)")); // Modify actions - am->AddAction(ID_EDIT_RENAMEOBJECT, tr("Rename Object(s)...")) - .SetStatusTip(tr("Rename Object")); - am->AddAction(ID_EDITMODE_MOVE, tr("Move")) .SetIcon(Style::icon("Move")) .SetApplyHoverEffect() diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 3e726f2468..24913a7388 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -3959,18 +3959,6 @@ void CRenderViewport::RenderConstructionPlane() Ang3 angles = Ang3(pGrid->rotationAngles.x * gf_PI / 180.0, pGrid->rotationAngles.y * gf_PI / 180.0, pGrid->rotationAngles.z * gf_PI / 180.0); Matrix34 tm = Matrix33::CreateRotationXYZ(angles); - if (gSettings.snap.bGridGetFromSelected) - { - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } - } - u = tm * u; v = tm * v; } @@ -4025,11 +4013,6 @@ void CRenderViewport::RenderConstructionPlane() void CRenderViewport::RenderSnappingGrid() { // First, Check whether we should draw the grid or not. - CSelectionGroup* pSelGroup = GetIEditor()->GetSelection(); - if (pSelGroup == nullptr || pSelGroup->GetCount() != 1) - { - return; - } CGrid* pGrid = GetViewManager()->GetGrid(); if (pGrid->IsEnabled() == false && pGrid->IsAngleSnapEnabled() == false) { diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index 51f9b1f3e9..d9fdb42c0b 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -91,7 +91,6 @@ #define ID_EXPORT_INDOORS 32915 #define ID_VIEW_CYCLE2DVIEWPORT 32916 #define ID_SNAPANGLE 32917 -#define ID_EDIT_RENAMEOBJECT 32925 #define ID_CHANGEMOVESPEED_INCREASE 32928 #define ID_CHANGEMOVESPEED_DECREASE 32929 #define ID_CHANGEMOVESPEED_CHANGESTEP 32930 From f5f035122b7c61470961fcda226e3aa575b28c8e Mon Sep 17 00:00:00 2001 From: sharmajs-amzn <82233357+sharmajs-amzn@users.noreply.github.com> Date: Tue, 4 May 2021 15:00:02 -0700 Subject: [PATCH 055/112] {LYN-3229} Update AssImp package with latest AssImp 3rd party source changes (#545) (#554) --- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 620995a85b..4056242a47 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARG ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index 290508b348..e06eadcbea 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index bdc93d9a0e..939948d501 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) From 27472169e2c915d33f202b8fdc3adedaad8c1281 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 4 May 2021 17:06:22 -0500 Subject: [PATCH 056/112] Change global default scene debug draw id variale declare from static constexpr const to inline constexpr --- .../AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index 776c7893ca..fb6b8d7d72 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -34,7 +34,7 @@ class ITexture; namespace AzFramework { - static constexpr const AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene + inline constexpr AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene /// DebugDisplayRequests provides a debug draw api to be used by components and viewport features. class DebugDisplayRequests From 3b8264016ab5ef9a88256d49f47fbc447012b831 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 15:06:34 -0700 Subject: [PATCH 057/112] Updating testing --- .../Code/Tests/PhysXColliderPrefabTests.cpp | 157 ++++++++++++------ 1 file changed, 110 insertions(+), 47 deletions(-) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index d489ac2990..f6a913b61d 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -13,12 +13,12 @@ #include #include + #include -#include -#include -#include -#include -#include +#include +#include +#include +#include #include #include @@ -26,101 +26,164 @@ #include #include #include -#include -#include -#include -#include namespace PhysX { - class PhysXColliderPrefabTest + class PhysXColliderPrefabTests : public ::testing::Test { protected: - void SetUp() override - { - - } - - void TearDown() override - { - - } - - }; - TEST_F(PhysXColliderPrefabTest, JsonStoreAndLoadPhysicsObjectsWithPrefabTest) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesNotNull) { + //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; //material selection Physics::MaterialSelection materialSelection; - AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); + AZ::JsonSerializationResult::ResultCode result + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Material Selection", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); Physics::MaterialSelection newSelection; - AZ::JsonSerialization::Load(newSelection, prefabDom); + result = AZ::JsonSerialization::Load(newSelection, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_EQ(materialSelection.GetMaterialId(), newSelection.GetMaterialId()); //collider configuration Physics::ColliderConfiguration colliderConfig; - AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); Physics::ColliderConfiguration newConfig; - AZ::JsonSerialization::Load(newConfig, prefabDom); + result = AZ::JsonSerialization::Load(newConfig, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_EQ(colliderConfig.m_collisionLayer, newConfig.m_collisionLayer); + } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; //shared pointer - collider configuration - defaults only auto colliderConfigPtr = AZStd::make_shared(); AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); colliderConfigPtr = nullptr; - AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, colliderConfigPtr); + //shared pointer - shape configuration - defaults only + auto shapeConfigPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + shapeConfigPtr = nullptr; + result = AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, shapeConfigPtr); + + + } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_NonDefaultPhysicsTypes_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; + //shared pointer - collider configuration - non default auto updatedColliderConfigPtr = AZStd::make_shared(); updatedColliderConfigPtr->m_isTrigger = true; - AZ::JsonSerializationResult::ResultCode result2 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); updatedColliderConfigPtr = nullptr; - AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, updatedColliderConfigPtr); - //shared pointer - shape configuration - defaults only - auto shapeConfigPtr = AZStd::make_shared(); - AZ::JsonSerializationResult::ResultCode result3 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); - - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); - - shapeConfigPtr = nullptr; - AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); - - EXPECT_NE(nullptr, shapeConfigPtr); - //shared pointer - shape configuration - non default auto updatedShapeConfigPtr = AZStd::make_shared(); updatedShapeConfigPtr->m_radius = 2.0f; - AZ::JsonSerializationResult::ResultCode result4 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); updatedShapeConfigPtr = nullptr; - AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, updatedColliderConfigPtr); } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; + + //shared pointer - box collider - defaults only + auto boxColliderPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + boxColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(boxColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, boxColliderPtr); + + //shared pointer - sphere collider - defaults only + auto sphereColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + sphereColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(sphereColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, sphereColliderPtr); + + //shared pointer - capsule collider - defaults only + auto capsuleColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + capsuleColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(capsuleColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, capsuleColliderPtr); + + //shared pointer - shape collider - defaults only + auto shapeColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + shapeColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(shapeColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, shapeColliderPtr); + } } From 71039186ab353f32638e2baaf4c3091220e66bfb Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 4 May 2021 15:18:48 -0700 Subject: [PATCH 058/112] Removed RayTracingSceneSrg files from the .cmake file --- .../Feature/Common/Assets/atom_feature_common_asset_files.cmake | 2 -- 1 file changed, 2 deletions(-) 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 f14fb4f4a0..84ef494216 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 @@ -280,8 +280,6 @@ set(FILES ShaderLib/Atom/Features/Shadow/Shadow.azsli ShaderLib/Atom/Features/Shadow/ShadowmapAtlasLib.azsli ShaderLib/Atom/Features/Vertex/VertexHelper.azsli - ShaderResourceGroups/RayTracingSceneSrg.azsli - ShaderResourceGroups/RayTracingSceneSrgAll.azsli ShaderResourceGroups/SceneSrg.azsli ShaderResourceGroups/SceneSrgAll.azsli ShaderResourceGroups/SceneTimeSrg.azsli From 36e3c80df435b89c14124844741cf947ac7fa3de Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 15:41:23 -0700 Subject: [PATCH 059/112] Fixing spacing --- Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index f6a913b61d..4287ce17db 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -96,8 +96,6 @@ namespace PhysX EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, shapeConfigPtr); - - } TEST_F(PhysXColliderPrefabTests, StoreAndLoad_NonDefaultPhysicsTypes_PointersNotNull) From d4f19cb0b5ebbc06d701559b53823d4d9ecda353 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 4 May 2021 15:53:40 -0700 Subject: [PATCH 060/112] Fix Mac build --- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index e06eadcbea..e564d64fc3 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -47,5 +47,5 @@ ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-mac TARGETS mik ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-mac TARGETS googletest PACKAGE_HASH cbf020d5ef976c5db8b6e894c6c63151ade85ed98e7c502729dd20172acae5a8) ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac TARGETS GoogleBenchmark PACKAGE_HASH ad25de0146769c91e179953d845de2bec8ed4a691f973f47e3eb37639381f665) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-mac TARGETS OpenSSL PACKAGE_HASH 28adc1c0616ac0482b2a9d7b4a3a3635a1020e87b163f8aba687c501cf35f96c) -ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 4723ac43b19d4633c3fa4b9642f27c992d30cdc689f769f82869786f1c22a728) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) From e414cc151d4f941edfd4917b367eef22840f3bf8 Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 00:00:06 +0100 Subject: [PATCH 061/112] SPEC-6590 Implemented network entities instantiation by network spawnable asset ID --- .../Spawnable/SpawnableEntitiesInterface.h | 6 + .../Spawnable/SpawnableEntitiesManager.cpp | 21 +++ .../Spawnable/SpawnableEntitiesManager.h | 6 + .../NetworkEntity/NetworkEntityManager.cpp | 138 ++++++++++-------- .../NetworkEntity/NetworkEntityManager.h | 7 +- .../NetworkEntity/NetworkSpawnableLibrary.cpp | 1 - .../Pipeline/NetworkPrefabProcessor.cpp | 5 +- 7 files changed, 121 insertions(+), 63 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index ea19b3a0be..95d0b9e3a7 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -148,6 +148,12 @@ namespace AzFramework //! Blocks until all operations made on the provided ticket before the barrier call have completed. virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback) = 0; + //! Register a handler for OnSpawned events. + virtual void AddOnSpawnedHandler(AZ::Event>::Handler& handler) = 0; + + //! Register a handler for OnDespawned events. + virtual void AddOnDespawnedHandler(AZ::Event>::Handler& handler) = 0; + protected: [[nodiscard]] virtual void* CreateTicket(AZ::Data::Asset&& spawnable) = 0; virtual void DestroyTicket(void* ticket) = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 4e98616ef1..3ab004b516 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -114,6 +114,16 @@ namespace AzFramework } } + void SpawnableEntitiesManager::AddOnSpawnedHandler(AZ::Event>::Handler& handler) + { + handler.Connect(m_onSpawnedEvent); + } + + void SpawnableEntitiesManager::AddOnDespawnedHandler(AZ::Event>::Handler& handler) + { + handler.Connect(m_onDespawnedEvent); + } + auto SpawnableEntitiesManager::ProcessQueue() -> CommandQueueStatus { AZStd::queue pendingRequestQueue; @@ -223,6 +233,8 @@ namespace AzFramework ticket.m_spawnedEntities.begin() + spawnedEntitiesCount, ticket.m_spawnedEntities.end())); } + m_onSpawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -257,6 +269,8 @@ namespace AzFramework ticket.m_spawnedEntities.begin() + spawnedEntitiesCount, ticket.m_spawnedEntities.end())); } + m_onSpawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -289,6 +303,8 @@ namespace AzFramework request.m_completionCallback(*request.m_ticket); } + m_onDespawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -315,6 +331,8 @@ namespace AzFramework &GameEntityContextRequestBus::Events::DestroyGameEntityAndDescendants, entity->GetId()); } } + + m_onDespawnedEvent.Signal(ticket.m_spawnable); // Rebuild the list of entities. ticket.m_spawnedEntities.clear(); @@ -350,6 +368,9 @@ namespace AzFramework } ticket.m_currentTicketId++; + + m_onSpawnedEvent.Signal(ticket.m_spawnable); + return true; } else diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index 29e9ed797b..c70b9ccaa6 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -60,6 +60,9 @@ namespace AzFramework void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback) override; + void AddOnSpawnedHandler(AZ::Event>::Handler& handler) override; + void AddOnDespawnedHandler(AZ::Event>::Handler& handler) override; + // // The following function is thread safe but intended to be run from the main thread. // @@ -156,5 +159,8 @@ namespace AzFramework AZStd::deque m_delayedQueue; //!< Requests that were processed before, but couldn't be completed. AZStd::queue m_pendingRequestQueue; AZStd::mutex m_pendingRequestQueueMutex; + + AZ::Event> m_onSpawnedEvent; + AZ::Event> m_onDespawnedEvent; }; } // namespace AzFramework diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index d1701bbb89..3764b92b25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -34,9 +35,14 @@ namespace Multiplayer : m_networkEntityAuthorityTracker(*this) , m_removeEntitiesEvent([this] { RemoveEntities(); }, AZ::Name("NetworkEntityManager remove entities event")) , m_updateEntityDomainEvent([this] { UpdateEntityDomain(); }, AZ::Name("NetworkEntityManager update entity domain event")) + , m_onSpawnedHandler([this](AZ::Data::Asset spawnable) { this->OnSpawned(spawnable); }) + , m_onDespawnedHandler([this](AZ::Data::Asset spawnable) { this->OnDespawned(spawnable); }) { AZ::Interface::Register(this); AzFramework::RootSpawnableNotificationBus::Handler::BusConnect(); + + AzFramework::SpawnableEntitiesInterface::Get()->AddOnSpawnedHandler(m_onSpawnedHandler); + AzFramework::SpawnableEntitiesInterface::Get()->AddOnDespawnedHandler(m_onDespawnedHandler); } NetworkEntityManager::~NetworkEntityManager() @@ -365,58 +371,57 @@ namespace Multiplayer { INetworkEntityManager::EntityList returnList; - // TODO: Implement for non-root spawnables auto spawnableAssetId = m_networkPrefabLibrary.GetAssetIdByName(prefabEntryId.m_prefabName); - if (spawnableAssetId == m_rootSpawnableAsset.GetId()) + // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary + auto netSpawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(spawnableAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(netSpawnableAsset); + + AzFramework::Spawnable* netSpawnable = netSpawnableAsset.GetAs(); + if (!netSpawnable) { - AzFramework::Spawnable* netSpawnable = m_rootSpawnableAsset.GetAs(); - if (!netSpawnable) + return returnList; + } + + const uint32_t entityIndex = prefabEntryId.m_entityOffset; + + if (entityIndex == PrefabEntityId::AllIndices) + { + return CreateEntitiesImmediate(*netSpawnable, netEntityRole); + } + + const AzFramework::Spawnable::EntityList& entities = netSpawnable->GetEntities(); + size_t entitiesSize = entities.size(); + if (entityIndex >= entitiesSize) + { + return returnList; + } + + AZ::SerializeContext* serializeContext = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + + AZ::Entity* clone = serializeContext->CloneObject(entities[entityIndex].get()); + AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); + clone->SetId(AZ::Entity::MakeId()); + + NetBindComponent* netBindComponent = clone->FindComponent(); + if (netBindComponent) + { + netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); + + auto* transformComponent = clone->FindComponent(); + if (transformComponent) { - return returnList; + transformComponent->SetWorldTM(transform); } - const uint32_t entityIndex = prefabEntryId.m_entityOffset; - - if (entityIndex == PrefabEntityId::AllIndices) + if (autoActivate == AutoActivate::DoNotActivate) { - return CreateEntitiesImmediate(*netSpawnable, netEntityRole); + clone->SetRuntimeActiveByDefault(false); } - const AzFramework::Spawnable::EntityList& entities = netSpawnable->GetEntities(); - size_t entitiesSize = entities.size(); - if (entityIndex >= entitiesSize) - { - return returnList; - } + AzFramework::GameEntityContextRequestBus::Broadcast(&AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); - - AZ::Entity* clone = serializeContext->CloneObject(entities[entityIndex].get()); - AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); - clone->SetId(AZ::Entity::MakeId()); - - NetBindComponent* netBindComponent = clone->FindComponent(); - if (netBindComponent) - { - netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); - - auto* transformComponent = clone->FindComponent(); - if (transformComponent) - { - transformComponent->SetWorldTM(transform); - } - - if (autoActivate == AutoActivate::DoNotActivate) - { - clone->SetRuntimeActiveByDefault(false); - } - - AzFramework::GameEntityContextRequestBus::Broadcast( - &AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); - - returnList.push_back(netBindComponent->GetEntityHandle()); - } + returnList.push_back(netBindComponent->GetEntityHandle()); } return returnList; @@ -429,13 +434,37 @@ namespace Multiplayer } void NetworkEntityManager::OnRootSpawnableAssigned( - AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) + [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { - AzFramework::Spawnable* rootSpawnableData = rootSpawnable.GetAs(); - const auto& entityList = rootSpawnableData->GetEntities(); + auto* multiplayer = AZ::Interface::Get(); + const auto agentType = multiplayer->GetAgentType(); + + if (agentType == MultiplayerAgentType::Client) + { + multiplayer->SendReadyForEntityUpdates(true); + } + } + + void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) + { + // TODO: Do we need to clear all entities here? + auto* multiplayer = AZ::Interface::Get(); + const auto agentType = multiplayer->GetAgentType(); + + if (agentType == MultiplayerAgentType::Client) + { + multiplayer->SendReadyForEntityUpdates(false); + } + } + + void NetworkEntityManager::OnSpawned(AZ::Data::Asset spawnable) + { + AzFramework::Spawnable* spawnableData = spawnable.GetAs(); + const auto& entityList = spawnableData->GetEntities(); if (entityList.size() == 0) { - AZ_Error("NetworkEntityManager", false, "OnRootSpawnableAssigned: Root spawnable doesn't have any entities."); + AZ_Error("NetworkEntityManager", false, "OnSpawned: Spawnable %s doesn't have any entities.", + spawnable.GetHint().c_str()); return; } @@ -443,7 +472,7 @@ namespace Multiplayer auto* spawnableHolder = rootEntity->FindComponent(); if (!spawnableHolder) { - AZ_Error("NetworkEntityManager", false, "OnRootSpawnableAssigned: Root entity doesn't have NetworkSpawnableHolderComponent."); + // Root entity doesn't have NetworkSpawnableHolderComponent. It means there's no corresponding network spawnable. return; } @@ -465,8 +494,6 @@ namespace Multiplayer return; } - m_rootSpawnableAsset = netSpawnableAsset; - auto* multiplayer = AZ::Interface::Get(); const auto agentType = multiplayer->GetAgentType(); @@ -477,17 +504,10 @@ namespace Multiplayer { CreateEntitiesImmediate(*netSpawnable, NetEntityRole::Authority); } - else - { - // If we don't spawn net entities immediately (i.e. it is a client), - // tell the server/host it can start sending updates that will instantiate entities. - multiplayer->SendReadyForEntityUpdates(true); - } } - void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) + void NetworkEntityManager::OnDespawned([[maybe_unused]]AZ::Data::Asset spawnable) { - // TODO: Do we need to clear all entities here? - m_rootSpawnableAsset.Release(); + // TODO: Remove entities instantiated from the spawnable } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index 142730188b..4439503373 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -84,6 +84,9 @@ namespace Multiplayer NetEntityId NextId(); + void OnSpawned(AZ::Data::Asset spawnable); + void OnDespawned(AZ::Data::Asset spawnable); + NetworkEntityTracker m_networkEntityTracker; NetworkEntityAuthorityTracker m_networkEntityAuthorityTracker; MultiplayerComponentRegistry m_multiplayerComponentRegistry; @@ -111,6 +114,8 @@ namespace Multiplayer DeferredRpcMessages m_localDeferredRpcMessages; NetworkSpawnableLibrary m_networkPrefabLibrary; - AZ::Data::Asset m_rootSpawnableAsset; + + AZ::Event>::Handler m_onSpawnedHandler; + AZ::Event>::Handler m_onDespawnedHandler; }; } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp index ad2e18e222..ebf5d2609b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp @@ -46,7 +46,6 @@ namespace Multiplayer const AZ::Name name = AZ::Name(relativePath); m_spawnables[name] = id; m_spawnablesReverseLookup[id] = name; - } void NetworkSpawnableLibrary::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 2006272135..4962d16fb4 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -104,9 +104,10 @@ namespace Multiplayer networkedEntityIds.push_back(sourceEntity->GetId()); } } - if (!PrefabDomUtils::StoreInstanceInPrefabDom(*sourceInstance, prefab)) + + if (networkedEntityIds.empty()) { - AZ_Error("NetworkPrefabProcessor", false, "Saving exported Prefab Instance within a Prefab Dom failed."); + // No networked entities in the prefab, no need to do anything in this processor. return; } From 88b524d868ab61369e74334823f858a46e2da158 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Tue, 4 May 2021 16:00:06 -0700 Subject: [PATCH 062/112] ATOM-14495 "POM Height Bias" (continued) Added Height Offset support to StandardMultilayerPBR.materialtype. In order to make this work, I updated the GetDepth callback function to support the option of returning absolute depth values rather than relative depth values. Although I could have done transformations inside the GetDepth function, having this as absolute cleans things up a lot. StandardMultilayerPBR_Parallax.lua functor code now populates the MaterialSRG with displacement min/max values, instead of having to normalize the depth factors for each layer. I think this is easier to understand and work with. Added Height Offset to each layer of StandardMultilayerPBR. Updated the naming and description for the parallax factor in each layer, to match the other material types. I removed the global "factor" material property because it doesn't seem applicable anymore since we have per-layer height offset. We can always add some form of this later if customers ask for it. Squashed commit of the following: commit 8df460800ff7058f9fbb01f995efdd5ab53d3d2c Author: Chris Santora Date: Tue May 4 13:35:27 2021 -0700 Found a workaround for the DXC compiler bug commit 5d81617285eb42bb7b48eb060234d2cb89249e34 Author: Chris Santora Date: Tue May 4 12:27:22 2021 -0700 Local WIP changes to get a DepthResult struct set up for the GetDepth functions. --- .../Materials/Types/EnhancedPBR_Common.azsli | 2 +- .../Types/EnhancedPBR_ForwardPass.azsl | 2 +- .../Types/StandardMultilayerPBR.materialtype | 75 ++++++--- .../Types/StandardMultilayerPBR_Common.azsli | 21 ++- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 5 +- .../StandardMultilayerPBR_ForwardPass.azsl | 16 +- .../Types/StandardMultilayerPBR_Parallax.lua | 52 ++++--- ...StandardMultilayerPBR_ParallaxPerLayer.lua | 3 +- ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 5 +- .../Materials/Types/StandardPBR_Common.azsli | 3 +- .../Types/StandardPBR_ForwardPass.azsl | 2 +- .../Atom/Features/ParallaxMapping.azsli | 146 ++++++++++++++---- .../Types/AutoBrick_ForwardPass.azsl | 4 +- 13 files changed, 244 insertions(+), 92 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli index 314f15e8e1..4fc98dcf8b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli @@ -105,7 +105,7 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 09a16556d6..173312c82e 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -193,7 +193,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_parallax_highlightClipping && displacementIsClipped) { - baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + ApplyParallaxClippingHighlight(baseColor); } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 780a055c78..e2119dcf12 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -356,19 +356,6 @@ "id": "m_parallaxUvIndex" } }, - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values for all layers.", - "type": "Float", - "defaultValue": 1.0, - "min": 0.0, - "softMax": 2.0, - "connection": { - "type": "ShaderInput", - "id": "m_parallaxMainDepthFactor" - } - }, { "id": "algorithm", "displayName": "Algorithm", @@ -403,6 +390,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "uv": [ @@ -1271,8 +1269,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -1282,6 +1280,19 @@ "id": "m_layer1_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer1_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -1964,8 +1975,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -1975,6 +1986,19 @@ "id": "m_layer2_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer2_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -2657,8 +2681,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -2668,6 +2692,19 @@ "id": "m_layer3_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer3_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index 93cf9fdb7c..ba0eaf2ac1 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -60,7 +60,10 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial float4 m_pad3; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. uint m_parallaxUvIndex; - float m_parallaxMainDepthFactor; + + // These are used to limit the heightmap intersection search range to the narrowest band possible, to give the best quality result. + float m_displacementMin; // The lowest displacement value possible from all layers combined + float m_displacementMax; // The highest displacement value possible from all layers combined float3x3 m_uvMatrix; float4 m_pad4; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. @@ -211,7 +214,7 @@ void GetDepth_Setup(float3 vertexBlendMask) } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { float3 layerDepthValues = float3(0,0,0); @@ -223,8 +226,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer1_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.r = SampleDepthOrHeightMap(MaterialSrg::m_layer1_m_depthInverted, MaterialSrg::m_layer1_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.r = SampleDepthOrHeightMap(MaterialSrg::m_layer1_m_depthInverted, MaterialSrg::m_layer1_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.r *= MaterialSrg::m_layer1_m_depthFactor; + layerDepthValues.r -= MaterialSrg::m_layer1_m_depthOffset; } if(o_layer2_o_useDepthMap) @@ -235,8 +239,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer2_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.g = SampleDepthOrHeightMap(MaterialSrg::m_layer2_m_depthInverted, MaterialSrg::m_layer2_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.g = SampleDepthOrHeightMap(MaterialSrg::m_layer2_m_depthInverted, MaterialSrg::m_layer2_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.g *= MaterialSrg::m_layer2_m_depthFactor; + layerDepthValues.g -= MaterialSrg::m_layer2_m_depthOffset; } if(o_layer3_o_useDepthMap) @@ -247,8 +252,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer3_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.b = SampleDepthOrHeightMap(MaterialSrg::m_layer3_m_depthInverted, MaterialSrg::m_layer3_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.b = SampleDepthOrHeightMap(MaterialSrg::m_layer3_m_depthInverted, MaterialSrg::m_layer3_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.b *= MaterialSrg::m_layer3_m_depthFactor; + layerDepthValues.b -= MaterialSrg::m_layer3_m_depthOffset; } // Note, when the blend source is BlendMaskSource::VertexColors, parallax will not be able to blend correctly between layers. It will end up using the same blend mask values @@ -256,7 +262,6 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) // you have a small depth factor relative to the size of the blend transition. float3 blendMaskValues = GetBlendMaskValues(uv, s_blendMaskFromVertexStream); - float3 depth = BlendLayers(layerDepthValues.r, layerDepthValues.g, layerDepthValues.b, blendMaskValues); - - return depth; + float depth = BlendLayers(layerDepthValues.r, layerDepthValues.g, layerDepthValues.b, blendMaskValues); + return DepthResultAbsolute(depth); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index bc8045f412..ae156d7313 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -115,8 +115,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index 3f49152c1c..df7ca7dc16 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -148,12 +148,14 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_debugDrawMode == DebugDrawMode::DepthMaps) { GetDepth_Setup(IN.m_blendMask); - float depth = GetDepth(IN.m_uv[MaterialSrg::m_parallaxUvIndex], float2(0,0), float2(0,0)); + float depth = GetNormalizedDepth(-MaterialSrg::m_displacementMax, -MaterialSrg::m_displacementMin, IN.m_uv[MaterialSrg::m_parallaxUvIndex], float2(0,0), float2(0,0)); return MakeDebugOutput(IN, float3(depth,depth,depth)); } // ------- Parallax ------- + bool displacementIsClipped = false; + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(ShouldHandleParallax()) { @@ -162,10 +164,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -227,6 +230,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 layer2_baseColor = BlendBaseColor(layer2_sampledColor, MaterialSrg::m_layer2_m_baseColor.rgb, MaterialSrg::m_layer2_m_baseColorFactor, o_layer2_o_baseColorTextureBlendMode, o_layer2_o_baseColor_useTexture); float3 layer3_baseColor = BlendBaseColor(layer3_sampledColor, MaterialSrg::m_layer3_m_baseColor.rgb, MaterialSrg::m_layer3_m_baseColorFactor, o_layer3_o_baseColorTextureBlendMode, o_layer3_o_baseColor_useTexture); float3 baseColor = BlendLayers(layer1_baseColor, layer2_baseColor, layer3_baseColor, blendMaskValues); + + if(o_parallax_highlightClipping && displacementIsClipped) + { + ApplyParallaxClippingHighlight(baseColor); + } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua index 522121c96f..8880a4b842 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua @@ -20,10 +20,12 @@ function GetMaterialPropertyDependencies() "layer1_parallax.enable", "layer2_parallax.enable", "layer3_parallax.enable", - "parallax.factor", "layer1_parallax.factor", "layer2_parallax.factor", - "layer3_parallax.factor" + "layer3_parallax.factor", + "layer1_parallax.offset", + "layer2_parallax.offset", + "layer3_parallax.offset" } end @@ -31,6 +33,23 @@ function GetShaderOptionDependencies() return {"o_parallax_feature_enabled"} end +function MergeRange(heightMinMax, offset, factor) + top = offset + bottom = offset - factor + + if(heightMinMax[1] == nil) then + heightMinMax[1] = top + else + heightMinMax[1] = math.max(heightMinMax[1], top) + end + + if(heightMinMax[0] == nil) then + heightMinMax[0] = bottom + else + heightMinMax[0] = math.min(heightMinMax[0], bottom) + end +end + function Process(context) local enableParallax = context:GetMaterialPropertyValue_bool("parallax.enable") local enable1 = context:GetMaterialPropertyValue_bool("layer1_parallax.enable") @@ -39,30 +58,25 @@ function Process(context) enableParallax = enableParallax and (enable1 or enable2 or enable3) context:SetShaderOptionValue_bool("o_parallax_feature_enabled", enableParallax) - -- Smaller values for the main parallax factor used in GetParallaxOffset() give better quality. - -- So increase the per-layer parallax factors by normalizing them, and reduce the main factor accordingly. if(enableParallax) then local factorLayer1 = context:GetMaterialPropertyValue_float("layer1_parallax.factor") local factorLayer2 = context:GetMaterialPropertyValue_float("layer2_parallax.factor") local factorLayer3 = context:GetMaterialPropertyValue_float("layer3_parallax.factor") - local mainFactor = context:GetMaterialPropertyValue_float("parallax.factor") - maxLayerFactor = 0.0 - if(enable1) then maxLayerFactor = math.max(maxLayerFactor, factorLayer1) end - if(enable2) then maxLayerFactor = math.max(maxLayerFactor, factorLayer2) end - if(enable3) then maxLayerFactor = math.max(maxLayerFactor, factorLayer3) end + local offsetLayer1 = context:GetMaterialPropertyValue_float("layer1_parallax.offset") + local offsetLayer2 = context:GetMaterialPropertyValue_float("layer2_parallax.offset") + local offsetLayer3 = context:GetMaterialPropertyValue_float("layer3_parallax.offset") - if(maxLayerFactor < 0.0001) then + local heightMinMax = {nil, nil} + if(enable1) then MergeRange(heightMinMax, offsetLayer1, factorLayer1) end + if(enable2) then MergeRange(heightMinMax, offsetLayer2, factorLayer2) end + if(enable3) then MergeRange(heightMinMax, offsetLayer3, factorLayer3) end + + if(heightMinMax[1] - heightMinMax[0] < 0.0001) then context:SetShaderOptionValue_bool("o_parallax_feature_enabled", false) else - factorLayer1 = factorLayer1 / maxLayerFactor - factorLayer2 = factorLayer2 / maxLayerFactor - factorLayer3 = factorLayer3 / maxLayerFactor - mainFactor = mainFactor * maxLayerFactor; - context:SetShaderConstant_float("m_layer1_m_depthFactor", factorLayer1) - context:SetShaderConstant_float("m_layer2_m_depthFactor", factorLayer2) - context:SetShaderConstant_float("m_layer3_m_depthFactor", factorLayer3) - context:SetShaderConstant_float("m_parallaxMainDepthFactor", mainFactor) + context:SetShaderConstant_float("m_displacementMin", heightMinMax[0]) + context:SetShaderConstant_float("m_displacementMax", heightMinMax[1]) end end end @@ -76,8 +90,8 @@ function ProcessEditor(context) end context:SetMaterialPropertyVisibility("parallax.parallaxUv", visibility) - context:SetMaterialPropertyVisibility("parallax.factor", visibility) context:SetMaterialPropertyVisibility("parallax.algorithm", visibility) context:SetMaterialPropertyVisibility("parallax.quality", visibility) context:SetMaterialPropertyVisibility("parallax.pdo", visibility) + context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua index a1695e827b..119dfed436 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua @@ -42,7 +42,8 @@ function ProcessEditor(context) if(not enable or textureMap == nil) then visibility = MaterialPropertyVisibility_Hidden end - + context:SetMaterialPropertyVisibility("parallax.factor", visibility) + context:SetMaterialPropertyVisibility("parallax.offset", visibility) context:SetMaterialPropertyVisibility("parallax.invert", visibility) end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 6fa721ef47..325937b228 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -114,8 +114,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index ee1533cf16..2e2ad742cb 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -94,11 +94,12 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } + COMMON_OPTIONS_PARALLAX() bool ShouldHandleParallax() diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 4d12eb181d..acc355bc41 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -157,7 +157,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_parallax_highlightClipping && displacementIsClipped) { - baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + ApplyParallaxClippingHighlight(baseColor); } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 8027443f9a..1d2beb0f10 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -23,25 +23,104 @@ option bool o_parallax_feature_enabled; option bool o_parallax_highlightClipping; option bool o_parallax_shadow; +// I tried to make this an enum class, but ran into some DXC bug when compiling to SPIRV. +enum DepthResultCode +{ + DepthResultCode_Invalid, + DepthResultCode_Normalized, //!< The result is in range [0,1], where 0 is the top of the heightmap and 1 is the bottom of the heightmap. + DepthResultCode_Absolute //!< The result is tangent space units (the same as world units if there's no mesh scaling), where 0 is at the mesh surface and positive values are below the surface. +}; + +//! The return value for the GetDepth() callback function below. +struct DepthResult +{ + DepthResultCode m_resultCode; + float m_depth; +}; + +//! Convenience function for making a DepthResult with Code::Normalized +DepthResult DepthResultNormalized(float depth) +{ + DepthResult result; + result.m_resultCode = DepthResultCode_Normalized; + result.m_depth = depth; + return result; +} + +//! Convenience function for making a DepthResult with Code::Absolute +DepthResult DepthResultAbsolute(float depth) +{ + DepthResult result; + result.m_resultCode = DepthResultCode_Absolute; + result.m_depth = depth; + return result; +} + //! The client shader must define this function. //! This allows the client shader to implement special depth map sampling, for example procedurally generating or blending depth maps. +//! In simple cases though, the implementation of GetDepth() can simply call SampleDepthOrHeightMap(). //! @param uv the UV coordinates to use for sampling //! @param uv_ddx will be set to ddx_fine(uv) //! @param uv_ddy will be set to ddy_fine(uv) -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy); +//! @return see struct DepthResult +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy); //! Convenience function that can be used to implement GetDepth(). //! @param isHeightmap indicates whether to sample the map is a height map rather than a depth map. -float SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) +//! @return see struct DepthResult. In this case it will always contain a Code::Normalized result. +DepthResult SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) { - return abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); + DepthResult result; + result.m_resultCode = DepthResultCode_Normalized; + result.m_depth = abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); + return result; } -float GetClampedDepth(float minSampledDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +//! Calls GetDepth() and then normalizes the result if it isn't normalized already. +//! @param startDepth is the high point, which corresponds to a normalized depth value of 0. +//! @param stopDepth is the low point, which corresponds to a normalized depth value of 1. +//! @param inverseDepthRange is an optimization, and must be set to "1.0 / (stopDepth - startDepth)". +//! @param uv the UV coordinates to use for sampling +//! @param uv_ddx must be set to ddx_fine(uv) +//! @param uv_ddy must be set to ddy_fine(uv) +//! @param a depth value in the range [0,1] +float GetNormalizedDepth(float startDepth, float stopDepth, float inverseDepthRange, float2 uv, float2 uv_ddx, float2 uv_ddy) { - float sampledDepthValue = GetDepth(uv, uv_ddx, uv_ddy); - sampledDepthValue = max(sampledDepthValue, minSampledDepth); - return sampledDepthValue; + // startDepth can be less than 0, representing a displacement above the mesh surface. + // But since we don't currently support any vertex displacement, negative depth values would cause various + // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax + // surfaces disappearing at low angles. So we clamp all depth values to a minimum of 0. + + float normalizedDepth = 0.0; + + DepthResult depthResult = GetDepth(uv, uv_ddx, uv_ddy); + + if(stopDepth - startDepth > 0.0001) + { + if(DepthResultCode_Normalized == depthResult.m_resultCode) + { + float minNormalizedDepth = -startDepth * inverseDepthRange; + normalizedDepth = max(depthResult.m_depth, minNormalizedDepth); + } + else if(DepthResultCode_Absolute == depthResult.m_resultCode) + { + float clampedAbsoluteDepth = max(depthResult.m_depth, 0.0); + normalizedDepth = (clampedAbsoluteDepth - startDepth) * inverseDepthRange; + } + } + + return normalizedDepth; +} + +float GetNormalizedDepth(float startDepth, float stopDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +{ + float inverseDepthRange = 1.0 / (stopDepth - startDepth); + return GetNormalizedDepth(startDepth, stopDepth, inverseDepthRange, uv, uv_ddx, uv_ddy); +} + +void ApplyParallaxClippingHighlight(inout float3 baseColor) +{ + baseColor = lerp(baseColor, float3(1.0, 0.0, 1.0), 0.5); } struct ParallaxOffset @@ -55,7 +134,7 @@ struct ParallaxOffset ParallaxOffset BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) { // the amount to shift - float2 delta = dirToCameraTS.xy * GetDepth(uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; + float2 delta = dirToCameraTS.xy * GetNormalizedDepth(0, depthFactor, uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; ParallaxOffset result; @@ -89,25 +168,23 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo float2 ddx_uv = ddx_fine(uv); float2 ddy_uv = ddy_fine(uv); + + float depthSearchStart = -depthOffset; + float depthSearchEnd = depthSearchStart + depthFactor; + float inverseDepthFactor = 1.0 / depthFactor; + // This is the relative position at which we begin searching for intersection. // It is adjusted according to the depthOffset, raising or lowering the whole surface by depthOffset units. float3 parallaxOffset = dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; - // Note that depthOffset can raise the heightmap toward (and potentially above) the surface of the mesh. - // We will clamp the heightmap samples to prevent displacements that lie above the surface, which would cause various - // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax - // surfaces disappearing at low angles. - float minSampledDepth = depthOffset / depthFactor; - minSampledDepth = clamp(minSampledDepth, 0, 1); - // Get an initial heightmap sample to start the intersection search, starting at our initial parallaxOffset position. - float currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + float currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); float prevSample; - // Note that when depthOffset > 0, we could actually narrow the search so that instead of going through the entire [0,1] range - // of the heightmap, we could go through the range [minSampledDepth,1]. This would give more accurate results and fewer artifacts - // in case where depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. + // Note that when depthOffset < 0, we could actually narrow the search so that instead of going through the entire [depthSearchStart,depthSearchEnd] range + // of the heightmap, we could go through the range [0,depthSearchEnd]. This would give more accurate results and fewer artifacts + // in case where the magnitude of depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. // Do a basic search for the intersect step while(currentSample > currentStep) @@ -116,7 +193,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += delta; prevSample = currentSample; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } // Depending on the algorithm, we refine the result of the above search @@ -156,7 +233,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += reliefDelta * depthSign; currentStep += reliefStep * depthSign; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -184,7 +261,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += adjustedDelta; prevSample = currentSample; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -197,17 +274,24 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset>1. if(parallaxOffset.z > 0.0) { - result.m_isClipped = o_parallax_highlightClipping; parallaxOffset = float3(0,0,0); } - // Extra check to report whether the heightmap is clipped. Inaccuracies in the intersection search make it difficult to rely on - // parallaxOffset.z to determine whether clipping has occurred. The most accurate way to report clipping is to sample the - // heightmap one last time at the final adjusted UV. Since that's expensive, we only do it when the o_parallax_highlightClipping - // option is set. - else if (o_parallax_highlightClipping) + + if (o_parallax_highlightClipping) { - float sampledDepthValue = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); - result.m_isClipped = sampledDepthValue < minSampledDepth; + // The most accurate way to report clipping is to sample the heightmap one last time at the final adjusted UV. + // (trying to do it based on parallaxOffset.z values just leads to too many edge cases) + + DepthResult depthResult = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + + if(DepthResultCode_Normalized == depthResult.m_resultCode) + { + result.m_isClipped = lerp(depthSearchStart, depthSearchEnd, depthResult.m_depth) < 0; + } + else if(DepthResultCode_Absolute == depthResult.m_resultCode) + { + result.m_isClipped = depthResult.m_depth < 0.0; + } } if(o_parallax_shadow && any(dirToLightTS)) @@ -233,7 +317,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo } shadowUV += shadowDelta; - currentSample = GetClampedDepth(minSampledDepth, shadowUV, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, shadowUV, ddx_uv, ddy_uv); currentStep -= step; } diff --git a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl index fd11d0d8cd..c90b1d1446 100644 --- a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl +++ b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl @@ -119,12 +119,12 @@ void GetSurfaceShape(float2 uv, out float depth, out float3 normal) } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { float depth; float3 normal; GetSurfaceShape(uv, depth, normal); - return depth; + return DepthResultNormalized(depth); } ForwardPassOutput AutoBrick_ForwardPassPS(VSOutput IN) From 0791d1d05f84dc1aff1f91759cfcb8f9aee98400 Mon Sep 17 00:00:00 2001 From: Mike Chang <62353586+amzn-changml@users.noreply.github.com> Date: Tue, 4 May 2021 16:09:26 -0700 Subject: [PATCH 063/112] Set default CDN for 3p system to production Cloudfront --- cmake/3rdPartyPackages.cmake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmake/3rdPartyPackages.cmake b/cmake/3rdPartyPackages.cmake index b3545fd415..60d8b4e20d 100644 --- a/cmake/3rdPartyPackages.cmake +++ b/cmake/3rdPartyPackages.cmake @@ -32,7 +32,8 @@ include(cmake/LySet.cmake) # also allowed: # "s3://bucketname" (it will use LYPackage_S3Downloader.cmake to download it from a s3 bucket) -set(LY_PACKAGE_SERVER_URLS "" CACHE STRING "Server URLS to fetch packages from") +# https://d2c171ws20a1rv.cloudfront.net will be the current "production" CDN until formally moved to the public O3DE repo +set(LY_PACKAGE_SERVER_URLS "https://d2c171ws20a1rv.cloudfront.net" CACHE STRING "Server URLS to fetch packages from") # Note: if you define the "LY_PACKAGE_SERVER_URLS" environment variable # it will be added to this value in the front, so that users can set # an env var and use that as an "additional" set of servers beyond the default set. From 5e6d058a43434b938c067adbd94b7b643a91c9d3 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 18:23:02 -0700 Subject: [PATCH 064/112] Removing default case to fix crash and updating tests --- .../Serialization/Json/JsonDeserializer.cpp | 4 +- .../Code/Tests/PhysXColliderPrefabTests.cpp | 44 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index 8d0da9e54a..9e0ab80dd1 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -33,10 +33,10 @@ namespace AZ "Target object for Json Serialization is pointing to nothing during loading."); } - if (IsExplicitDefault(value)) + /*if (IsExplicitDefault(value)) { return context.Report(Tasks::ReadField, Outcomes::DefaultsUsed, "Value has an explicit default."); - } + }*/ BaseJsonSerializer* serializer = context.GetRegistrationContext()->GetSerializerForType(typeId); if (serializer) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index 4287ce17db..5748fca931 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -36,7 +36,7 @@ namespace PhysX protected: }; - TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesNotNull) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesEqual) { //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; @@ -130,58 +130,58 @@ namespace PhysX EXPECT_NE(nullptr, updatedColliderConfigPtr); } - TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_PointersNotNull) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_ValuesEqual) { //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; //shared pointer - box collider - defaults only - auto boxColliderPtr = AZStd::make_shared(); + BoxColliderComponent boxColliderComponent; AZ::JsonSerializationResult::ResultCode result - = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderPtr); + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - boxColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(boxColliderPtr, prefabDom); + BoxColliderComponent newBoxColliderComponent; + result = AZ::JsonSerialization::Load(newBoxColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, boxColliderPtr); + EXPECT_EQ(newBoxColliderComponent.GetCollisionLayerName(), boxColliderComponent.GetCollisionLayerName()); //shared pointer - sphere collider - defaults only - auto sphereColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderPtr); + SphereColliderComponent sphereColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - sphereColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(sphereColliderPtr, prefabDom); + SphereColliderComponent newSphereColliderComponent; + result = AZ::JsonSerialization::Load(newSphereColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, sphereColliderPtr); + EXPECT_EQ(newSphereColliderComponent.GetCollisionLayerName(), sphereColliderComponent.GetCollisionLayerName()); //shared pointer - capsule collider - defaults only - auto capsuleColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderPtr); + CapsuleColliderComponent capsuleColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - capsuleColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(capsuleColliderPtr, prefabDom); + CapsuleColliderComponent newCapsuleColliderComponent; + result = AZ::JsonSerialization::Load(newCapsuleColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, capsuleColliderPtr); + EXPECT_EQ(newCapsuleColliderComponent.GetCollisionLayerName(), capsuleColliderComponent.GetCollisionLayerName()); //shared pointer - shape collider - defaults only - auto shapeColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderPtr); + ShapeColliderComponent shapeColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - shapeColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(shapeColliderPtr, prefabDom); + ShapeColliderComponent newShapeColliderComponent; + result = AZ::JsonSerialization::Load(newShapeColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, shapeColliderPtr); + EXPECT_EQ(newShapeColliderComponent.GetCollisionLayerName(), shapeColliderComponent.GetCollisionLayerName()); } } From 7963924b6ac528e710565356862c41efa53566e4 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 18:27:09 -0700 Subject: [PATCH 065/112] Removing extra commented code --- .../AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index 9e0ab80dd1..88d698b352 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -33,11 +33,6 @@ namespace AZ "Target object for Json Serialization is pointing to nothing during loading."); } - /*if (IsExplicitDefault(value)) - { - return context.Report(Tasks::ReadField, Outcomes::DefaultsUsed, "Value has an explicit default."); - }*/ - BaseJsonSerializer* serializer = context.GetRegistrationContext()->GetSerializerForType(typeId); if (serializer) { From ceb7ac333a1e58941606dc401fded753522662ff Mon Sep 17 00:00:00 2001 From: balibhan Date: Wed, 5 May 2021 12:31:43 +0530 Subject: [PATCH 066/112] removed debug print --- .../scripting/OnEntityActivatedDeactivated_PrintMessage.py | 1 - 1 file changed, 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py index cea1230348..51b63c4268 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -145,7 +145,6 @@ def OnEntityActivatedDeactivated_PrintMessage(): def locate_expected_lines(line_list: list): found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] - print(f"bhanu: {found_lines}") return all(line in found_lines for line in line_list) # 1) Create temp level From 24167e7c023671ba7ae2928d35c6e638c0353ff8 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Wed, 5 May 2021 12:36:47 +0100 Subject: [PATCH 067/112] address PR comments --- ...243589_Joints_BallSoftLimitsConstrained.py | 25 ++++++++----------- .../PythonTests/physics/TestSuite_Periodic.py | 6 +++-- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py index b7bc8439e4..16266b2da3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py @@ -102,32 +102,27 @@ def C18243589_Joints_BallSoftLimitsConstrained(): normalizedStartPos = JointsHelper.getRelativeVector(lead.position, follower.position) normalizedStartPos = normalizedStartPos.GetNormalizedSafe() #the targeted angle to reach between the initial vector and the current follower-lead vector - targetAngleDeg = 45 - targetAngle = math.radians(targetAngleDeg) - - maxTotalWaitTime = 2.0 #seconds - waitTime = 0.0 - waitStep = 0.2 + TARGET_ANGLE_DEG = 45 + targetAngle = math.radians(TARGET_ANGLE_DEG) angleAchieved = 0.0 - while waitTime < maxTotalWaitTime: - waitTime = waitTime + waitStep - general.idle_wait(waitStep) # wait for lead and follower to move + def checkAngleMet(): #calculate the current follower-lead vector normalVec = JointsHelper.getRelativeVector(lead.position, follower.position) normalVec = normalVec.GetNormalizedSafe() #dot product + acos to get the angle angleAchieved = math.acos(normalizedStartPos.Dot(normalVec)) #is it above target? - if angleAchieved > targetAngle: - followerMovedAboveJoint = True - break + return angleAchieved > targetAngle + + MAX_WAIT_TIME = 2.0 #seconds + followerMovedAboveJoint = helper.wait_for_condition(checkAngleMet, MAX_WAIT_TIME) # 5) Check to see if lead and follower behaved as expected - Report.info_vector3(lead.position, "lead position after {:.2f} second:".format(waitTime)) - Report.info_vector3(follower.position, "follower position after {:.2f} second:".format(waitTime)) + Report.info_vector3(lead.position, "lead position:") + Report.info_vector3(follower.position, "follower position:") angleAchievedDeg = math.degrees(angleAchieved) - Report.info("Angle achieved {:.2f} Target {:.2f}".format(angleAchievedDeg, targetAngleDeg)) + Report.info(f"Angle achieved {angleAchievedDeg:.2f} Target {TARGET_ANGLE_DEG:.2f}") leadPositionDelta = lead.position.Subtract(leadInitialPosition) leadRemainedStill = JointsHelper.vector3SmallerThanScalar(leadPositionDelta, FLOAT_EPSILON) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py index 4f91f539ee..93831e9658 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py @@ -254,6 +254,8 @@ class TestAutomation(TestAutomationBase): from . import C4044697_Material_PerfaceMaterialValidation as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail( + reason="This test will sometimes fail as the ball will continue to roll before the timeout is reached.") @revert_physics_config def test_C4976202_RigidBody_StopsWhenBelowKineticThreshold(self, request, workspace, editor, launcher_platform): from . import C4976202_RigidBody_StopsWhenBelowKineticThreshold as test_module @@ -468,12 +470,12 @@ class TestAutomation(TestAutomationBase): from . import C6090547_ForceRegion_ParentChildForceRegions as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config + @revert_physics_config def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform): from . import C19578021_ShapeCollider_CanBeAdded as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config + @revert_physics_config def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform): from . import C15425929_Undo_Redo as test_module self._run_test(request, workspace, editor, test_module) From 9e2975ba3cb81a819ddd06c7704a0ce09a8cdb0e Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 14:19:23 +0100 Subject: [PATCH 068/112] Fixed unit tests when Spawnable system component was missing --- Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp index c18c2ee5e3..2e0b9c0759 100644 --- a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp +++ b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ namespace UnitTest { SetupAllocator(); AZ::NameDictionary::Create(); + m_spawnableComponent = new AzFramework::SpawnableSystemComponent(); m_mpComponent = new Multiplayer::MultiplayerSystemComponent(); m_initHandler = Multiplayer::SessionInitEvent::Handler([this](AzNetworking::INetworkInterface* value) { TestInitEvent(value); }); @@ -41,6 +43,7 @@ namespace UnitTest void TearDown() override { delete m_mpComponent; + delete m_spawnableComponent; AZ::NameDictionary::Destroy(); TeardownAllocator(); } @@ -69,6 +72,7 @@ namespace UnitTest Multiplayer::ConnectionAcquiredEvent::Handler m_connAcquiredHandler; Multiplayer::MultiplayerSystemComponent* m_mpComponent = nullptr; + AzFramework::SpawnableSystemComponent* m_spawnableComponent = nullptr; }; TEST_F(MultiplayerSystemTests, TestInitEvent) From f4bd72880e00b4eae6e56285bf9489aa74f2b95d Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 14:28:45 +0100 Subject: [PATCH 069/112] Fixed tabs --- .../Code/Source/NetworkEntity/NetworkEntityManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 3764b92b25..ce55f66caa 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -372,7 +372,7 @@ namespace Multiplayer INetworkEntityManager::EntityList returnList; auto spawnableAssetId = m_networkPrefabLibrary.GetAssetIdByName(prefabEntryId.m_prefabName); - // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary + // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary auto netSpawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(spawnableAssetId, AZ::Data::AssetLoadBehavior::PreLoad); AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(netSpawnableAsset); @@ -508,6 +508,6 @@ namespace Multiplayer void NetworkEntityManager::OnDespawned([[maybe_unused]]AZ::Data::Asset spawnable) { - // TODO: Remove entities instantiated from the spawnable + // TODO: Remove entities instantiated from the spawnable } } From d7b796fd73a14e4951abeb1d18e5ed075e35e6e6 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Wed, 5 May 2021 09:07:28 -0600 Subject: [PATCH 070/112] Remove I3DEngine CryCommon Interface (#567) Delete: - I3DEngine - Missions - Time of day - GameEffectsSystem Gem - ImageProcessing Gem - SVOGI Gem - Various other things that don't do anything now that the legacy renderer has been removed. --- Code/CryEngine/CryCommon/CryEngineDecalInfo.h | 77 - Code/CryEngine/CryCommon/Gem.h | 98 - Code/CryEngine/CryCommon/I3DEngine.h | 3021 ----------------- Code/CryEngine/CryCommon/I3DEngine_info.h | 53 - Code/CryEngine/CryCommon/IEntityRenderState.h | 1 - Code/CryEngine/CryCommon/ILocalMemoryUsage.h | 33 - Code/CryEngine/CryCommon/IMaterial.h | 3 +- Code/CryEngine/CryCommon/IMovieSystem.h | 1 - Code/CryEngine/CryCommon/IObjManager.h | 1 - Code/CryEngine/CryCommon/ISystem.h | 22 - Code/CryEngine/CryCommon/ITimeOfDay.h | 286 -- .../CryEngine/CryCommon/Mocks/I3DEngineMock.h | 528 --- .../CryEngine/CryCommon/Mocks/IRendererMock.h | 6 +- Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 8 - Code/CryEngine/CryCommon/Mocks/StubTimer.h | 2 + Code/CryEngine/CryCommon/WindowsUtils.h | 215 -- .../CryEngine/CryCommon/crycommon_files.cmake | 7 - .../CryCommon/crycommon_testing_files.cmake | 1 - .../CrySystem/CrySystem_precompiled.h | 2 - .../CrySystem/LevelSystem/LevelSystem.cpp | 55 +- .../LevelSystem/SpawnableLevelSystem.cpp | 59 +- Code/CryEngine/CrySystem/PerfHUD.cpp | 55 - .../CrySystem/Statistics/LocalMemoryUsage.cpp | 1389 -------- .../CrySystem/Statistics/LocalMemoryUsage.h | 245 -- Code/CryEngine/CrySystem/System.cpp | 103 +- Code/CryEngine/CrySystem/System.h | 16 - Code/CryEngine/CrySystem/SystemInit.cpp | 13 - Code/CryEngine/CrySystem/SystemRender.cpp | 315 -- Code/CryEngine/CrySystem/SystemWin32.cpp | 18 - Code/CryEngine/CrySystem/ViewSystem/View.cpp | 2 +- .../CrySystem/ViewSystem/ViewSystem.cpp | 10 - Code/CryEngine/CrySystem/VisRegTest.cpp | 1 - .../CryEngine/CrySystem/crysystem_files.cmake | 2 - Code/Sandbox/Editor/2DViewport.cpp | 108 - .../AzAssetBrowserRequestHandler.cpp | 14 - .../AzAssetBrowserRequestHandler.h | 11 - .../Preview/LegacyPreviewer.cpp | 409 --- .../AzAssetBrowser/Preview/LegacyPreviewer.h | 100 - .../AzAssetBrowser/Preview/LegacyPreviewer.ui | 176 - .../Preview/LegacyPreviewerFactory.cpp | 71 - .../Preview/LegacyPreviewerFactory.h | 34 - Code/Sandbox/Editor/BaseLibraryManager.cpp | 3 - .../Editor/Controls/PreviewModelCtrl.cpp | 1194 ------- .../Editor/Controls/PreviewModelCtrl.h | 198 -- .../Editor/Controls/TimeOfDaySlider.cpp | 26 - .../Sandbox/Editor/Controls/TimeOfDaySlider.h | 34 - Code/Sandbox/Editor/CryEdit.cpp | 180 - Code/Sandbox/Editor/CryEdit.h | 4 - Code/Sandbox/Editor/CryEditDoc.cpp | 275 -- Code/Sandbox/Editor/CryEditDoc.h | 24 - Code/Sandbox/Editor/DisplaySettings.cpp | 5 - Code/Sandbox/Editor/EditorDefs.h | 1 - Code/Sandbox/Editor/EditorViewportWidget.cpp | 32 +- Code/Sandbox/Editor/EditorViewportWidget.h | 4 - Code/Sandbox/Editor/EnvironmentPanel.cpp | 53 - Code/Sandbox/Editor/EnvironmentPanel.h | 53 - Code/Sandbox/Editor/EnvironmentPanel.ui | 56 - Code/Sandbox/Editor/Export/ExportManager.cpp | 59 +- Code/Sandbox/Editor/GameEngine.cpp | 185 - Code/Sandbox/Editor/GameEngine.h | 7 - Code/Sandbox/Editor/GameExporter.cpp | 175 +- Code/Sandbox/Editor/GameExporter.h | 2 - Code/Sandbox/Editor/Geometry/EdGeometry.cpp | 16 - Code/Sandbox/Editor/Geometry/EdGeometry.h | 84 - Code/Sandbox/Editor/Geometry/EdMesh.cpp | 1548 --------- Code/Sandbox/Editor/Geometry/EdMesh.h | 194 -- Code/Sandbox/Editor/IEditor.h | 9 - Code/Sandbox/Editor/IEditorImpl.cpp | 17 - Code/Sandbox/Editor/IEditorImpl.h | 2 - Code/Sandbox/Editor/IconManager.cpp | 37 +- Code/Sandbox/Editor/IconManager.h | 4 - Code/Sandbox/Editor/Include/IIconManager.h | 1 - Code/Sandbox/Editor/Lib/Tests/IEditorMock.h | 2 - Code/Sandbox/Editor/LyViewPaneNames.h | 1 - Code/Sandbox/Editor/MainWindow.cpp | 9 - Code/Sandbox/Editor/Mission.cpp | 364 -- Code/Sandbox/Editor/Mission.h | 105 - Code/Sandbox/Editor/ModelViewport.cpp | 961 ------ Code/Sandbox/Editor/ModelViewport.h | 258 -- Code/Sandbox/Editor/ModelViewportDC.cpp | 24 - Code/Sandbox/Editor/Objects/BaseObject.cpp | 5 +- Code/Sandbox/Editor/Objects/BaseObject.h | 5 - Code/Sandbox/Editor/Objects/DisplayContext.h | 2 - .../Editor/Objects/DisplayContextShared.inl | 24 +- Code/Sandbox/Editor/Objects/EntityObject.cpp | 51 +- Code/Sandbox/Editor/Objects/EntityObject.h | 4 - Code/Sandbox/Editor/Objects/ObjectManager.cpp | 13 - Code/Sandbox/Editor/Objects/ObjectManager.h | 3 - .../Sandbox/Editor/Objects/SelectionGroup.cpp | 1 + Code/Sandbox/Editor/PanelPreview.cpp | 42 - Code/Sandbox/Editor/PanelPreview.h | 40 - Code/Sandbox/Editor/RenderViewport.cpp | 70 +- Code/Sandbox/Editor/RenderViewport.h | 5 - Code/Sandbox/Editor/Resource.h | 2 - Code/Sandbox/Editor/Settings.cpp | 6 - Code/Sandbox/Editor/Settings.h | 2 - Code/Sandbox/Editor/ThumbnailGenerator.cpp | 198 -- Code/Sandbox/Editor/ThumbnailGenerator.h | 30 - Code/Sandbox/Editor/TimeOfDay.qrc | 34 - Code/Sandbox/Editor/TimeOfDayDialog.cpp | 1443 -------- Code/Sandbox/Editor/TimeOfDayDialog.h | 182 - Code/Sandbox/Editor/TimeOfDayDialog.ui | 980 ------ .../Editor/TrackView/TrackViewDialog.cpp | 6 - .../Editor/TrackView/TrackViewNodes.cpp | 64 +- Code/Sandbox/Editor/Util/CubemapUtils.cpp | 1 + Code/Sandbox/Editor/Util/FileUtil.cpp | 61 - Code/Sandbox/Editor/Util/KDTree.cpp | 2 + Code/Sandbox/Editor/Util/VariableTypeInfo.cpp | 445 --- Code/Sandbox/Editor/Util/VariableTypeInfo.h | 221 -- Code/Sandbox/Editor/editor_core_files.cmake | 2 - Code/Sandbox/Editor/editor_lib_files.cmake | 30 +- .../Plugins/EditorCommon/ManipScene.cpp | 1 - .../Plugins/EditorCommon/QViewport.cpp | 348 +- Code/Sandbox/Plugins/EditorCommon/QViewport.h | 1 - .../Code/Source/Previewer/ImagePreviewer.ui | 5 - .../Code/Source/Engine/ATLAudioObject.cpp | 2 +- .../Code/Source/Engine/ATLComponents.cpp | 2 +- Gems/CMakeLists.txt | 3 - .../Code/Tests/UI/LODSkinnedMeshTests.cpp | 1 - Gems/FastNoise/Code/Tests/FastNoiseTest.cpp | 1 - .../Assets/GameEffectsSystem_Dependencies.xml | 3 - Gems/GameEffectSystem/Assets/seedList.seed | 13 - Gems/GameEffectSystem/CMakeLists.txt | 12 - Gems/GameEffectSystem/Code/CMakeLists.txt | 37 - .../Code/gameeffectsystem_files.cmake | 27 - .../Code/gameeffectsystem_shared_files.cmake | 16 - .../GameEffects/GameEffectBase.h | 213 -- .../GameEffects/IGameEffect.h | 103 - .../GameEffectsSystemDefines.h | 179 - .../GameEffectSystem/IGameEffectSystem.h | 163 - .../GameEffectSystem/IGameRenderNode.h | 51 - .../Code/source/GameEffectSystemGem.cpp | 79 - .../Code/source/GameEffectSystemGem.h | 36 - .../source/GameEffectSystem_precompiled.cpp | 12 - .../source/GameEffectSystem_precompiled.h | 21 - .../GameEffects/GameEffectSoftCodeLibrary.cpp | 23 - .../Code/source/GameEffectsSystem.cpp | 1012 ------ .../Code/source/GameEffectsSystem.h | 137 - .../RenderElements/GameRenderElement.cpp | 79 - .../source/RenderElements/GameRenderElement.h | 78 - .../GameRenderElementSoftCodeLibrary.cpp | 24 - .../GameRenderNodeSoftCodeLibrary.cpp | 24 - .../Code/source/RenderNodes/IGameRenderNode.h | 51 - Gems/GameEffectSystem/gem.json | 12 - .../GameStateLevelRunning.inl | 5 - .../Code/Source/Gestures_precompiled.h | 1 - Gems/GradientSignal/Code/CMakeLists.txt | 2 - .../Code/Include/GradientSignal/ImageAsset.h | 4 +- .../Editor/EditorImageBuilderComponent.cpp | 12 +- .../Code/Source/GradientImageConversion.cpp | 36 +- .../GradientSignal/Code/Source/ImageAsset.cpp | 22 +- .../Code/Tests/GradientSignalImageTests.cpp | 4 +- .../Code/Tests/ImageAssetTests.cpp | 34 +- Gems/ImGui/Code/Editor/ImGuiViewport.cpp | 4 - Gems/ImGui/Code/Editor/ImGuiViewport.h | 1 + .../Include/LYImGuiUtils/ImGuiDrawHelpers.h | 2 + Gems/ImGui/Code/Source/ImGuiManager.cpp | 4 +- Gems/ImGui/Code/Source/ImGui_precompiled.h | 1 - .../LYCommonMenu/ImGuiLYAssetExplorer.cpp | 1 + .../Code/Source/InAppPurchases_precompiled.h | 1 - Gems/LmbrCentral/Code/Source/LmbrCentral.cpp | 17 - Gems/LmbrCentral/Code/Source/LmbrCentral.h | 5 - .../MaterialOwnerRequestBusHandlerImpl.h | 349 -- Gems/LmbrCentral/Code/lmbrcentral_files.cmake | 1 - .../Editor/Animation/UiAnimViewDialog.cpp | 6 - .../Code/Editor/Animation/UiAnimViewNodes.cpp | 59 +- .../Code/Source/Animation/AnimNode.cpp | 1 - .../Code/Source/Animation/AnimSequence.cpp | 1 - Gems/LyShine/Code/Tests/SpriteTest.cpp | 1 - .../Source/Cinematics/AnimEnvironmentNode.cpp | 247 -- .../Source/Cinematics/AnimEnvironmentNode.h | 61 - .../Code/Source/Cinematics/AnimNode.cpp | 1 - .../Code/Source/Cinematics/AnimPostFXNode.cpp | 10 - .../Code/Source/Cinematics/AnimSequence.cpp | 5 - .../Code/Source/Cinematics/MaterialNode.cpp | 31 +- .../Source/Cinematics/ShadowsSetupNode.cpp | 2 - .../Source/Components/SequenceComponent.cpp | 2 - Gems/Maestro/Code/maestro_static_files.cmake | 2 - .../Components/EditorSystemComponent.cpp | 25 - Gems/SVOGI/CMakeLists.txt | 12 - Gems/SVOGI/Code/CMakeLists.txt | 48 - Gems/SVOGI/Code/Include/SVOGI/SVOGIBus.h | 37 - .../Platform/Android/SVOGI_Traits_Android.h | 14 - .../Platform/Android/SVOGI_Traits_Platform.h | 14 - .../Android/platform_android_files.cmake | 15 - .../Platform/Linux/SVOGI_Traits_Linux.h | 14 - .../Platform/Linux/SVOGI_Traits_Platform.h | 14 - .../Platform/Linux/platform_linux_files.cmake | 15 - .../Source/Platform/Mac/SVOGI_Traits_Mac.h | 14 - .../Platform/Mac/SVOGI_Traits_Platform.h | 14 - .../Platform/Mac/platform_mac_files.cmake | 15 - .../Platform/Windows/SVOGI_Traits_Platform.h | 14 - .../Platform/Windows/SVOGI_Traits_Windows.h | 14 - .../Windows/platform_windows_files.cmake | 15 - .../Platform/iOS/SVOGI_Traits_Platform.h | 14 - .../Source/Platform/iOS/SVOGI_Traits_iOS.h | 14 - .../Platform/iOS/platform_ios_files.cmake | 15 - Gems/SVOGI/Code/Source/SVOGIModule.cpp | 54 - .../Code/Source/SVOGISystemComponent.cpp | 448 --- Gems/SVOGI/Code/Source/SVOGISystemComponent.h | 143 - Gems/SVOGI/Code/Source/SVOGI_precompiled.cpp | 14 - Gems/SVOGI/Code/Source/SVOGI_precompiled.h | 15 - Gems/SVOGI/Code/Source/SvoBrick.cpp | 1283 ------- Gems/SVOGI/Code/Source/SvoBrick.h | 225 -- Gems/SVOGI/Code/Source/SvoTree.cpp | 1321 ------- Gems/SVOGI/Code/Source/SvoTree.h | 233 -- Gems/SVOGI/Code/Source/TextureBlockPacker.cpp | 272 -- Gems/SVOGI/Code/Source/TextureBlockPacker.h | 118 - Gems/SVOGI/Code/svogi_files.cmake | 24 - Gems/SVOGI/Code/svogi_shared_files.cmake | 14 - Gems/SVOGI/gem.json | 23 - .../TerrainSurfaceDataSystemComponent.cpp | 1 - .../Code/Tests/SurfaceDataTest.cpp | 1 - .../Code/Source/AreaSystemComponent.cpp | 12 - .../Code/Source/Debugger/DebugComponent.cpp | 91 - .../Code/Source/Debugger/DebugComponent.h | 1 - Gems/Vegetation/Code/Source/Descriptor.cpp | 2 - .../Legacy/WhiteBoxLegacyRenderMesh.cpp | 465 --- .../Legacy/WhiteBoxLegacyRenderMesh.h | 42 - .../Code/Source/WhiteBoxSystemComponent.cpp | 1 - .../Code/whitebox_supported_files.cmake | 2 - .../ConsoleFrontendConfig.in | 1 - 222 files changed, 124 insertions(+), 26474 deletions(-) delete mode 100644 Code/CryEngine/CryCommon/CryEngineDecalInfo.h delete mode 100644 Code/CryEngine/CryCommon/Gem.h delete mode 100644 Code/CryEngine/CryCommon/I3DEngine.h delete mode 100644 Code/CryEngine/CryCommon/I3DEngine_info.h delete mode 100644 Code/CryEngine/CryCommon/ILocalMemoryUsage.h delete mode 100644 Code/CryEngine/CryCommon/ITimeOfDay.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h delete mode 100644 Code/CryEngine/CryCommon/WindowsUtils.h delete mode 100644 Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp delete mode 100644 Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h delete mode 100644 Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp delete mode 100644 Code/Sandbox/Editor/Controls/PreviewModelCtrl.h delete mode 100644 Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp delete mode 100644 Code/Sandbox/Editor/Controls/TimeOfDaySlider.h delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.cpp delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.h delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.ui delete mode 100644 Code/Sandbox/Editor/Geometry/EdGeometry.cpp delete mode 100644 Code/Sandbox/Editor/Geometry/EdGeometry.h delete mode 100644 Code/Sandbox/Editor/Geometry/EdMesh.cpp delete mode 100644 Code/Sandbox/Editor/Geometry/EdMesh.h delete mode 100644 Code/Sandbox/Editor/Mission.cpp delete mode 100644 Code/Sandbox/Editor/Mission.h delete mode 100644 Code/Sandbox/Editor/ModelViewport.cpp delete mode 100644 Code/Sandbox/Editor/ModelViewport.h delete mode 100644 Code/Sandbox/Editor/ModelViewportDC.cpp delete mode 100644 Code/Sandbox/Editor/PanelPreview.cpp delete mode 100644 Code/Sandbox/Editor/PanelPreview.h delete mode 100644 Code/Sandbox/Editor/ThumbnailGenerator.cpp delete mode 100644 Code/Sandbox/Editor/ThumbnailGenerator.h delete mode 100644 Code/Sandbox/Editor/TimeOfDay.qrc delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.cpp delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.h delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.ui delete mode 100644 Code/Sandbox/Editor/Util/VariableTypeInfo.cpp delete mode 100644 Code/Sandbox/Editor/Util/VariableTypeInfo.h delete mode 100644 Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml delete mode 100644 Gems/GameEffectSystem/Assets/seedList.seed delete mode 100644 Gems/GameEffectSystem/CMakeLists.txt delete mode 100644 Gems/GameEffectSystem/Code/CMakeLists.txt delete mode 100644 Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake delete mode 100644 Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectsSystem.h delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h delete mode 100644 Gems/GameEffectSystem/gem.json delete mode 100644 Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h delete mode 100644 Gems/Maestro/Code/Source/Cinematics/AnimEnvironmentNode.cpp delete mode 100644 Gems/Maestro/Code/Source/Cinematics/AnimEnvironmentNode.h delete mode 100644 Gems/SVOGI/CMakeLists.txt delete mode 100644 Gems/SVOGI/Code/CMakeLists.txt delete mode 100644 Gems/SVOGI/Code/Include/SVOGI/SVOGIBus.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/SVOGI_Traits_Android.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/platform_android_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/SVOGI_Traits_Linux.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/platform_linux_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/SVOGI_Traits_Mac.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/platform_mac_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/SVOGI_Traits_Windows.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/platform_windows_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/SVOGI_Traits_iOS.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/platform_ios_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/SVOGIModule.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGISystemComponent.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGISystemComponent.h delete mode 100644 Gems/SVOGI/Code/Source/SVOGI_precompiled.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGI_precompiled.h delete mode 100644 Gems/SVOGI/Code/Source/SvoBrick.cpp delete mode 100644 Gems/SVOGI/Code/Source/SvoBrick.h delete mode 100644 Gems/SVOGI/Code/Source/SvoTree.cpp delete mode 100644 Gems/SVOGI/Code/Source/SvoTree.h delete mode 100644 Gems/SVOGI/Code/Source/TextureBlockPacker.cpp delete mode 100644 Gems/SVOGI/Code/Source/TextureBlockPacker.h delete mode 100644 Gems/SVOGI/Code/svogi_files.cmake delete mode 100644 Gems/SVOGI/Code/svogi_shared_files.cmake delete mode 100644 Gems/SVOGI/gem.json delete mode 100644 Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.cpp delete mode 100644 Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.h diff --git a/Code/CryEngine/CryCommon/CryEngineDecalInfo.h b/Code/CryEngine/CryCommon/CryEngineDecalInfo.h deleted file mode 100644 index f38533e341..0000000000 --- a/Code/CryEngine/CryCommon/CryEngineDecalInfo.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : declaration of struct CryEngineDecalInfo. - -// Note: -// 3D Engine and Character Animation subsystems (as well as perhaps -// some others) transfer data about the decals that need to be spawned -// via this structure. This is to avoid passing many parameters through -// each function call, and to save on copying these parameters when just -// simply passing the structure from one function to another. - -#ifndef CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H -#define CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H -#pragma once - -#include "Cry_Math.h" - -// Summary: -// Structure containing common parameters that describe a decal - -struct SDecalOwnerInfo -{ - SDecalOwnerInfo() { memset(this, 0, sizeof(*this)); nRenderNodeSlotId = nRenderNodeSlotSubObjectId = -1; } - struct IStatObj* GetOwner(Matrix34A& objMat); - - struct IRenderNode* pRenderNode; // Owner (decal will be attached to or wrapped around of this object) - PodArray* pDecalReceivers; - int nRenderNodeSlotId; // is set internally by 3dengine - int nRenderNodeSlotSubObjectId; // is set internally by 3dengine - int nMatID; -}; - -struct CryEngineDecalInfo -{ - SDecalOwnerInfo ownerInfo; - Vec3 vPos; // Decal position (world coordinates) - Vec3 vNormal; // Decal/face normal - float fSize; // Decal size - float fLifeTime; // Decal life time (in seconds) - float fAngle; // Angle of rotation - struct IStatObj* pIStatObj; // Decal geometry - Vec3 vHitDirection; // Direction from weapon/player position to decal position (bullet direction) - float fGrowTime, fGrowTimeAlpha;// Used for blood pools - unsigned int nGroupId; // Used for multi-component decals - bool bSkipOverlappingTest; // Always spawn decals even if there are a lot of other decals in same place - bool bAssemble; // Assemble to bigger decals if more than 1 decal is on the same place - bool bForceEdge; // force the decal to the nearest edge of the owner mesh and project it accordingly - bool bForceSingleOwner; // Do not attempt to cast the decal into the environment even if it's large enough - bool bDeferred; - uint8 sortPrio; - char szMaterialName[_MAX_PATH]; // name of material used for rendering the decal (in favor of szTextureName/nTid and the default decal shader) - bool preventDecalOnGround; // mainly for decal placement support - const Matrix33* pExplicitRightUpFront; // mainly for decal placement support - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const{} - - // the constructor fills in some non-obligatory fields; the other fields must be filled in by the client - CryEngineDecalInfo () - { - memset(this, 0, sizeof(*this)); - ownerInfo.nRenderNodeSlotId = ownerInfo.nRenderNodeSlotSubObjectId = -1; - sortPrio = 255; - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H diff --git a/Code/CryEngine/CryCommon/Gem.h b/Code/CryEngine/CryCommon/Gem.h deleted file mode 100644 index 3097fcf304..0000000000 --- a/Code/CryEngine/CryCommon/Gem.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(Gem_h) -#endif - -#if defined(LINUX) || defined(APPLE) || defined(ANDROID) - #define OPENGL 1 -#endif - -#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 <3dEngine.h> -#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 -#include -#include - -#include diff --git a/Code/CryEngine/CryCommon/I3DEngine.h b/Code/CryEngine/CryCommon/I3DEngine.h deleted file mode 100644 index 883b0a6d3b..0000000000 --- a/Code/CryEngine/CryCommon/I3DEngine.h +++ /dev/null @@ -1,3021 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : 3dengine interface - -#ifndef CRYINCLUDE_CRYCOMMON_I3DENGINE_H -#define CRYINCLUDE_CRYCOMMON_I3DENGINE_H -#pragma once - -// The maximum number of unique surface types that can be used per node -#define MMRM_MAX_SURFACE_TYPES 16 -#define COMPILED_OCTREE_FILE_NAME "terrain/terrain.dat" - -// !!! Do not add any headers here !!! -#include "CryEngineDecalInfo.h" -#include -#include // <> required for Interfuscator -#include "IRenderer.h" -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include "CryArray.h" -#include // <> required for Interfuscator -#include -// !!! Do not add any headers here !!! - -class IOpticsManager; -class CContentCGF; -class ICrySizer; -class CRenderView; -struct ISystem; -struct CVars; -struct pe_params_particle; -struct IMaterial; -struct SpawnParams; -struct ForceObject; -struct IRenderNode; -struct IObjManager; -struct IDeferredPhysicsEventManager; -struct IBSPTree3D; -struct ITextureLoadHandler; -struct ITimeOfDay; -struct MacroTextureConfiguration; - -namespace LegacyProceduralVegetation -{ - class IVegetationPoolManager; -} - -namespace LegacyTerrain -{ - struct MacroTextureConfiguration; -} - -namespace ChunkFile -{ - struct IChunkFileWriter; -} - -namespace AZ -{ - class Aabb; -} - -enum E3DEngineParameter -{ - E3DPARAM_SUN_COLOR, - - E3DPARAM_SUN_SPECULAR_MULTIPLIER, - - E3DPARAM_AMBIENT_GROUND_COLOR, - E3DPARAM_AMBIENT_MIN_HEIGHT, - E3DPARAM_AMBIENT_MAX_HEIGHT, - - E3DPARAM_FOG_COLOR, - E3DPARAM_FOG_COLOR2, - E3DPARAM_FOG_RADIAL_COLOR, - - E3DPARAM_VOLFOG_HEIGHT_DENSITY, - E3DPARAM_VOLFOG_HEIGHT_DENSITY2, - - E3DPARAM_VOLFOG_GRADIENT_CTRL, - - E3DPARAM_VOLFOG_GLOBAL_DENSITY, - E3DPARAM_VOLFOG_RAMP, - - E3DPARAM_VOLFOG_SHADOW_RANGE, - E3DPARAM_VOLFOG_SHADOW_DARKENING, - E3DPARAM_VOLFOG_SHADOW_ENABLE, - - E3DPARAM_VOLFOG2_CTRL_PARAMS, - E3DPARAM_VOLFOG2_SCATTERING_PARAMS, - E3DPARAM_VOLFOG2_RAMP, - E3DPARAM_VOLFOG2_COLOR, - E3DPARAM_VOLFOG2_GLOBAL_DENSITY, - E3DPARAM_VOLFOG2_HEIGHT_DENSITY, - E3DPARAM_VOLFOG2_HEIGHT_DENSITY2, - E3DPARAM_VOLFOG2_COLOR1, - E3DPARAM_VOLFOG2_COLOR2, - - E3DPARAM_SKYLIGHT_SUN_INTENSITY, - - E3DPARAM_SKYLIGHT_KM, - E3DPARAM_SKYLIGHT_KR, - E3DPARAM_SKYLIGHT_G, - - E3DPARAM_SKYLIGHT_WAVELENGTH_R, - E3DPARAM_SKYLIGHT_WAVELENGTH_G, - E3DPARAM_SKYLIGHT_WAVELENGTH_B, - - E3DPARAM_NIGHSKY_HORIZON_COLOR, - E3DPARAM_NIGHSKY_ZENITH_COLOR, - E3DPARAM_NIGHSKY_ZENITH_SHIFT, - - E3DPARAM_NIGHSKY_STAR_INTENSITY, - - E3DPARAM_NIGHSKY_MOON_DIRECTION, - E3DPARAM_NIGHSKY_MOON_COLOR, - E3DPARAM_NIGHSKY_MOON_SIZE, - E3DPARAM_NIGHSKY_MOON_INNERCORONA_COLOR, - E3DPARAM_NIGHSKY_MOON_INNERCORONA_SCALE, - E3DPARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, - E3DPARAM_NIGHSKY_MOON_OUTERCORONA_SCALE, - - E3DPARAM_CLOUDSHADING_MULTIPLIERS, - E3DPARAM_CLOUDSHADING_SUNCOLOR, - E3DPARAM_CLOUDSHADING_SKYCOLOR, - - E3DPARAM_CORONA_SIZE, - - E3DPARAM_OCEANFOG_COLOR, - E3DPARAM_OCEANFOG_DENSITY, - - // Sky highlight (ex. From Lightning) - E3DPARAM_SKY_HIGHLIGHT_COLOR, - E3DPARAM_SKY_HIGHLIGHT_SIZE, - E3DPARAM_SKY_HIGHLIGHT_POS, - - E3DPARAM_SKY_MOONROTATION, - - E3DPARAM_SKY_SKYBOX_ANGLE, - E3DPARAM_SKY_SKYBOX_STRETCHING, - - EPARAM_SUN_SHAFTS_VISIBILITY, - - E3DPARAM_SKYBOX_MULTIPLIER, - - E3DPARAM_DAY_NIGHT_INDICATOR, - - // Tone mapping tweakables - E3DPARAM_HDR_FILMCURVE_SHOULDER_SCALE, - E3DPARAM_HDR_FILMCURVE_LINEAR_SCALE, - E3DPARAM_HDR_FILMCURVE_TOE_SCALE, - E3DPARAM_HDR_FILMCURVE_WHITEPOINT, - - E3DPARAM_HDR_EYEADAPTATION_PARAMS, - E3DPARAM_HDR_EYEADAPTATION_PARAMS_LEGACY, - E3DPARAM_HDR_BLOOM_AMOUNT, - - E3DPARAM_HDR_COLORGRADING_COLOR_SATURATION, - E3DPARAM_HDR_COLORGRADING_COLOR_BALANCE, - - E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR, - E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY, - E3DPARAM_COLORGRADING_FILTERS_GRAIN -}; - -enum EShadowMode -{ - ESM_NORMAL = 0, - ESM_HIGHQUALITY -}; - -struct IBSPTree3D -{ - typedef DynArray CFace; - typedef DynArray FaceList; - - virtual ~IBSPTree3D() {} - virtual bool IsInside(const Vec3& vPos) const = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual size_t WriteToBuffer(void* pBuffer) const = 0; - virtual void ReadFromBuffer(const void* pBuffer) = 0; -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// This structure is filled and passed by the caller to the DebugDraw functions of the stat object or entity. -struct SGeometryDebugDrawInfo -{ - Matrix34 tm; // Transformation Matrix - ColorB color; // Optional color of the lines. - ColorB lineColor; // Optional color of the lines. - - // Optional flags controlling how to render debug draw information. - uint32 bNoCull : 1; - uint32 bNoLines : 1; - uint32 bExtrude : 1; // Extrude debug draw geometry alittle bit so it is over real geometry. - - SGeometryDebugDrawInfo() - : color(255, 0, 255, 255) - , lineColor(255, 255, 0, 255) - , bNoLines(0) - , bNoCull(0) { tm.SetIdentity(); } -}; - -struct SFrameLodInfo -{ - uint32 nID; - float fLodRatio; - float fTargetSize; - uint nMinLod; - uint nMaxLod; - - SFrameLodInfo() - { - nID = 0; - fLodRatio = 0.f; - fTargetSize = 0.f; - nMinLod = 0; - nMaxLod = 6; - } -}; -struct SMeshLodInfo -{ - static const int s_nMaxLodCount = 5; - float fGeometricMean; - uint nFaceCount; - uint32 nFrameLodID; - SMeshLodInfo() - { - Clear(); - } - void Clear() - { - fGeometricMean = 0.f; - nFaceCount = 0; - nFrameLodID = 0; - } - void Merge(const SMeshLodInfo& lodInfo) - { - uint nTotalCount = nFaceCount + lodInfo.nFaceCount; - if (nTotalCount > 0) - { - float fGeometricMeanTotal = 0.f; - if (fGeometricMean > 0.f) - { - fGeometricMeanTotal += logf(fGeometricMean) * nFaceCount; - } - if (lodInfo.fGeometricMean > 0.f) - { - fGeometricMeanTotal += logf(lodInfo.fGeometricMean) * lodInfo.nFaceCount; - } - fGeometricMean = expf(fGeometricMeanTotal / (float)nTotalCount); - nFaceCount = nTotalCount; - } - } -}; -// Summary: -// Physics material enumerator, allows for 3dengine to get material id from game code. -struct IPhysMaterialEnumerator -{ - // - virtual ~IPhysMaterialEnumerator(){} - virtual int EnumPhysMaterial(const char* szPhysMatName) = 0; - virtual bool IsCollidable(int nMatId) = 0; - virtual int GetMaterialCount() = 0; - virtual const char* GetMaterialNameByIndex(int index) = 0; - // -}; - - -// Summary: -// Physics foreign data flags. -enum EPhysForeignFlags -{ - PFF_HIDABLE = 0x1, - PFF_HIDABLE_SECONDARY = 0x2, - PFF_EXCLUDE_FROM_STATIC = 0x4, - PFF_UNIMPORTANT = 0x20, - PFF_OUTDOOR_AREA = 0x40, - PFF_MOVING_PLATFORM = 0x80, -}; - -// Summary: -// Ocean data flags. -enum EOceanRenderFlags -{ - OCR_NO_DRAW = 1 << 0, - OCR_OCEANVOLUME_VISIBLE = 1 << 1, -}; - -// Summary: -// Structure to pass vegetation group properties. -struct IStatInstGroup -{ - enum EPlayerHideable - { - ePlayerHideable_None = 0, - ePlayerHideable_High, - ePlayerHideable_Mid, - ePlayerHideable_Low, - - ePlayerHideable_COUNT, - }; - - IStatInstGroup() - { - pStatObj = 0; - szFileName[0] = 0; - bHideability = 0; - bHideabilitySecondary = 0; - fBending = 0; - nCastShadowMinSpec = 0; - bRecvShadow = 0; - bDynamicDistanceShadows = false; - bUseAlphaBlending = 0; - fSpriteDistRatio = 1.f; - fShadowDistRatio = 1.f; - fMaxViewDistRatio = 1.f; - fLodDistRatio = 1.f; - fBrightness = 1.f; - pMaterial = 0; - - fDensity = 1; - fElevationMax = 4096; - fElevationMin = 8; - fSize = 1; - fSizeVar = 0; - fSlopeMax = 255; - fSlopeMin = 0; - fStiffness = 0.5f; - fDamping = 2.5f; - fVariance = 0.6f; - fAirResistance = 1.f; - bRandomRotation = false; - nRotationRangeToTerrainNormal = 0; - nMaterialLayers = 0; - bAllowIndoor = false; - fAlignToTerrainCoefficient = 0.f; - bAutoMerged = false; - minConfigSpec = (ESystemConfigSpec)0; - nTexturesAreStreamedIn = 0; - nPlayerHideable = ePlayerHideable_None; - nID = -1; - } - - IStatObj* GetStatObj() - { - IStatObj* p = pStatObj; - return (IStatObj*)p; - } - const IStatObj* GetStatObj() const - { - const IStatObj* p = pStatObj; - return (const IStatObj*)p; - } - - _smart_ptr pStatObj; - char szFileName[256]; - bool bHideability; - bool bHideabilitySecondary; - float fBending; - uint8 nCastShadowMinSpec; - bool bRecvShadow; - bool bDynamicDistanceShadows; - bool bUseAlphaBlending; - float fSpriteDistRatio; - float fLodDistRatio; - float fShadowDistRatio; - float fMaxViewDistRatio; - float fBrightness; - bool bRandomRotation; - int32 nRotationRangeToTerrainNormal; - float fAlignToTerrainCoefficient; - bool bAllowIndoor; - bool bAutoMerged; - - float fDensity; - float fElevationMax; - float fElevationMin; - float fSize; - float fSizeVar; - float fSlopeMax; - float fSlopeMin; - float fStiffness; - float fDamping; - float fVariance; - float fAirResistance; - - float fVegRadius; - float fVegRadiusVert; - float fVegRadiusHor; - - int nPlayerHideable; - int nID; - - // Minimal configuration spec for this vegetation group. - ESystemConfigSpec minConfigSpec; - - // Override material for this instance group. - _smart_ptr pMaterial; - - // Material layers bitmask -> which layers are active. - uint8 nMaterialLayers; - - // Textures Are Streamed In. - uint8 nTexturesAreStreamedIn; - - // Flags similar to entity render flags. - int m_dwRndFlags; -}; - -// Description: -// Water volumes should usually be created by I3DEngine::CreateWaterVolume. -// Summary: -// Interface to water volumes. -struct IWaterVolume -{ - // - //DOC-IGNORE-BEGIN - virtual ~IWaterVolume(){} - virtual void UpdatePoints(const Vec3* pPoints, int nCount, float fHeight) = 0; - virtual void SetFlowSpeed(float fSpeed) = 0; - virtual void SetAffectToVolFog(bool bAffectToVolFog) = 0; - virtual void SetTriSizeLimits(float fTriMinSize, float fTriMaxSize) = 0; - // virtual void SetMaterial(const char * szShaderName) = 0; - virtual void SetMaterial(_smart_ptr pMaterial) = 0; - virtual _smart_ptr GetMaterial() = 0; - virtual const char* GetName() const = 0; - virtual void SetName(const char* szName) = 0; - //DOC-IGNORE-END - - // Description: - // Used to change the water level. Will assign a new Z value to all - // vertices of the water geometry. - // Arguments: - // vNewOffset - Position of the new water level - // Summary: - // Sets a new water level. - virtual void SetPositionOffset(const Vec3& vNewOffset) = 0; - // -}; - -struct SClipVolumeBlendInfo -{ - static const int BlendPlaneCount = 2; - - Plane_tpl blendPlanes[BlendPlaneCount]; - struct IClipVolume* blendVolumes[BlendPlaneCount]; -}; - -struct IClipVolume -{ - enum EClipVolumeFlags - { - eClipVolumeConnectedToOutdoor = BIT(0), - eClipVolumeIgnoreGI = BIT(1), - eClipVolumeAffectedBySun = BIT(2), - eClipVolumeBlend = BIT(3), - eClipVolumeIsVisArea = BIT(4), - eClipVolumeIgnoreOutdoorAO = BIT(5), - }; - - virtual ~IClipVolume() {}; - virtual void GetClipVolumeMesh(_smart_ptr& renderMesh, Matrix34& worldTM) const = 0; - virtual AABB GetClipVolumeBBox() const = 0; - virtual bool IsPointInsideClipVolume(const Vec3& point) const = 0; - - virtual uint8 GetStencilRef() const = 0; - virtual uint GetClipVolumeFlags() const = 0; -}; - -// Summary: -// Provides information about the different VisArea volumes. -struct IVisArea - : public IClipVolume -{ - // - virtual ~IVisArea(){} - // Summary: - // Gets the last rendered frame id. - // Return Value: - // An int which contains the frame id. - virtual int GetVisFrameId() = 0; - - // Description: - // Gets a list of all the VisAreas which are connected to the current one. - // Arguments: - // pAreas - Pointer to an array of IVisArea* - // nMaxConnNum - The maximum of IVisArea to write in pAreas - // bSkipDisabledPortals - Ignore portals which are disabled - // Return Value: - // An integer which hold the amount of VisArea found to be connected. If - // the return is equal to nMaxConnNum, it's possible that not all - // connected VisAreas were returned due to the restriction imposed by the - // argument. - // Summary: - // Gets all the areas which are connected to the current one. - virtual int GetVisAreaConnections(IVisArea** pAreas, int nMaxConnNum, bool bSkipDisabledPortals = false) = 0; - - // Summary: - // Determines if it's connected to an outdoor area. - // Return Value: - // True if the VisArea is connected to an outdoor area. - virtual bool IsConnectedToOutdoor() const = 0; - - // Summary: - // Determines if the visarea ignores Global Illumination inside. - // Return Value: - // True if the VisArea ignores Global Illumination inside. - virtual bool IsIgnoringGI() const = 0; - - // Summary: - // Determines if the visarea ignores Outdoor Ambient occlusion inside. - // Return Value: - // True if the VisArea ignores Outdoor Ambient Occlusion inside. - virtual bool IsIgnoringOutdoorAO() const = 0; - - // Summary: - // Gets the name. - // Notes: - // The name is always returned in lower case. - // Return Value: - // A null terminated char array containing the name of the VisArea. - virtual const char* GetName() = 0; - - // Summary: - // Determines if this VisArea is a portal. - // Return Value: - // True if the VisArea is a portal, or false in the opposite case. - virtual bool IsPortal() const = 0; - - // Description: - // Searches for a specified VisArea to see if it's connected to the current - // VisArea. - // Arguments: - // pAnotherArea - A specified VisArea to find - // nMaxRecursion - The maximum number of recursion to do while searching - // bSkipDisabledPortals - Will avoid searching disabled VisAreas - // pVisitedAreas - if not NULL - will get list of all visited areas - // Return Value: - // True if the VisArea was found. - // Summary: - // Searches for a specified VisArea. - virtual bool FindVisArea(IVisArea* pAnotherArea, int nMaxRecursion, bool bSkipDisabledPortals) = 0; - - // Description: - // Searches for the surrounding VisAreas which connected to the current - // VisArea. - // Arguments: - // nMaxRecursion - The maximum number of recursion to do while searching - // bSkipDisabledPortals - Will avoid searching disabled VisAreas - // pVisitedAreas - if not NULL - will get list of all visited areas - // Return Value: - // None. - // Summary: - // Searches for the surrounding VisAreas. - virtual void FindSurroundingVisArea(int nMaxRecursion, bool bSkipDisabledPortals, PodArray* pVisitedAreas = NULL, int nMaxVisitedAreas = 0, int nDeepness = 0) = 0; - - // Summary: - // Determines if it's affected by outdoor lighting. - // Return Value: - // Returns true if the VisArea if it's affected by outdoor lighting, else - // false will be returned. - virtual bool IsAffectedByOutLights() const = 0; - - // Summary: - // Determines if the spere can be affect the VisArea. - // Return Value: - // Returns true if the VisArea can be affected by the sphere, else - // false will be returned. - virtual bool IsSphereInsideVisArea(const Vec3& vPos, const f32 fRadius) = 0; - - // Summary: - // Clips geometry inside or outside a vis area. - // Return Value: - // Whether geom was clipped. - virtual bool ClipToVisArea(bool bInside, Sphere& sphere, Vec3 const& vNormal) = 0; - - // Summary: - // Gives back the axis aligned bounding box of VisArea. - // Return Value: - // Returns the pointer of a AABB. - virtual const AABB* GetAABBox() const = 0; - - // Summary: - // Gives back the axis aligned bounding box of all static objects in the VisArea. - // This AABB can be huger than the ViaArea AABB as some objects might not be completely inside the VisArea. - // Return Value: - // Returns the pointer to the AABB. - virtual const AABB* GetStaticObjectAABBox() const = 0; - - // Summary: - // Determines if the point can be affect the VisArea. - // Return Value: - // Returns true if the VisArea can be affected by the point, else - // false will be returned. - virtual bool IsPointInsideVisArea(const Vec3& vPos) const = 0; - - virtual void GetShapePoints(const Vec3*& pPoints, size_t& nPoints) = 0; - virtual float GetHeight() = 0; - // -}; - -#include "OceanConstants.h" - -// float m_SortId : offseted by +WATER_LEVEL_SORTID_OFFSET if the camera object line is crossing the water surface -// : otherwise offseted by -WATER_LEVEL_SORTID_OFFSET -#define WATER_LEVEL_SORTID_OFFSET 10000000 - -#define DEFAULT_SID 0 - -// Summary: -// indirect lighting quadtree definition. -namespace NQT -{ - // Forward declaration - template - class CQuadTree; -} - -#define FILEVERSION_TERRAIN_SHLIGHTING_FILE 5 - -enum EVoxelBrushShape -{ - evbsSphere = 1, - evbsBox, -}; - -enum EVoxelEditTarget -{ - evetVoxelObjects = 1, -}; - -enum EVoxelEditOperation -{ - eveoNone = 0, - eveoPaintHeightPos, - eveoPaintHeightNeg, - eveoCreate, - eveoSubstract, - eveoMaterial, - eveoBaseColor, - eveoBlurPos, - eveoBlurNeg, - eveoCopyTerrainPos, - eveoCopyTerrainNeg, - eveoPickHeight, - eveoIntegrateMeshPos, - eveoIntegrateMeshNeg, - eveoForceDepth, - eveoLimitLod, - eveoLast, -}; - -#define COMPILED_VISAREA_MAP_FILE_NAME "terrain\\indoor.dat" -#define COMPILED_MERGED_MESHES_BASE_NAME "terrain\\merged_meshes_sectors\\" -#define COMPILED_MERGED_MESHES_LIST "mmrm_used_meshes.lst" -#define LEVEL_INFO_FILE_NAME "levelinfo.xml" - -////////////////////////////////////////////////////////////////////////// - -#pragma pack(push,4) - -#define VISAREAMANAGER_CHUNK_VERSION 6 - -#define SERIALIZATION_FLAG_BIG_ENDIAN 1 -#define SERIALIZATION_FLAG_SECTOR_PALETTES 2 - -#define TCH_FLAG2_AREA_ACTIVATION_IN_USE 1 - -struct SVisAreaManChunkHeader -{ - int8 nVersion; - int8 nDummy; - int8 nFlags; - int8 nFlags2; - int nChunkSize; - int nVisAreasNum; - int nPortalsNum; - int nOcclAreasNum; - - AUTO_STRUCT_INFO -}; - -struct SOcTreeNodeChunk -{ - int16 nChunkVersion; - int16 ucChildsMask; - AABB nodeBox; - int32 nObjectsBlockSize; - - AUTO_STRUCT_INFO -}; - -struct SHotUpdateInfo -{ - SHotUpdateInfo() - { - nHeigtmap = 1; - nObjTypeMask = ~0; - pVisibleLayerMask = NULL; - pLayerIdTranslation = NULL; - areaBox.Reset(); - } - - uint32 nHeigtmap; - uint32 nObjTypeMask; - const uint8* pVisibleLayerMask; - const uint16* pLayerIdTranslation; - AABB areaBox; - - AUTO_STRUCT_INFO -}; - -#define OCTREE_CHUNK_VERSION 29 - -//============================================================================================== - -// Summary: -// Common header for binary files used by 3dengine -struct SCommonFileHeader -{ - char signature[4]; // File signature, should be "CRY " - uint8 file_type; // File type - uint8 flags; // File common flags - uint16 version; // File version - - AUTO_STRUCT_INFO -}; - -struct IVisAreaCallback -{ - // - virtual ~IVisAreaCallback(){} - virtual void OnVisAreaDeleted(IVisArea* pVisArea) = 0; - // -}; - -struct IVisAreaManager -{ - // - virtual ~IVisAreaManager(){} - // Summary: - // Loads data into VisAreaManager engine from memory block. - virtual bool SetCompiledData(uint8* pData, int nDataSize, std::vector** ppStatObjTable, std::vector<_smart_ptr >** ppMatTable, bool bHotUpdate, SHotUpdateInfo* pExportInfo) = 0; - - // Summary: - // Saves data from VisAreaManager engine into memory block. - virtual bool GetCompiledData(uint8* pData, int nDataSize, std::vector** ppStatObjTable, std::vector<_smart_ptr >** ppMatTable, std::vector** ppStatInstGroupTable, EEndian eEndian, SHotUpdateInfo* pExportInfo = NULL) = 0; - - // Summary: - // Returns VisAreaManager data memory block size. - virtual int GetCompiledDataSize(SHotUpdateInfo* pExportInfo = NULL) = 0; - - // Summary: - // Returns the accumulated number of visareas and portals. - virtual int GetNumberOfVisArea() const = 0; - - // Summary: - // Returns the visarea interface based on the id (0..GetNumberOfVisArea()) it can be a visarea or a portal. - virtual IVisArea* GetVisAreaById(int nID) const = 0; - - virtual void AddListener(IVisAreaCallback* pListener) = 0; - virtual void RemoveListener(IVisAreaCallback* pListener) = 0; - - virtual void PrepareSegmentData(const AABB& box) = 0; - virtual void ReleaseInactiveSegments() = 0; - virtual bool CreateSegment(int nSID) = 0; - virtual bool DeleteSegment(int nSID, bool bDeleteNow) = 0; - virtual bool StreamCompiledData(uint8* pData, int nDataSize, int nSID, std::vector* pStatObjTable, std::vector<_smart_ptr >* pMatTable, std::vector* pStatInstGroupTable, const Vec2& vIndexOffset) = 0; - virtual void OffsetPosition(const Vec3& delta) = 0; - virtual void UpdateConnections() = 0; - // Summary: - // Clones all vis areas in a region of the level, offsetting and rotating them based - // on the values passed in. - // Arguments: - // offset - Offset amount, relative to the center of the region passed in. - // zRotation - Rotation around the z axis, in radians. - virtual void CloneRegion(const AABB& region, const Vec3& offset, float zRotation) = 0; - - // Summary: - // Removes all vis areas in a region of the level. - virtual void ClearRegion(const AABB& region) = 0; - - virtual void GetObjectsByType(PodArray& lstObjects, EERType objType, const AABB* pBBox, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - virtual void GetObjectsByFlags(uint dwFlags, PodArray& lstObjects) = 0; - - virtual void GetObjects(PodArray& lstObjects, const AABB* pBBox) = 0; - - virtual bool IsOutdoorAreasVisible() = 0; -}; - -struct SSkyLightRenderParams -{ - static const int skyDomeTextureWidth = 64; - static const int skyDomeTextureHeight = 32; - static const int skyDomeTextureSize = 64 * 32; - - static const int skyDomeTextureWidthBy8 = 8; - static const int skyDomeTextureWidthBy4Log = 4; // = log2(64/4) - static const int skyDomeTextureHeightBy2Log = 4; // = log2(32/2) - - SSkyLightRenderParams() - : m_pSkyDomeMesh(0) - , m_pSkyDomeTextureDataMie(0) - , m_pSkyDomeTextureDataRayleigh(0) - , m_skyDomeTexturePitch(0) - , m_skyDomeTextureTimeStamp(-1) - , m_partialMieInScatteringConst(0.0f, 0.0f, 0.0f, 0.0f) - , m_partialRayleighInScatteringConst(0.0f, 0.0f, 0.0f, 0.0f) - , m_sunDirection(0.0f, 0.0f, 0.0f, 0.0f) - , m_phaseFunctionConsts(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColor(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColorMieNoPremul(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColorRayleighNoPremul(0.0f, 0.0f, 0.0f, 0.0f) - , m_skyColorTop(0.0f, 0.0f, 0.0f) - , m_skyColorNorth(0.0f, 0.0f, 0.0f) - , m_skyColorEast(0.0f, 0.0f, 0.0f) - , m_skyColorSouth(0.0f, 0.0f, 0.0f) - , m_skyColorWest(0.0f, 0.0f, 0.0f) - { - } - - // Sky dome mesh - _smart_ptr m_pSkyDomeMesh; - - // temporarily add padding bytes to prevent fetching Vec4 constants below from wrong offset - uint32 dummy0; - uint32 dummy1; - - // Sky dome texture data - const void* m_pSkyDomeTextureDataMie; - const void* m_pSkyDomeTextureDataRayleigh; - size_t m_skyDomeTexturePitch; - int m_skyDomeTextureTimeStamp; - - int pad;//Enable 16 byte alignment for Vec4s - - // Sky dome shader constants - Vec4 m_partialMieInScatteringConst; - Vec4 m_partialRayleighInScatteringConst; - Vec4 m_sunDirection; - Vec4 m_phaseFunctionConsts; - Vec4 m_hazeColor; - Vec4 m_hazeColorMieNoPremul; - Vec4 m_hazeColorRayleighNoPremul; - - // Sky hemisphere colors - Vec3 m_skyColorTop; - Vec3 m_skyColorNorth; - Vec3 m_skyColorEast; - Vec3 m_skyColorSouth; - Vec3 m_skyColorWest; -}; - -struct SVisAreaInfo -{ - float fHeight; - Vec3 vAmbientColor; - bool bAffectedByOutLights; - bool bIgnoreSkyColor; - bool bSkyOnly; - float fViewDistRatio; - bool bDoubleSide; - bool bUseDeepness; - bool bUseInIndoors; - bool bOceanIsVisible; - bool bIgnoreGI; - bool bIgnoreOutdoorAO; - float fPortalBlending; -}; - -struct SDebugFPSInfo -{ - SDebugFPSInfo() - : fAverageFPS(0.0f) - , fMaxFPS(0.0f) - , fMinFPS(0.0f) - { - } - float fAverageFPS; - float fMinFPS; - float fMaxFPS; -}; - -struct SRainParams -{ - SRainParams() - : fAmount(0.f) - , fCurrentAmount(0.f) - , fRadius(0.f) - , nUpdateFrameID(-1) - , bIgnoreVisareas(false) - , bDisableOcclusion(false) - , matOccTrans(IDENTITY) - , matOccTransRender(IDENTITY) - , qRainRotation(IDENTITY) - , areaAABB(AABB::RESET) - , bApplySkyColor(false) - , fSkyColorWeight(0.5f) - { - } - - Matrix44 matOccTrans; // Transformation matrix for rendering into a new occ map - Matrix44 matOccTransRender; // Transformation matrix for rendering occluded rain using current occ map - Quat qRainRotation; // Quaternion for the scene's rain entity rotation - AABB areaAABB; - - Vec3 vWorldPos; - Vec3 vColor; - - float fAmount; - float fCurrentAmount; - float fRadius; - - // Deferred rain params - float fFakeGlossiness; // unused - float fFakeReflectionAmount; // unused - float fDiffuseDarkening; - float fRainDropsAmount; - float fRainDropsSpeed; - float fRainDropsLighting; - float fMistAmount; - float fMistHeight; - float fPuddlesAmount; - float fPuddlesMaskAmount; - float fPuddlesRippleAmount; - float fSplashesAmount; - - int nUpdateFrameID; - - bool bApplyOcclusion; - bool bIgnoreVisareas; - bool bDisableOcclusion; - -// Summary: -// Common scene rain parameters shared across engine and editor - bool bApplySkyColor; - float fSkyColorWeight; - - // Bus ID to listen to -}; - -struct SSnowParams -{ - SSnowParams() - : m_vWorldPos(0, 0, 0) - , m_fRadius(0.0) - , m_fSnowAmount(0.0) - , m_fFrostAmount(0.0) - , m_fSurfaceFreezing(0.0) - , m_nSnowFlakeCount(0) - , m_fSnowFlakeSize(0.0) - , m_fSnowFallBrightness(0.0) - , m_fSnowFallGravityScale(0.0) - , m_fSnowFallWindScale(0.0) - , m_fSnowFallTurbulence(0.0) - , m_fSnowFallTurbulenceFreq(0.0) - { - } - - Vec3 m_vWorldPos; - float m_fRadius; - - // Surface params. - float m_fSnowAmount; - float m_fFrostAmount; - float m_fSurfaceFreezing; - - - // Snowfall params. - int m_nSnowFlakeCount; - float m_fSnowFlakeSize; - float m_fSnowFallBrightness; - float m_fSnowFallGravityScale; - float m_fSnowFallWindScale; - float m_fSnowFallTurbulence; - float m_fSnowFallTurbulenceFreq; -}; - - -struct IScreenshotCallback -{ - // - virtual ~IScreenshotCallback(){} - virtual void SendParameters(void* data, uint32 width, uint32 height, f32 minx, f32 miny, f32 maxx, f32 maxy) = 0; - // -}; - -class IStreamedObjectListener -{ -public: - // - virtual void OnCreatedStreamedObject(const char* filename, void* pHandle) = 0; - virtual void OnRequestedStreamedObject(void* pHandle) = 0; - virtual void OnReceivedStreamedObject(void* pHandle) = 0; - virtual void OnUnloadedStreamedObject(void* pHandle) = 0; - virtual void OnBegunUsingStreamedObjects(void** pHandles, size_t numHandles) = 0; - virtual void OnEndedUsingStreamedObjects(void** pHandles, size_t numHandles) = 0; - virtual void OnDestroyedStreamedObject(void* pHandle) = 0; - // -protected: - virtual ~IStreamedObjectListener() {} -}; - -#pragma pack(push, 16) - -struct SFogVolumeData -{ - AABB avgAABBox; - ColorF fogColor; - int m_volumeType; - Vec3 m_heightFallOffBasePoint; - float m_densityOffset; - Vec3 m_heightFallOffDirScaled; - float m_globalDensity; - - SFogVolumeData() : - avgAABBox(AABB::RESET), - m_globalDensity(0.0f), - m_densityOffset(0.0f), - m_volumeType(0), - m_heightFallOffBasePoint(Vec3(0, 0, 0)), - m_heightFallOffDirScaled(Vec3(0, 0, 0)), - fogColor(ColorF(1.0f, 1.0f, 1.0f, 1.0f)) - { - } - -}; - -// Summary: -// Light volumes data - -#define LIGHTVOLUME_MAXLIGHTS 16 - -struct SLightVolume -{ - struct SLightData - { - SLightData() - : vPos(0, 0, 0, 0) - , vColor(0, 0, 0, 0) - , vParams(0, 0, 0, 0) {} - SLightData(const Vec4& vInPos, const Vec4& vInColor, const Vec4& vInParams) - : vPos(vInPos) - , vColor(vInColor) - , vParams(vInParams) {} - - Vec4 vPos; - Vec4 vColor; - Vec4 vParams; - }; - - SLightVolume() - { - pData.reserve(LIGHTVOLUME_MAXLIGHTS); - } - - typedef DynArray LightDataVector; - - DEFINE_ALIGNED_DATA(LightDataVector, pData, 16); -}; - -#pragma pack(pop) - -struct CRNTmpData -{ - struct SRNUserData - { - int m_narrDrawFrames[MAX_RECURSION_LEVELS]; - SLodDistDissolveTransitionState lodDistDissolveTransitionState; - Matrix34 objMat; - OcclusionTestClient m_OcclState; - struct IClipVolume* m_pClipVolume; - SBending m_Bending; - SBending m_BendingPrev; - Vec3 vCurrentWind; - uint32 nBendingLastFrame : 29; - uint32 bWindCurrent : 1; - uint32 bBendingSet : 1; - uint16 nCubeMapId; - uint16 nCubeMapIdCacheClearCounter; - uint8 nWantedLod; - CRenderObject* m_pRenderObject[MAX_STATOBJ_LODS_NUM]; - CRenderObject* m_arrPermanentRenderObjects[MAX_STATOBJ_LODS_NUM]; - } userData; - - CRNTmpData() { memset(this, 0, sizeof(*this)); assert((void*)this == (void*)&this->userData); nPhysAreaChangedProxyId = ~0; } - CRNTmpData* pNext, * pPrev; - CRNTmpData** pOwnerRef; - uint32 nFrameInfoId; - uint32 nPhysAreaChangedProxyId; - - void Unlink() - { - if (!pNext || !pPrev) - { - return; - } - pNext->pPrev = pPrev; - pPrev->pNext = pNext; - pNext = pPrev = NULL; - } - - void Link(CRNTmpData* Before) - { - if (pNext || pPrev) - { - return; - } - pNext = Before->pNext; - Before->pNext->pPrev = this; - Before->pNext = this; - pPrev = Before; - } - - int Count() - { - int nCounter = 0; - for (CRNTmpData* pElem = pNext; pElem != this; pElem = pElem->pNext) - { - nCounter++; - } - return nCounter; - } - - void OffsetPosition(const Vec3& delta) - { - userData.objMat.SetTranslation(userData.objMat.GetTranslation() + delta); - } -}; - - -// Summary: -// Interface to the 3d Engine. -struct I3DEngine - : public IProcess -{ - struct SObjectsStreamingStatus - { - int nReady; - int nInProgress; - int nTotal; - int nActive; - int nAllocatedBytes; - int nMemRequired; - int nMeshPoolSize; // in MB - - }; - - struct OceanAnimationData - { - float fWindDirection; - float fWindSpeed; - float fWavesSpeed; - float fWavesAmount; - float fWavesSize; - float fWindDirectionU; - float fWindDirectionV; - }; - - struct SStremaingBandwidthData - { - SStremaingBandwidthData() - { - memset(this, 0, sizeof(SStremaingBandwidthData)); - } - float fBandwidthActual; - float fBandwidthRequested; - }; - - enum eStreamingSubsystem - { - eStreamingSubsystem_Textures, - eStreamingSubsystem_Objects, - eStreamingSubsystem_Audio, - }; - - using LoadStaticObjectAsyncResult = AZStd::function)>; - - struct StaticObjectAsyncLoadRequest - { - StaticObjectAsyncLoadRequest() = default; - - LoadStaticObjectAsyncResult m_callback; - string m_filename; - string m_geomName; - bool m_useStreaming; - unsigned long m_loadingFlags; - }; - - struct CausticsParams - { - float tiling = 0.0f; - float distanceAttenuation = 0.0f; - float height = 0.0f; - float depth = 0.0f; - float intensity = 0.0f; - }; - - - // - // Summary: - // Initializes the 3D Engine. - // See Also: - // ShutDown - // Notes: - // Only call once, after creating the instance. - virtual bool Init() = 0; - - - // Summary: - // Sets the path used to load levels. - // See Also: - // LoadLevel - // Arguments: - // szFolderName - Should contains the folder to be used - virtual void SetLevelPath(const char* szFolderName) = 0; - - virtual bool CheckMinSpec(uint32 nMinSpec) = 0; - - virtual void PrepareOcclusion(const CCamera& rCamera) = 0; - virtual void EndOcclusion() = 0; - // Description: - // Will load a level from the folder specified with SetLevelPath. If a - // level is already loaded, the resources will be deleted before. - // See Also: - // SetLevelPath - // Arguments: - // szFolderName - Name of the subfolder to load - // szMissionName - Name of the mission - // Return Value: - // A boolean which indicate the result of the function; true is - // succeed, or false if failed. - // Summary: - // Load a level. - virtual bool LoadLevel(const char* szFolderName, const char* szMissionName) = 0; - virtual bool InitLevelForEditor(const char* szFolderName, const char* szMissionName) = 0; - virtual bool LevelLoadingInProgress() = 0; - // Summary: - // Handles any work needed at start of new frame. - // Notes: - // Should be called for every frame. - virtual void OnFrameStart() = 0; - - // Description: - // Must be called after the game completely finishes loading the level. - // 3D engine uses it to pre-cache some resources needed for rendering. - // See Also: - // LoadLevel - // Summary: - // Pre-caches some resources need for rendering. - virtual void PostLoadLevel() = 0; - - // Description: - // Loads the required assets for a null level. - virtual void LoadEmptyLevel() = 0; - - // Summary: - // Clears all rendering resources, all objects, characters and materials, voxels and terrain. - // Notes: - // Should always be called before LoadLevel, and also before loading textures from a script. - virtual void UnloadLevel() = 0; - - - // Summary: - // Updates the 3D Engine. - // Notes: - // Should be called for every frame. - virtual void Update() = 0; - - // Summary: - // Returns the Camera used for Rendering on 3DEngine Side, normaly equal to the view camera, except if frozen with e_camerafreeze - // Notes: - // Only valid during RenderWorld(else the camera of the last frame is used) - // This is the camera which should be used for all Engine side culling (since e_camerafreeze allows easy debugging then) - virtual const CCamera& GetRenderingCamera() const = 0; - virtual float GetZoomFactor() const = 0; - - // Summary: - // clear all per frame temp data used in SRenderingPass - virtual void Tick() = 0; - - // Summary: - // Update all ShaderItems flags, only required after shaders were reloaded at runtime - virtual void UpdateShaderItems() = 0; - - // Summary: - // Deletes the 3D Engine instance. - virtual void Release() = 0; - - // Summary: - // Draws the world. - // See Also: - // SetCamera - // Arguments: - // szDebugName - name that can be visualized for debugging purpose, must not be 0 - virtual void RenderWorld(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName) = 0; - - virtual void RenderSceneReflection(int nRenderFlags, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Prepares for the world stream update, should be called before rendering - virtual void PreWorldStreamUpdate(const CCamera& cam) = 0; - - // Summary: - // Performs the actual world streaming update. PreWorldStreamUpdate must be called before - virtual void WorldStreamUpdate() = 0; - - // Summary: - // Shuts down the 3D Engine. - virtual void ShutDown() = 0; - - // Summary: - // Loads a static object from a CGF file. Does not increment the static object's reference counter. The reference returned is not guaranteed to be valid when run outside the main thread. Best used for priming the cache - // See Also: - // IStatObj - // Arguments: - // fileName - CGF Filename - should not be 0 or "" - // geomName - Optional name of geometry inside CGF. - // subObject - [Out]Optional Out parameter,Pointer to the - // loadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, defined in IMaterial.h, under the interface IMaterialManager. - // data - Raw buffer contain CGF data. - // dataSize - Size of the raw data buffer. - // Return Value: - // A pointer to an object derived from IStatObj. - virtual IStatObj* LoadStatObjUnsafeManualRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr, - bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) = 0; - - // Summary: - // Loads a static object from a CGF file. Increments the static object's reference counter. This method is threadsafe. Not suitable for preloading - // See Also: - // IStatObj - // Arguments: - // fileName - CGF Filename - should not be 0 or "", even if data is provided. - // geomName - Optional name of geometry inside CGF. - // subObject - [Out]Optional Out parameter,Pointer to the - // loadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, defined in IMaterial.h, under the interface IMaterialManager. - // data - Raw buffer contain CGF data. - // dataSize - Size of the raw data buffer. - // Return Value: - // A smart pointer to an object derived from IStatObj. - virtual _smart_ptr LoadStatObjAutoRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr, - bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) = 0; - - // Summary: - // Flushes queued async mesh loads. - virtual void ProcessAsyncStaticObjectLoadRequests() = 0; - - // Summary: - // Loads a static object from a CGF file asynchronously and invokes a callback on completion. - // Actual load will occur on the main thread. - // See Also: - // IStatObj - // Arguments: - // callback - The user callback to invoke on completion. - // szFileName - CGF Filename - should not be 0 or "" - // szGeomName - Optional name of geometry inside CGF. - // ppSubObject - [Out]Optional Out parameter,Pointer to the - // nLoadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, - // defined in IMaterial.h, under the interface IMaterialManager. - // Return Value: - // None - virtual void LoadStatObjAsync(LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName = nullptr, bool bUseStreaming = true, unsigned long nLoadingFlags = 0) = 0; - - // Summary: - // Finds a static object created from the given filename - // See Also: - // IStatObj - // Arguments: - // szFileName - CGF Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IStatObj. - virtual IStatObj* FindStatObjectByFilename(const char* filename) = 0; - - // Summary: - // Gets gsm range - // Return Value: - // An integer representing the gsm range. - virtual const float GetGSMRange() = 0; - - // Summary: - // Gets gsm range step - // Return Value: - // An integer representing the gsm range step - virtual const float GetGSMRangeStep() = 0; - - // Summary: - // Gets the amount of loaded objects. - // Return Value: - // An integer representing the amount of loaded objects. - virtual int GetLoadedObjectCount() { return 0; } - - // Summary: - // Fills pObjectsArray with pointers to loaded static objects - // if pObjectsArray is NULL only fills nCount parameter with amount of loaded objects. - virtual void GetLoadedStatObjArray(IStatObj** pObjectsArray, int& nCount) = 0; - - // Summary: - // Gets stats on streamed objects - virtual void GetObjectsStreamingStatus(SObjectsStreamingStatus& outStatus) = 0; - - // Summary: - // Gets stats on the streaming bandwidth requests from subsystems - // Arguments: - // subsystem - the streaming subsystem we want bandwidth data for - // outData - structure containing the bandwidth data for the subsystem requested - virtual void GetStreamingSubsystemData(int subsystem, SStremaingBandwidthData& outData) = 0; - - // Summary: - // Registers an entity to be rendered. - // Arguments: - // pEntity - The entity to render - virtual void RegisterEntity(IRenderNode* pEntity, int nSID = -1, int nSIDConsideredSafe = -1) = 0; - - // Summary: - // Selects an entity for debugging. - // Arguments: - // pEntity - The entity to render - virtual void SelectEntity(IRenderNode* pEntity) = 0; - - ////////////////////////////////////////////// - // Start Confetti ////////////////////////// - // Summary: - // Return the setting for sun shadows. Return false for sub classes without sun shadows settings. - virtual bool IsSunShadows(){ return false; }; - // End Confetti////////////////////////////// - ////////////////////////////////////////////// - - // Summary: - // Offers same functionality as Cry3DEngineBase::MakeSystemMaterialFromShader - virtual _smart_ptr MakeSystemMaterialFromShaderHelper(const char* sShaderName, SInputShaderResources* Res = NULL) = 0; - - virtual bool CheckMinSpecHelper(uint32 nMinSpec) = 0; - - virtual void OnCasterDeleted(IShadowCaster* pCaster) = 0; - - virtual void GetStatObjAndMatTables(DynArray* pStatObjTable, DynArray<_smart_ptr>* pMatTable, DynArray* pStatInstGroupTable, uint32 nObjTypeMask) = 0; - -#ifndef _RELEASE - enum EDebugDrawListAssetTypes - { - DLOT_ALL = 0, - DLOT_CHARACTER = BIT(2), - DLOT_STATOBJ = BIT(3) - }; - - struct SObjectInfoToAddToDebugDrawList - { - const char* pName; - const char* pClassName; - const char* pFileName; - IRenderNode* pRenderNode; - uint32 numTris; - uint32 numVerts; - uint32 texMemory; - uint32 meshMemory; - EDebugDrawListAssetTypes type; - const AABB* pBox; - const Matrix34* pMat; - }; - - virtual void AddObjToDebugDrawList(SObjectInfoToAddToDebugDrawList& objInfo) = 0; - virtual bool IsDebugDrawListEnabled() const = 0; -#endif - - - // Summary: - // Notices the 3D Engine to stop rendering a specified entity. - // Arguments: - // pEntity - The entity to stop render - virtual void UnRegisterEntityDirect(IRenderNode* pEntity) = 0; - virtual void UnRegisterEntityAsJob(IRenderNode* pEnt) = 0; - // Summary: - // Returns whether a world pos is under water. - virtual bool IsUnderWater(const Vec3& vPos) const = 0; - - // Summary: - // Returns whether ocean volume is visible or not. - virtual void SetOceanRenderFlags(uint8 nFlags) = 0; - virtual uint8 GetOceanRenderFlags() const = 0; - virtual uint32 GetOceanVisiblePixelsCount() const = 0; - - // Summary: - // Gets the closest walkable bottom z straight beneath the given reference position. - // Notes: - // This function will take into account both the global terrain elevation and local voxel (or other solid walkable object). - // Arguments: - // referencePos - Position from where to start searching downwards. - // maxRelevantDepth - Max depth caller is interested in relative to referencePos (for ray casting performance reasons). - // objtypes - expects physics entity flags. Use this to specify what object types make a valid bottom for you. - // Return Value: - // A float value which indicate the global world z of the bottom level beneath the referencePos. - // If the referencePos is below terrain but not inside any voxel area BOTTOM_LEVEL_UNKNOWN is returned. - virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth, int objtypes) = 0; - // A set of overloads for enabling users to use different sets of input params. Basically, only - // referencePos is mandatory. The overloads as such don't need to be virtual but this seems to be - // a purely virtual interface. - virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth = 10.0f) = 0; - virtual float GetBottomLevel(const Vec3& referencePos, int objflags) = 0; - - // Summary: - // Gets the ocean water level. Fastest option, always prefer is only ocean height required. - // Notes: - // This function will take into account just the global water level. - // Return Value: - // A float value which indicate the water level. In case no water was - // found at the specified location, the value WATER_LEVEL_UNKNOWN will - // be returned. - virtual float GetWaterLevel() = 0; - - // Summary: - // Gets the closest walkable bottom z straight beneath the given reference position. - // - Use with caution the accurate query - SLOW - // Notes: - // This function will take into account both the global water level and any water volume present. - // Function is provided twice for performance with diff. arguments. - // Arguments: - // pvPos - Desired position to inspect the water level - // pent - Pointer to return the physical entity to test against (optional) - // Return Value: - // A float value which indicate the water level. In case no water was - // found at the specified location, the value WATER_LEVEL_UNKNOWN will - // be returned. - virtual float GetWaterLevel(const Vec3* pvPos, IPhysicalEntity* pent = NULL, bool bAccurate = false) = 0; - - // Summary: - // Gets the ocean water level for a specified position. - // - Use with caution the accurate query - SLOW - // Notes: - // This function only takes into account ocean water. - // Arguments: - // pCurrPos - Position to check water level - // Return Value: - // A float value which indicate the water level. - virtual float GetAccurateOceanHeight(const Vec3& pCurrPos) const = 0; - - // Summary: - // Gets caustics parameters. - virtual CausticsParams GetCausticsParams() const = 0; - - // Summary: - // Gets ocean animation parameters. - virtual OceanAnimationData GetOceanAnimationParams() const = 0; - - // Summary: - // Gets HDR setup parameters. - // Return Value: - virtual void GetHDRSetupParams (Vec4 pParams[5]) const = 0; - - // Summary: - // Removes all particles and decals from the world. - virtual void ResetParticlesAndDecals() = 0; - - // Summary: - // Creates new decals on the walls, static objects, terrain and entities. - // Arguments: - // Decal - Structure describing the decal effect to be applied - virtual void CreateDecal(const CryEngineDecalInfo& Decal) = 0; - - // Summary: - // Removes decals in a specified range. - // Arguments: - // vAreaBox - Specify the area in which the decals will be removed - // pEntity - if not NULL will only delete decals attached to this entity - virtual void DeleteDecalsInRange(AABB* pAreaBox, IRenderNode* pEntity) = 0; - - // Summary: - // Sets the current sun base color. - virtual void SetSunColor(Vec3 vColor) = 0; - - // Summary: - // Gets the current sun animated color. - virtual Vec3 GetSunAnimColor() = 0; - - // Summary: - // Sets the current sky brightening multiplier. - virtual void SetSunAnimColor(const Vec3& color) = 0; - - // Summary: - // Sets the current sun animation speed. - virtual float GetSunAnimSpeed() = 0; - - // Summary: - virtual void SetSunAnimSpeed(float sunAnimSpeed) = 0; - - // Summary: - // Gets the current sun animation phase. - virtual AZ::u8 GetSunAnimPhase() = 0; - // Summary: - // Sets the current sun animation phase. - virtual void SetSunAnimPhase(AZ::u8 sunAnimPhase) = 0; - - // Summary: - // Gets the current sun animation index. - virtual AZ::u8 GetSunAnimIndex() = 0; - - // Summary: - // Sets the current sun animation index. - virtual void SetSunAnimIndex(AZ::u8 sunAnimIndex) = 0; - - // Summary: - // Sets current rain parameters. - virtual void SetRainParams(const SRainParams& rainParams) = 0; - - // Summary: - // Gets the validity and fills current rain parameters. - virtual bool GetRainParams(SRainParams& rainParams) = 0; - - // Summary: - // Sets current snow surface parameters. - virtual void SetSnowSurfaceParams(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing) = 0; - - // Summary: - // Gets current snow surface parameters. - virtual bool GetSnowSurfaceParams(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing) = 0; - - // Summary: - // Sets current snow parameters. - virtual void SetSnowFallParams(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq) = 0; - - // Summary: - // Gets current snow parameters. - virtual bool GetSnowFallParams(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq) = 0; - - // Summary: - // Sets the view distance scale. - // Arguments: - // fScale - may be between 0 and 1, 1.f = Unmodified view distance set by level designer, value of 0.5 will reduce it twice - // Notes: - // This value will be reset automatically to 1 on next level loading. - virtual void SetMaxViewDistanceScale(float fScale) = 0; - - // Summary: - // Gets the view distance. - // Return Value: - // A float value representing the maximum view distance. - virtual float GetMaxViewDistance(bool bScaled = true) = 0; - - virtual const SFrameLodInfo& GetFrameLodInfo() const = 0; - virtual void SetFrameLodInfo(const SFrameLodInfo& frameLodInfo) = 0; - - // Summary: - // Sets the fog color. - virtual void SetFogColor(const Vec3& vFogColor) = 0; - - // Summary: - // Gets the fog color. - virtual Vec3 GetFogColor() = 0; - - // Summary: - // Gets various sky light parameters. - virtual void GetSkyLightParameters(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths) = 0; - - // Summary: - // Sets various sky light parameters. - virtual void SetSkyLightParameters(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate = false) = 0; - - // Return Value: - // In logarithmic scale -4.0 .. 4.0 - virtual float GetLightsHDRDynamicPowerFactor() const = 0; - - // Return true if tessellation is allowed for given render object - virtual bool IsTessellationAllowed(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass = false) const = 0; - - // allows to modify material on render nodes at run-time (make sure it is properly restored back) - virtual void SetRenderNodeMaterialAtPosition(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat) = 0; - - // override the camera precache point with the requested position for the current round - virtual void OverrideCameraPrecachePoint(const Vec3& vPos) = 0; - - // begin streaming of meshes and textures for specified position, pre-cache stops after fTimeOut seconds - virtual int AddPrecachePoint(const Vec3& vPos, const Vec3& vDir, float fTimeOut = 3.f, float fImportanceFactor = 1.0f) = 0; - virtual void ClearPrecachePoint(int id) = 0; - virtual void ClearAllPrecachePoints() = 0; - - virtual void GetPrecacheRoundIds(int pRoundIds[MAX_STREAM_PREDICTION_ZONES]) = 0; - - virtual void TraceFogVolumes(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality) = 0; - - //DOC-IGNORE-BEGIN - - // Internal functions, mostly used by the editor, which won't be documented for now - - // Summary: - // Removes all static objects on the map (for editor) - virtual void RemoveAllStaticObjects(int nSID = DEFAULT_SID) = 0; - - // Summary: - // Sets group parameters - virtual bool SetStatInstGroup(int nGroupId, const IStatInstGroup& siGroup, int nSID = 0) = 0; - - // Summary: - // Gets group parameters - virtual bool GetStatInstGroup(int nGroupId, IStatInstGroup& siGroup, int nSID = 0) = 0; - - //DOC-IGNORE-END - - // Summary: - // Notifies of an explosion, and maybe creates an hole in the terrain - // Description: - // This function should usually make sure that no static objects are near before making the hole. - // Arguments: - // vPos - Position of the explosion - // fRadius - Radius of the explosion - // bDeformTerrain - Allow to deform the terrain - virtual void OnExplosion(Vec3 vPos, float fRadius, bool bDeformTerrain = true) = 0; - - // Summary: - // Sets the physics material enumerator - // Arguments: - // pPhysMaterialEnumerator - The physics material enumarator to set - virtual void SetPhysMaterialEnumerator(IPhysMaterialEnumerator* pPhysMaterialEnumerator) = 0; - - // Summary: - // Gets the physics material enumerator - // Return Value: - // A pointer to an IPhysMaterialEnumerator derived object. - virtual IPhysMaterialEnumerator* GetPhysMaterialEnumerator() = 0; - - //DOC-IGNORE-BEGIN - //Internal functions - - // Summary: - // Allows to enable fog in editor - virtual void SetupDistanceFog() = 0; - - // Summary: - // Loads environment settings for specified mission - virtual void LoadMissionDataFromXMLNode(const char* szMissionName) = 0; - - virtual void LoadEnvironmentSettingsFromXML(XmlNodeRef pInputNode, int nSID = DEFAULT_SID) = 0; - - // Summary: - // This one is called by the editor when the terrain editing tools are not being built. - // This is the case when the game developers are using external tools to author terrain. - // The Octree data and the terrain heightmap data are stored in the same file. - // This method makes sure only the non-terrain data of the Octree is loaded. - virtual bool LoadCompiledOctreeForEditor() = 0; - - //DOC-IGNORE-END - - //DOC-IGNORE-BEGIN - // Set direction to the sun - // virtual void SetSunDir( const Vec3& vNewSunDir ) = 0; - - // Summary: - // Return non-normalized direction to the sun - virtual Vec3 GetSunDir() const = 0; - - // Summary: - // Return normalized direction to the sun - virtual Vec3 GetSunDirNormalized() const = 0; - - // Summary: - // Return realtime (updated every frame with real sun position) normalized direction to the scene - virtual Vec3 GetRealtimeSunDirNormalized() const = 0; - - //Internal function used by 3d engine and renderer - // Summary: - // Gets distance to the sector containig ocean water - virtual float GetDistanceToSectorWithWater() = 0; - //DOC-IGNORE-END - - // Summary: - // Gets the sun color - // Notes: - // Should have been specified in the editor. - // Return Value: - // An rgb value contained in a Vec3 object. - virtual Vec3 GetSunColor() const = 0; - - // Summary: - // Retrieves the current SSAO multiplier - // Notes: - // Return Value: - // scalar value - virtual float GetSSAOAmount() const = 0; - - // Summary: - // Retrieves the current SSAO contrast multiplier - // Notes: - // Return Value: - // scalar value - virtual float GetSSAOContrast() const = 0; - // Summary: - // Frees entity render info. - virtual void FreeRenderNodeState(IRenderNode* pEntity) = 0; - - // Summary: - // Adds the level's path to a specified filename. - // Arguments: - // szFileName - The filename for which we need to add the path - // Return Value: - // Full path for the filename; including the level path and the filename appended after. - virtual const char* GetLevelFilePath(const char* szFileName) = 0; - - // Summary: - // Displays statistic on the 3d Engine. - // Arguments: - // fTextPosX - X position for the text - // fTextPosY - Y position for the text - // fTextStepY - Amount of pixels to distance each line - // bEnhanced - false=normal, true=more interesting information - virtual void DisplayInfo(float& fTextPosX, float& fTextPosY, float& fTextStepY, bool bEnhanced) = 0; - - // Summary: - // Displays CPU and GPU memory usage statistics on screen - virtual void DisplayMemoryStatistics() = 0; - - // Summary: - // Draws text right aligned at the y pixel precision. - virtual void DrawTextRightAligned(const float x, const float y, const char* format, ...) PRINTF_PARAMS(4, 5) = 0; - virtual void DrawTextRightAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...) PRINTF_PARAMS(6, 7) = 0; - - virtual void DrawBBoxHelper(const Vec3& vMin, const Vec3& vMax, ColorB col = Col_White) = 0; - virtual void DrawBBoxHelper(const AABB& box, ColorB col = Col_White) = 0; - - // Summary: - // Enables or disables portal at a specified position. - // Arguments: - // vPos - Position to place the portal - // bActivate - Set to true in order to enable the portal, or to false to disable - // szEntityName - - virtual void ActivatePortal(const Vec3& vPos, bool bActivate, const char* szEntityName) = 0; - - //DOC-IGNORE-BEGIN - // Summary: - // Counts memory usage - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Summary: - // Counts resource memory usage - // Arguments: - // cstAABB - Use the whole level AABB if you want to grab the resources - // from the whole level. For height level, use something BIG - // (ie: +-FLT_MAX) - virtual void GetResourceMemoryUsage(ICrySizer* pSizer, const AABB& cstAABB) = 0; - //DOC-IGNORE-END - - // Summary: - // Creates a new VisArea. - // Return Value: - // A pointer to a newly created VisArea object - virtual IVisArea* CreateVisArea(uint64 visGUID) = 0; - - // Summary: - // Deletes a VisArea. - // Arguments: - // pVisArea - A pointer to the VisArea to delete - virtual void DeleteVisArea(IVisArea* pVisArea) = 0; - - //mat: todo - - // Summary: - // Updates the VisArea - // Arguments: - // pArea - - // pPoints - - // nCount - - // szName - - // info - - // bReregisterObjects - - virtual void UpdateVisArea(IVisArea* pArea, const Vec3* pPoints, int nCount, const char* szName, const SVisAreaInfo& info, bool bReregisterObjects) = 0; - - // Summary: - // Determines if two VisAreas are connected. - // Description: - // Used to determine if a sound is potentially hearable between two VisAreas. - // Arguments: - // pArea1 - A pointer to a VisArea - // pArea2 - A pointer to a VisArea - // nMaxRecursion - Maximum number of recursions to be done - // bSkipDisabledPortals - Indicate if disabled portals should be skipped - // Return Value: - // A boolean value set to true if the two VisAreas are connected, else false will be returned. - virtual bool IsVisAreasConnected(IVisArea* pArea1, IVisArea* pArea2, int nMaxRecursion = 1, bool bSkipDisabledPortals = true) = 0; - - // Summary: - // Creates a ClipVolume. - // Return Value: - // A pointer to a newly created ClipVolume object - virtual IClipVolume* CreateClipVolume() = 0; - - // Summary: - // Deletes a ClipVolume. - // Arguments: - // pClipVolume - A pointer to the ClipVolume to delete - virtual void DeleteClipVolume(IClipVolume* pClipVolume) = 0; - - // Summary: - // Updates a ClipVolume - // Arguments: - // pClipVolume - Pointer to volume that needs updating - // pRenderMesh - Pointer to new render mesh - // worldTM - Updated world transform - // szName - Updated ClipVolume name - virtual void UpdateClipVolume(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName) = 0; - - //mat: todo - - // Summary: - // Creates instance of IRenderNode object with specified type. - virtual IRenderNode* CreateRenderNode(EERType type) = 0; - - // Summary: - // Delete RenderNode object. - virtual void DeleteRenderNode(IRenderNode* pRenderNode) = 0; - - - // Summary: - // Gets wind direction and force, averaged within a box. - virtual Vec3 GetWind(const AABB& box, bool bIndoors) const = 0; - - // Summary: - // Gets the global wind vector. - virtual Vec3 GetGlobalWind(bool bIndoors) const = 0; - - // Summary: - // Gets wind direction and forace at the sample points provided. - // Note: the positions defining the samples will be overwritten - // with the accumulated wind influences. - virtual bool SampleWind(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors) const = 0; - - // Description: - // Gets the VisArea which is present at a specified point. - // Arguments: - // vPos: - // Return Value: - // VisArea containing point, if any. 0 otherwise. - virtual IVisArea* GetVisAreaFromPos(const Vec3& vPos) = 0; - - // Description: - // Tests for intersection against Vis Areas. - // Arguments: - // box: Volume to test for intersection. - // pNodeCache (out, optional): Set to a cached pointer, for quicker calls to ClipToVisAreas. - // Return Value: - // Whether box intersects any vis areas. - virtual bool IntersectsVisAreas(const AABB& box, void** pNodeCache = 0) = 0; - - // Description: - // Clips geometry against the boundaries of VisAreas. - // Arguments: - // pInside: Vis Area to clip inside of. If 0, clip outside all Vis Areas. - // sphere - - // vNormal - - // pNodeChache - - // Return Value: - // Whether it was clipped - virtual bool ClipToVisAreas(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache = 0) = 0; - - // Summary: - // Enables or disables ocean rendering. - // Arguments: - // bOcean - Will enable or disable the rendering of ocean - virtual void EnableOceanRendering(bool bOcean) = 0; - - // Description: - // Register a texture load handler - virtual void AddTextureLoadHandler(ITextureLoadHandler* pHandler) = 0; - - // Description - // Unregister a texture load handler - virtual void RemoveTextureLoadHandler(ITextureLoadHandler* pHandler) = 0; - - // Description: - // Get a texture load handler for a given extension - virtual ITextureLoadHandler* GetTextureLoadHandlerForImage(const char* ext) = 0; - // Summary: - // Creates a new light source. - // Return Value: - // Pointer to newly created light or -1 if it fails. - virtual struct ILightSource* CreateLightSource() = 0; - - // Summary: - // Deletes a light. - // Arguments: - // Pointer to the light - virtual void DeleteLightSource(ILightSource* pLightSource) = 0; - - // Summary: - // Gives access to the list holding all static light sources - // Return Value: - // An array holding all the CDLight pointers. - virtual const PodArray* GetLightEntities() = 0; - - // Summary: - // Gives access to list holding all lighting volumes - // Return Value: - // An array holding all the SLightVolume pointers. - virtual void GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols) = 0; - - // Summary: - // Registers a volume for lighting - // Return Value: - // The index of the registered volume. - virtual uint16 RegisterVolumeForLighting(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Reload the heightmap. - // Description: - // Reloading the heightmap will resets all decals and particles. - // Notes: - // In future will restore deleted vegetations - // Returns: - // success - virtual bool RestoreTerrainFromDisk(int nSID = 0) = 0; - - //DOC-IGNORE-BEGIN - // tmp - virtual const char* GetFilePath(const char* szFileName) { return GetLevelFilePath(szFileName); } - //DOC-IGNORE-END - - // Summary: - // Post processing effects interfaces. - virtual class IPostEffectGroupManager* GetPostEffectGroups() const = 0; - virtual class IPostEffectGroup* GetPostEffectBaseGroup() const = 0; - - // Most code should use either GetPostEffectGroups() or GetPostEffectBaseGroup() instead of these - virtual void SetPostEffectParam(const char* pParam, float fValue, bool bForceValue = false) const = 0; - virtual void SetPostEffectParamVec4(const char* pParam, const Vec4& pValue, bool bForceValue = false) const = 0; - virtual void SetPostEffectParamString(const char* pParam, const char* pszArg) const = 0; - - virtual void GetPostEffectParam(const char* pParam, float& fValue) const = 0; - virtual void GetPostEffectParamVec4(const char* pParam, Vec4& pValue) const = 0; - virtual void GetPostEffectParamString(const char* pParam, const char*& pszArg) const = 0; - - virtual int32 GetPostEffectID(const char* pPostEffectName) = 0; - - virtual void ResetPostEffects(bool bOnSpecChange = false) = 0; - //Disable post effect groups other than default and base. - virtual void DisablePostEffects() = 0; - - virtual void SetShadowsGSMCache(bool bCache) = 0; - virtual void SetCachedShadowBounds(const AABB& shadowBounds, float fAdditionalCascadesScale) = 0; - virtual void SetRecomputeCachedShadows(uint nUpdateStrategy = 0) = 0; - - // Summary: - // In debug mode check memory heap and makes assert, do nothing in release - virtual void CheckMemoryHeap() = 0; - - // Summary: - // Removes all decals attached to specified entity. - virtual void DeleteEntityDecals(IRenderNode* pEntity) = 0; - - // Summary: - // Disables CGFs unloading. - virtual void LockCGFResources() = 0; - - // Summary: - // Enables CGFs unloading (this is default state), this function will also release all not used CGF's. - virtual void UnlockCGFResources() = 0; - - // Summary: - // Release all unused CGFs. - virtual void FreeUnusedCGFResources() = 0; - - - // Summary: - // Creates static object containing empty IndexedMesh. - virtual IStatObj* CreateStatObj() = 0; - virtual IStatObj* CreateStatObjOptionalIndexedMesh(bool createIndexedMesh) = 0; - - // Summary: - // Creates the instance of the indexed mesh. - virtual IIndexedMesh* CreateIndexedMesh() = 0; - - // Summary: - // Saves/loads state of engine objects. - virtual void SerializeState(TSerialize ser) = 0; - - // Summary: - // Cleanups after save/load. - virtual void PostSerialize(bool bReading) = 0; - - // Description: - // Retrieve pointer to the material i/o interface. - virtual IMaterialHelpers& GetMaterialHelpers() = 0; - - // Description: - // Retrieve pointer to the material manager interface. - virtual IMaterialManager* GetMaterialManager() = 0; - - // Description: - // Retrieve pointer to the object manager interface. - virtual IObjManager* GetObjManager() = 0; - - ////////////////////////////////////////////////////////////////////////// - // CGF Loader. - ////////////////////////////////////////////////////////////////////////// - // Description: - // Creates a chunkfile content instance - // Returns 'NULL' if the memory for the instance could not be allocated - virtual CContentCGF* CreateChunkfileContent(const char* filename) = 0; - - // Description: - // Deletes the chunkfile content instance - virtual void ReleaseChunkfileContent(CContentCGF*) = 0; - - // Description: - // Loads the contents of a chunkfile into the given CContentCGF. - // Returns 'false' on error. - virtual bool LoadChunkFileContent(CContentCGF* pCGF, const char* filename, bool bNoWarningMode = false, bool bCopyChunkFile = true) = 0; - - // Description: - // Loads the contents of a chunkfile into the given CContentCGF. - // Returns 'false' on error. - virtual bool LoadChunkFileContentFromMem(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode = false, bool bCopyChunkFile = true) = 0; - - // Description: - // Creates ChunkFile. - virtual IChunkFile* CreateChunkFile(bool bReadOnly = false) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Chunk file writer. - ////////////////////////////////////////////////////////////////////////// - enum EChunkFileFormat - { - eChunkFileFormat_0x745, - eChunkFileFormat_0x746, - }; - virtual ChunkFile::IChunkFileWriter* CreateChunkFileWriter(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename) const = 0; - virtual void ReleaseChunkFileWriter(ChunkFile::IChunkFileWriter* p) const = 0; - - // Description: - // Returns true if the ocean was created successfully. - virtual bool CreateOcean(_smart_ptr pTerrainWaterMat, float waterLevel) = 0; - - // Description: - // Deletes the ocean if it exists, otherwise does nothing. - virtual void DeleteOcean() = 0; - - // Description: - // Changes ocean material if the ocean exists. - virtual void ChangeOceanMaterial(_smart_ptr pMat) = 0; - - // Description: - // Changes ocean water level if the ocean exists. - virtual void ChangeOceanWaterLevel(float fWaterLevel) = 0; - - virtual void InitMaterialDefautMappingAxis(_smart_ptr pMat) = 0; - - // Description: - // Returns interface to visarea manager. - virtual IVisAreaManager* GetIVisAreaManager() = 0; - - // Description: - // Places camera into every visarea or every manually set pre-cache points and render the scenes. - virtual void PrecacheLevel(bool bPrecacheAllVisAreas, Vec3* pPrecachePoints, int nPrecachePointsNum) = 0; - - // Description: - // Proposes 3dengine to load on next frame all shaders and textures synchronously. - virtual void ProposeContentPrecache() = 0; - - - - // Description: - // Returns TOD interface. - virtual ITimeOfDay* GetTimeOfDay() = 0; - - // Description: - // Updates the sky material paths. LoadSkyMaterial will handle loading these materials. - virtual void SetSkyMaterialPath(const string& skyMaterialPath) = 0; - virtual void SetSkyLowSpecMaterialPath(const string& skyMaterialPath) = 0; - - // Description: - // Loads the sky material for the level. e_SkyType will determine if we load the low spec sky material or the regular sky material. - virtual void LoadSkyMaterial() = 0; - - // Description: - // Returns SkyBox material. - virtual _smart_ptr GetSkyMaterial() = 0; - - // Description: - // Sets SkyBox Material. - virtual void SetSkyMaterial(_smart_ptr pSkyMat) = 0; - - // Description: - // Sets global 3d engine parameter. - virtual void SetGlobalParameter(E3DEngineParameter param, const Vec3& v) = 0; - void SetGlobalParameter(E3DEngineParameter param, float val) { SetGlobalParameter(param, Vec3(val, 0, 0)); }; - - // Description: - // Retrieves global 3d engine parameter. - virtual void GetGlobalParameter(E3DEngineParameter param, Vec3& v) = 0; - float GetGlobalParameter(E3DEngineParameter param) { Vec3 v(0, 0, 0); GetGlobalParameter(param, v); return v.x; }; - - virtual void SetShadowMode(EShadowMode shadowMode) = 0; - virtual EShadowMode GetShadowMode() const = 0; - virtual void AddPerObjectShadow(IShadowCaster* pCaster, float fConstBias, float fSlopeBias, float fJitter, const Vec3& vBBoxScale, uint nTexSize) = 0; - virtual void RemovePerObjectShadow(IShadowCaster* pCaster) = 0; - virtual struct SPerObjectShadow* GetPerObjectShadow(IShadowCaster* pCaster) = 0; - virtual void GetCustomShadowMapFrustums(struct ShadowMapFrustum*& arrFrustums, int& nFrustumCount) = 0; - - // Description: - // Saves pStatObj to a stream. - // Notes: - // Full mesh for generated ones, path/geom otherwise - virtual int SaveStatObj(IStatObj* pStatObj, TSerialize ser) = 0; - // Description: - // Loads statobj from a stream - virtual IStatObj* LoadStatObj(TSerialize ser) = 0; - - // Description: - // Returns true if input line segment intersect clouds sprites. - virtual bool CheckIntersectClouds(const Vec3& p1, const Vec3& p2) = 0; - - // Description: - // Removes references to RenderMesh - virtual void OnRenderMeshDeleted(IRenderMesh* pRenderMesh) = 0; - - // Used to highlight an object under the reticule - virtual void DebugDraw_UpdateDebugNode() = 0; - - // Description: - // Used by editor during AO computations - virtual bool RayObjectsIntersection2D(Vec3 vStart, Vec3 vEnd, Vec3& vHitPoint, EERType eERType) = 0; - - - // Description: - // Used by editor during object alignment - virtual bool RenderMeshRayIntersection(IRenderMesh* pRenderMesh, SRayHitInfo& hitInfo, _smart_ptr pCustomMtl = 0) = 0; - - virtual void CheckCreateRNTmpData(CRNTmpData** ppInfo, IRenderNode* pRNode, const SRenderingPassInfo& passInfo) = 0; - - // Description: - // Frees lod transition state - virtual void FreeRNTmpData(CRNTmpData** ppInfo) = 0; - - // Description: - // Returns true if the Octree is ready. - virtual bool IsObjectTreeReady() = 0; - - virtual IOctreeNode* GetIObjectTree() = 0; - - // Description: - // Call function 2 times (first to get the size then to fill in the data) - // Arguments: - // pObjects - 0 if only the count is required - // Return Value: - // Count returned - virtual uint32 GetObjectsByType(EERType objType, IRenderNode** pObjects = 0) = 0; - virtual uint32 GetObjectsByTypeInBox(EERType objType, const AABB& bbox, IRenderNode** pObjects = 0, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - virtual uint32 GetObjectsInBox(const AABB& bbox, IRenderNode** pObjects = 0) = 0; - virtual uint32 GetObjectsByFlags(uint dwFlag, IRenderNode** pObjects = 0) = 0; - - // variant which takes a POD array which is resized in the function itself - virtual void GetObjectsByTypeInBox(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - - // Called from editor whenever an object is modified by the user - virtual void OnObjectModified(IRenderNode* pRenderNode, uint dwFlags) = 0; - - virtual void FillDebugFPSInfo(SDebugFPSInfo&) = 0; - - virtual const char* GetLevelFolder() = 0; - - virtual bool IsAreaActivationInUse() = 0; - - virtual void RenderRenderNode_ShadowPass(IShadowCaster* pRNode, const SRenderingPassInfo& passInfo, AZ::LegacyJobExecutor* pJobExecutor) = 0; - - virtual IOpticsManager* GetOpticsManager() = 0; - - // Description: - // Syncs and performs outstanding operations for the Asyncrhon ProcessStreaming Update - virtual void SyncProcessStreamingUpdate() = 0; - - // Set Callback for Editor to store additional information in Minimap tool - virtual void SetScreenshotCallback(IScreenshotCallback* pCallback) = 0; - - // Show/Hide objects by layer (useful for streaming and performance) - virtual void ActivateObjectsLayer(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap = NULL, bool bCheckLayerActivation = true) = 0; - - // Get object layer memory usage - virtual void GetLayerMemoryUsage(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals) const = 0; - - // Collect layer ID's to skip loading objects from these layers, e.g. to skip console specific layers - virtual void SkipLayerLoading(uint16 nLayerId, bool bClearList) = 0; - - // Activate streaming of render node and all sub-components - virtual void PrecacheRenderNode(IRenderNode* pObj, float fEntDistanceReal) = 0; - - virtual IDeferredPhysicsEventManager* GetDeferredPhysicsEventManager() = 0; - - virtual void SetStreamableListener(IStreamedObjectListener* pListener) = 0; - - // following functions are used by SRenderingPassInfo - virtual CCamera* GetRenderingPassCamera(const CCamera& rCamera) = 0; - - struct SSvoStaticTexInfo - { - SSvoStaticTexInfo() - { - ZeroStruct(*this); - } - - // SVO data pools - ITexture* pTexTree; - ITexture* pTexOpac; - ITexture* pTexRgb0; - ITexture* pTexRgb1; - ITexture* pTexDynl; - ITexture* pTexRgb2; - ITexture* pTexRgb3; - ITexture* pTexNorm; - ITexture* pTexAldi; - - ITexture* pGlobalSpecCM; - - float fGlobalSpecCM_Mult; - int nTexDimXY; - int nTexDimZ; - int nBrickSize; - bool bSvoReady; - bool bSvoFreeze; - }; - - struct SLightTI - { - Vec4 vPosR; - Vec4 vDirF; - Vec4 vCol; - float fSortVal; - class ITexture* pCM; - }; - - virtual void GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D) = 0; - - struct SSvoNodeInfo - { - AABB wsBox; - AABB tcBox; - int nAtlasOffset; - }; - - virtual void GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic) = 0; - -#if defined(USE_GEOM_CACHES) - // Summary: - // Loads a geometry cache from a CAX file. - // See Also: - // IGeomCache - // Arguments: - // szFileName - CAX Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IGeomCache. - virtual IGeomCache* LoadGeomCache(const char* szFileName) = 0; - - // Finds a geom cache created from the given filename - // See Also: - // IGeomCache - // Arguments: - // szFileName - CAX Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IGeomCache. - virtual IGeomCache* FindGeomCacheByFilename(const char* szFileName) = 0; -#endif - - // Summary: - // Loads a designer object from a stream of _decoded_ binary node. (Base64Decode) - // Arguments: - // szBinaryStream - decoded stream + size - virtual IStatObj* LoadDesignerObject(int nVersion, const char* szBinaryStream, int size) = 0; - - // Summary: - // Makes sure all queued culling jobs are completely finished. - // This is useful when adding or removing Components that trigger AZ::Job creation - // like the terrain system. It is important to complete those jobs before removing - // such type of components. - virtual void WaitForCullingJobsCompletion() = 0; - - // -}; - -#pragma pack(pop) - -#include - -// state of 3dengine during rendering -// used to prevent global state -struct SRenderingPassInfo -{ - enum EShadowMapType - { - SHADOW_MAP_NONE = 0, - SHADOW_MAP_GSM, - SHADOW_MAP_LOCAL, - SHADOW_MAP_CACHED, - SHADOW_MAP_CACHED_MGPU_COPY - }; - - // enum flags to identify which objects to skip for this pass - enum ESkipRenderingFlags - { - SHADOWS = BIT(0), - ENTITIES = BIT(3), - WATEROCEAN = BIT(5), - DECALS = BIT(7), - MERGED_MESHES = BIT(10), - ROADS = BIT(13), - WATER_VOLUMES = BIT(14), - CLOUDS = BIT(15), - CUBEMAP_GEN = BIT(16), - GEOM_CACHES = BIT(17), - DISABLE_RENDER_CHUNK_MERGE = BIT(18), - - // below are precombined flags - STATIC_OBJECTS = ENTITIES, - DEFAULT_FLAGS = SHADOWS | ENTITIES | WATEROCEAN | DECALS | MERGED_MESHES | ROADS | WATER_VOLUMES | CLOUDS | GEOM_CACHES, - DEFAULT_RECURSIVE_FLAGS = ENTITIES | WATEROCEAN | DECALS | MERGED_MESHES | ROADS | WATER_VOLUMES | CLOUDS | GEOM_CACHES - }; - - // creating function for RenderingPassInfo, the create functions will fetch all other necessary - // information like thread id/frame id, etc - static SRenderingPassInfo CreateGeneralPassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags = DEFAULT_FLAGS, bool bAuxWindow = false); - static SRenderingPassInfo CreateRecursivePassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags = DEFAULT_RECURSIVE_FLAGS); - static SRenderingPassInfo CreateShadowPassRenderingInfo(const CCamera& rCamera, int nLightFlags, int nShadowMapLod, bool bExtendedLod, bool bIsMGPUCopy, uint32* pShadowGenMask, uint32 nSide, uint32 nShadowFrustumID, uint32 nRenderingFlags = DEFAULT_FLAGS); - static SRenderingPassInfo CreateTempRenderingInfo(const CCamera& rCamera, const SRenderingPassInfo& rPassInfo); - static SRenderingPassInfo CreateTempRenderingInfo(uint32 nRenderingFlags, const SRenderingPassInfo& rPassInfo); - - // state getter - bool IsGeneralPass() const; - - bool IsRecursivePass() const; - uint32 GetRecursiveLevel() const; - - bool IsShadowPass() const; - bool IsCachedShadowPass() const; - EShadowMapType GetShadowMapType() const; - bool IsDisableRenderChunkMerge() const; - - bool IsAuxWindow() const; - - threadID ThreadID() const; - void SetThreadID(threadID id) { m_nThreadID = static_cast(id); } - - int GetFrameID() const; - uint32 GetMainFrameID() const; - - const CCamera& GetCamera() const; - bool IsCameraUnderWater() const; - - float GetZoomFactor() const; - float GetInverseZoomFactor() const; - bool RenderShadows() const; - bool RenderEntities() const; - bool RenderWaterOcean() const; - bool RenderDecals() const; - bool RenderWaterVolumes() const; - bool RenderClouds() const; - bool RenderGeomCaches() const; - - bool IsRenderingCubemap() const; - - uint32* ShadowGenMaskAddress() const; - uint32 ShadowFrustumID() const; - uint8 ShadowFrustumSide() const; - uint8 ShadowFrustumLod() const; - - CRenderView* GetRenderView() const; - - SRenderingPassInfo(threadID id) - { - SRenderingPassInfo(); - SetThreadID(id); - m_pRenderView = gEnv->pRenderer->GetRenderViewForThread(id); - } - -private: - - // private constructor, creation is only allowed with create functions - SRenderingPassInfo() - : pShadowGenMask(NULL) - , nShadowSide(0) - , nShadowLod(0) - , nShadowFrustumId(0) - , m_bAuxWindow(0) - , m_nRenderStackLevel(0) - , m_eShadowMapRendering(static_cast(SHADOW_MAP_NONE)) - , m_bCameraUnderWater(0) - , m_nRenderingFlags(0) - , m_fZoomFactor(0.0f) - , m_pCamera(NULL) - { - threadID nThreadID = 0; - gEnv->pRenderer->EF_Query(EFQ_MainThreadList, nThreadID); - m_nThreadID = aznumeric_caster(nThreadID); - m_nRenderFrameID = gEnv->pRenderer->GetFrameID(); - m_nRenderMainFrameID = gEnv->pRenderer->GetFrameID(false); - m_pRenderView = gEnv->pRenderer->GetRenderViewForThread(m_nThreadID); - } - - void InitRenderingFlags(uint32 nRenderingFlags); - void SetCamera(const CCamera& cam); - - uint8 m_nThreadID; - uint8 m_nRenderStackLevel; - uint8 m_eShadowMapRendering; // State flag denoting what type of shadow map is being currently rendered into - uint8 m_bCameraUnderWater; - - uint32 m_nRenderingFlags; - - float m_fZoomFactor; - - int m_nRenderFrameID; - uint32 m_nRenderMainFrameID; - - const CCamera* m_pCamera; - - // Render view used for this rendering pass - CRenderView* m_pRenderView; - - // members used only in shadow pass - uint32* pShadowGenMask; - uint32 nShadowFrustumId; - uint8 nShadowSide : 4; - uint8 nShadowLod : 4; - uint8 m_bAuxWindow; -}; - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsGeneralPass() const -{ - return m_nRenderStackLevel == 0 && m_bAuxWindow == 0 && static_cast(m_eShadowMapRendering) == SHADOW_MAP_NONE; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsRecursivePass() const -{ - return m_nRenderStackLevel > 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::GetRecursiveLevel() const -{ - return m_nRenderStackLevel; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsShadowPass() const -{ - return static_cast(m_eShadowMapRendering) != SHADOW_MAP_NONE; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsCachedShadowPass() const -{ - return IsShadowPass() && - (GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED || - GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED_MGPU_COPY); -} -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo::EShadowMapType SRenderingPassInfo::GetShadowMapType() const -{ - assert(IsShadowPass()); - return static_cast(m_eShadowMapRendering); -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsAuxWindow() const -{ - return m_bAuxWindow != 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline threadID SRenderingPassInfo::ThreadID() const -{ - return m_nThreadID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline int SRenderingPassInfo::GetFrameID() const -{ - return m_nRenderFrameID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::GetMainFrameID() const -{ - return m_nRenderMainFrameID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline const CCamera& SRenderingPassInfo::GetCamera() const -{ - assert(m_pCamera != NULL); - return *m_pCamera; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsCameraUnderWater() const -{ - return m_bCameraUnderWater != 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline float SRenderingPassInfo::GetZoomFactor() const -{ - return m_fZoomFactor; -} - -/////////////////////////////////////////////////////////////////////////////// -inline float SRenderingPassInfo::GetInverseZoomFactor() const -{ - return 1.0f / m_fZoomFactor; -} - - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderShadows() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::SHADOWS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderEntities() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::ENTITIES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderWaterOcean() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::WATEROCEAN) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderDecals() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::DECALS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderWaterVolumes() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::WATER_VOLUMES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderClouds() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::CLOUDS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderGeomCaches() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::GEOM_CACHES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsRenderingCubemap() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::CUBEMAP_GEN) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsDisableRenderChunkMerge() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::DISABLE_RENDER_CHUNK_MERGE) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint32* SRenderingPassInfo::ShadowGenMaskAddress() const -{ - assert(pShadowGenMask); - return pShadowGenMask; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::ShadowFrustumID() const -{ - return nShadowFrustumId; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint8 SRenderingPassInfo::ShadowFrustumSide() const -{ - return nShadowSide; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint8 SRenderingPassInfo::ShadowFrustumLod() const -{ - return nShadowLod; -} -//////////////////////////////////////////////////////////////////////////////// -inline CRenderView* SRenderingPassInfo::GetRenderView() const -{ - return m_pRenderView; -} -//////////////////////////////////////////////////////////////////////////////// -inline void SRenderingPassInfo::SetCamera(const CCamera& cam) -{ - m_pCamera = gEnv->p3DEngine->GetRenderingPassCamera(cam); - m_bCameraUnderWater = gEnv->p3DEngine->IsUnderWater(cam.GetPosition()); - m_fZoomFactor = 0.2f + 0.8f * (RAD2DEG(cam.GetFov()) / 60.f); -} - -//////////////////////////////////////////////////////////////////////////////// -inline void SRenderingPassInfo::InitRenderingFlags(uint32 nRenderingFlags) -{ - m_nRenderingFlags = nRenderingFlags; -#if (ALLOW_CONST_CVAR_MODIFICATIONS) - static ICVar* pDefaultMaterial = gEnv->pConsole->GetCVar("e_DefaultMaterial"); - static ICVar* pShadows = gEnv->pConsole->GetCVar("e_Shadows"); - static ICVar* pEntities = gEnv->pConsole->GetCVar("e_Entities"); - static ICVar* pWaterOcean = gEnv->pConsole->GetCVar("e_WaterOcean"); - static ICVar* pDecals = gEnv->pConsole->GetCVar("e_Decals"); - static ICVar* pWaterVolumes = gEnv->pConsole->GetCVar("e_WaterVolumes"); - static ICVar* pClouds = gEnv->pConsole->GetCVar("e_Clouds"); - static ICVar* pGeomCaches = gEnv->pConsole->GetCVar("e_GeomCaches"); - - if (pShadows->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::SHADOWS; - } - if (pEntities->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::ENTITIES; - } - if (pWaterOcean->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::WATEROCEAN; - } - if (pDecals->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::DECALS; - } - if (pWaterVolumes->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::WATER_VOLUMES; - } - if (pClouds->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::CLOUDS; - } - if (pGeomCaches->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::GEOM_CACHES; - } - - // on dedicated server, never render any object at all - if (gEnv->IsDedicated()) - { - m_nRenderingFlags = 0; - } -#endif // (ALLOW_CONST_CVAR_MODIFICATIONS) -} - -//////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateGeneralPassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags, bool bAuxWindow) -{ - static ICVar* pCameraFreeze = gEnv->pConsole->GetCVar("e_CameraFreeze"); - - // Update Camera only if e_camerafreeze is not set - const CCamera& rCameraToSet = (pCameraFreeze && pCameraFreeze->GetIVal() != 0) ? gEnv->p3DEngine->GetRenderingCamera() : rCamera; - - SRenderingPassInfo passInfo; - passInfo.SetCamera(rCameraToSet); - passInfo.InitRenderingFlags(nRenderingFlags); - passInfo.m_bAuxWindow = bAuxWindow; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateRecursivePassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags) -{ - static ICVar* pRecursionViewDistRatio = gEnv->pConsole->GetCVar("e_RecursionViewDistRatio"); - - SRenderingPassInfo passInfo; - passInfo.m_nRenderStackLevel = 1; - passInfo.SetCamera(rCamera); - - // adjust view distance in recursive mode by adjusting the ZoomFactor - passInfo.m_fZoomFactor /= pRecursionViewDistRatio->GetFVal(); - - passInfo.InitRenderingFlags(nRenderingFlags); - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateShadowPassRenderingInfo(const CCamera& rCamera, int nLightFlags, int nShadowMapLod, bool bExtendedLod, bool bIsMGPUCopy, uint32* pShadowGenMask, uint32 nSide, uint32 nShadowFrustumID, uint32 nRenderingFlags) -{ - SRenderingPassInfo passInfo; - passInfo.SetCamera(rCamera); - passInfo.InitRenderingFlags(nRenderingFlags); - - // set correct shadow map type - if (nLightFlags & DLF_SUN) - { - assert(nShadowMapLod >= 0 && nShadowMapLod < 8); - if (bExtendedLod) - { - passInfo.m_eShadowMapRendering = bIsMGPUCopy ? static_cast(SHADOW_MAP_CACHED_MGPU_COPY) : static_cast(SHADOW_MAP_CACHED); - } - else - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_GSM); - } - } - else if (nLightFlags & (DLF_POINT | DLF_PROJECT | DLF_AREA_LIGHT)) - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_LOCAL); - } - else - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_NONE); - } - - passInfo.pShadowGenMask = pShadowGenMask; - passInfo.nShadowSide = nSide; - passInfo.nShadowLod = nShadowMapLod; - passInfo.nShadowFrustumId = nShadowFrustumID; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateTempRenderingInfo(const CCamera& rCamera, const SRenderingPassInfo& rPassInfo) -{ - SRenderingPassInfo passInfo = rPassInfo; - passInfo.SetCamera(rCamera); - - passInfo.pShadowGenMask = NULL; - passInfo.nShadowSide = 0; - passInfo.nShadowFrustumId = 0; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateTempRenderingInfo(uint32 nRenderingFlags, const SRenderingPassInfo& rPassInfo) -{ - SRenderingPassInfo passInfo = rPassInfo; - passInfo.m_nRenderingFlags = nRenderingFlags; - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -// class to wrap a special counter used to presort SRendItems -// this is used to fix random ordering introduced by parallelization -// of parts of the 3DEngine -struct SRendItemSorter -{ - // Deferred PreProcess needs a special ordering, use these to prefix the values - // to ensure the deferred shading pass is after all LPV objects - enum EDeferredPreprocess - { - eLPVPass = 0, - eDeferredShadingPass = BIT(30) - }; - - static SRendItemSorter CreateRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateShadowPassRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateParticleRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateDeferredPreProcessRendItemSorter(const SRenderingPassInfo& passInfo, EDeferredPreprocess deferredPrerocessType); - static SRendItemSorter CreateDefaultRendItemSorter(); - - void IncreaseOctreeCounter() { nValue += eOctreeNodeCounter; } - void IncreaseObjectCounter() { nValue += eObjectCounter; } - void IncreaseGroupCounter() { nValue += eGroupCounter; } - - void IncreaseParticleCounter() { nValue += eParticleCounter; } - uint32 ParticleCounter() const { return nValue & ~eRecursivePassMask; } - - uint32 ShadowFrustumID() const { return nValue & ~eRecursivePassMask; } - - uint32 GetValue() const { return nValue; } - - bool operator<(const SRendItemSorter& rOther) const - { - return nValue < rOther.nValue; - } - - bool IsRecursivePass() const { return (nValue & eRecursivePassMask) != 0; } - - SRendItemSorter() - : nValue(0) {} - explicit SRendItemSorter(uint32 _nValue) - : nValue(_nValue) {} - -private: - // encode various counter in a single value - enum - { - eRecursivePassMask = BIT(31) - }; // present in all combinations - - // flags used for regular SRendItems - enum - { - eObjectCounter = BIT(0) - }; // bits 0-14 used - enum - { - eOctreeNodeCounter = BIT(14) - }; // bits 15-27 used - enum - { - eGroupCounter = BIT(27) - }; // bits 28-31 used - - // flags used for Particles - enum - { - eParticleCounter = BIT(0) - }; - - uint32 nValue; -}; - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateShadowPassRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = passInfo.ShadowFrustumID(); - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateParticleRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateDeferredPreProcessRendItemSorter(const SRenderingPassInfo& passInfo, EDeferredPreprocess deferredPrerocessType) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - rendItemSorter.nValue |= deferredPrerocessType; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateDefaultRendItemSorter() -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - return rendItemSorter; -} - -//Legacy Bus for communicating with SVOGI from the legacy engine code. -class SVOGILegacyRequests - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; -// static const bool LocklessDispatch = true; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Triggers an update of voxel data. - virtual void UpdateVoxelData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Triggers an update of voxel data to GPU. - virtual void UpdateRenderData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Called at framestart - virtual void OnFrameStart(const SRenderingPassInfo& passInfo) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Gets the textures bound for GI plus lighting data. - virtual void GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Generates a list of bricks that need to be updated in compute shaders. - virtual void GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Causes the GI system to free all voxel data. - virtual void ReleaseData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Register and unregister a mutex to protect assets during rendering. - virtual void RegisterMutex(AZStd::mutex* mutex) = 0; - virtual void UnregisterMutex() = 0; - -}; -using SVOGILegacyRequestBus = AZ::EBus; - - -#endif // CRYINCLUDE_CRYCOMMON_I3DENGINE_H - diff --git a/Code/CryEngine/CryCommon/I3DEngine_info.h b/Code/CryEngine/CryCommon/I3DEngine_info.h deleted file mode 100644 index f1c601fcc6..0000000000 --- a/Code/CryEngine/CryCommon/I3DEngine_info.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H -#define CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H -#pragma once - -#include "TypeInfo_impl.h" -#include "IShader_info.h" -#include // <> required for Interfuscator - -STRUCT_INFO_BEGIN(SVisAreaManChunkHeader) -STRUCT_VAR_INFO(nVersion, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nDummy, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nFlags2, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nChunkSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVisAreasNum, TYPE_INFO(int)) -STRUCT_VAR_INFO(nPortalsNum, TYPE_INFO(int)) -STRUCT_VAR_INFO(nOcclAreasNum, TYPE_INFO(int)) -STRUCT_INFO_END(SVisAreaManChunkHeader) - -STRUCT_INFO_BEGIN(SOcTreeNodeChunk) -STRUCT_VAR_INFO(nChunkVersion, TYPE_INFO(int16)) -STRUCT_VAR_INFO(ucChildsMask, TYPE_INFO(int16)) -STRUCT_VAR_INFO(nodeBox, TYPE_INFO(AABB)) -STRUCT_VAR_INFO(nObjectsBlockSize, TYPE_INFO(int32)) -STRUCT_INFO_END(SOcTreeNodeChunk) - -STRUCT_INFO_BEGIN(SHotUpdateInfo) -STRUCT_VAR_INFO(nHeigtmap, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(nObjTypeMask, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(areaBox, TYPE_INFO(AABB)) -STRUCT_INFO_END(SHotUpdateInfo) - -STRUCT_INFO_BEGIN(SCommonFileHeader) -STRUCT_VAR_INFO(signature, TYPE_ARRAY(4, TYPE_INFO(char))) -STRUCT_VAR_INFO(file_type, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(flags, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(version, TYPE_INFO(uint16)) -STRUCT_INFO_END(SCommonFileHeader) - -#endif // CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H diff --git a/Code/CryEngine/CryCommon/IEntityRenderState.h b/Code/CryEngine/CryCommon/IEntityRenderState.h index 92ff354eff..29b1bdc463 100644 --- a/Code/CryEngine/CryCommon/IEntityRenderState.h +++ b/Code/CryEngine/CryCommon/IEntityRenderState.h @@ -286,7 +286,6 @@ struct IRenderNode // Physicalizes node. virtual void Physicalize([[maybe_unused]] bool bInstant = false) {} - // Make sure I3DEngine::FreeRenderNodeState(this) is called in destructor of derived class. virtual ~IRenderNode() { assert(!m_pRNTmpData); }; // Summary: diff --git a/Code/CryEngine/CryCommon/ILocalMemoryUsage.h b/Code/CryEngine/CryCommon/ILocalMemoryUsage.h deleted file mode 100644 index fd1e7e3693..0000000000 --- a/Code/CryEngine/CryCommon/ILocalMemoryUsage.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface for LocalMemoryUsage - - -#ifndef CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H -#define CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H -#pragma once - - -class CCamera; -struct IRenderer; - -struct ILocalMemoryUsage -{ - virtual ~ILocalMemoryUsage(){} - virtual void OnRender(IRenderer* pRenderer, const CCamera* camera) = 0; - virtual void OnUpdate() = 0; - virtual void DeleteGlobalData() = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H diff --git a/Code/CryEngine/CryCommon/IMaterial.h b/Code/CryEngine/CryCommon/IMaterial.h index 81d612397f..020ddcc871 100644 --- a/Code/CryEngine/CryCommon/IMaterial.h +++ b/Code/CryEngine/CryCommon/IMaterial.h @@ -273,7 +273,7 @@ struct IMaterial ////////////////////////////////////////////////////////////////////////// // material name ////////////////////////////////////////////////////////////////////////// - //! Set material name, (Do not use this directly, to change material name use I3DEngine::RenameMatInfo method). + //! Set material name, (Do not use this directly virtual void SetName(const char* pName) = 0; //! Returns material name. virtual const char* GetName() const = 0; @@ -404,7 +404,6 @@ struct IMaterial ////////////////////////////////////////////////////////////////////////// // Makes this specific material enter sketch mode. - // Se also: I3DEngine::LoadCGF, in I3DEngine.h. // Current supported sketch modes: // - 0, no sketch. // - 1, normal sketch mode. diff --git a/Code/CryEngine/CryCommon/IMovieSystem.h b/Code/CryEngine/CryCommon/IMovieSystem.h index c22394e1b3..ce4e59d43c 100644 --- a/Code/CryEngine/CryCommon/IMovieSystem.h +++ b/Code/CryEngine/CryCommon/IMovieSystem.h @@ -26,7 +26,6 @@ #include #include #include -#include #include #include diff --git a/Code/CryEngine/CryCommon/IObjManager.h b/Code/CryEngine/CryCommon/IObjManager.h index acbd5c5d18..a63a252976 100644 --- a/Code/CryEngine/CryCommon/IObjManager.h +++ b/Code/CryEngine/CryCommon/IObjManager.h @@ -202,7 +202,6 @@ struct IObjManager // time counters virtual bool IsAfterWater(const Vec3& vPos, const SRenderingPassInfo& passInfo) = 0; - virtual void GetObjectsStreamingStatus(I3DEngine::SObjectsStreamingStatus& outStatus) = 0; virtual void FreeNotUsedCGFs() = 0; virtual void MakeUnitCube() = 0; diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 9b1e817602..96d9a6ad10 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -66,7 +66,6 @@ struct IConsole; struct IRemoteConsole; struct IRenderer; struct IProcess; -struct I3DEngine; struct ITimer; struct ICryFont; struct IMovieSystem; @@ -123,8 +122,6 @@ namespace Serialization { struct IArchiveHost; } -struct ILocalMemoryUsage; - typedef void* WIN_HWND; class CCamera; @@ -793,7 +790,6 @@ struct SSystemUpdateStats // ISystem struct SSystemGlobalEnvironment { - I3DEngine* p3DEngine; AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; IFileChangeMonitor* pFileChangeMonitor; @@ -801,7 +797,6 @@ struct SSystemGlobalEnvironment IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; - ILocalMemoryUsage* pLocalMemoryUsage; ::IConsole* pConsole; ISystem* pSystem = nullptr; ILog* pLog; @@ -1113,25 +1108,9 @@ struct ISystem virtual void DoWorkDuringOcclusionChecks() = 0; virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - // Summary: - // Renders subsystems. - virtual void Render() = 0; - // Summary: - // Begins rendering frame. - virtual void RenderBegin() = 0; - // Summary: - // Ends rendering frame and swap back buffer. - virtual void RenderEnd(bool bRenderStats = true, bool bMainWindow = true) = 0; - //! Update screen and call some important tick functions during loading. virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0; - // Description: - // Renders the statistics; this is called from RenderEnd, but if the - // Host application (Editor) doesn't employ the Render cycle in ISystem, - // it may call this method to render the essential statistics. - virtual void RenderStatistics() = 0; - // Summary: // Returns the current used memory. virtual uint32 GetUsedMemory() = 0; @@ -1229,7 +1208,6 @@ struct ISystem virtual ICryFont* GetICryFont() = 0; virtual IMemoryManager* GetIMemoryManager() = 0; virtual IMovieSystem* GetIMovieSystem() = 0; - virtual I3DEngine* GetI3DEngine() = 0; virtual ::IConsole* GetIConsole() = 0; virtual IRemoteConsole* GetIRemoteConsole() = 0; // Returns: diff --git a/Code/CryEngine/CryCommon/ITimeOfDay.h b/Code/CryEngine/CryCommon/ITimeOfDay.h deleted file mode 100644 index b491ea9359..0000000000 --- a/Code/CryEngine/CryCommon/ITimeOfDay.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -#pragma once - -struct SBezierKey; -struct ITimeOfDayUpdateCallback; -struct ISplineInterpolator; - - -//! Interface to the Time Of Day functionality. -struct ITimeOfDay -{ - enum ETimeOfDayParamID - { - PARAM_SUN_COLOR, - PARAM_SUN_INTENSITY, - PARAM_SUN_SPECULAR_MULTIPLIER, - - PARAM_FOG_COLOR, - PARAM_FOG_COLOR_MULTIPLIER, - PARAM_VOLFOG_HEIGHT, - PARAM_VOLFOG_DENSITY, - PARAM_FOG_COLOR2, - PARAM_FOG_COLOR2_MULTIPLIER, - PARAM_VOLFOG_HEIGHT2, - PARAM_VOLFOG_DENSITY2, - PARAM_VOLFOG_HEIGHT_OFFSET, - - PARAM_FOG_RADIAL_COLOR, - PARAM_FOG_RADIAL_COLOR_MULTIPLIER, - PARAM_VOLFOG_RADIAL_SIZE, - PARAM_VOLFOG_RADIAL_LOBE, - - PARAM_VOLFOG_FINAL_DENSITY_CLAMP, - - PARAM_VOLFOG_GLOBAL_DENSITY, - PARAM_VOLFOG_RAMP_START, - PARAM_VOLFOG_RAMP_END, - PARAM_VOLFOG_RAMP_INFLUENCE, - - PARAM_VOLFOG_SHADOW_DARKENING, - PARAM_VOLFOG_SHADOW_DARKENING_SUN, - PARAM_VOLFOG_SHADOW_DARKENING_AMBIENT, - PARAM_VOLFOG_SHADOW_RANGE, - - PARAM_VOLFOG2_HEIGHT, - PARAM_VOLFOG2_DENSITY, - PARAM_VOLFOG2_HEIGHT2, - PARAM_VOLFOG2_DENSITY2, - PARAM_VOLFOG2_GLOBAL_DENSITY, - PARAM_VOLFOG2_RAMP_START, - PARAM_VOLFOG2_RAMP_END, - PARAM_VOLFOG2_COLOR1, - PARAM_VOLFOG2_ANISOTROPIC1, - PARAM_VOLFOG2_COLOR2, - PARAM_VOLFOG2_ANISOTROPIC2, - PARAM_VOLFOG2_BLEND_FACTOR, - PARAM_VOLFOG2_BLEND_MODE, - PARAM_VOLFOG2_COLOR, - PARAM_VOLFOG2_ANISOTROPIC, - PARAM_VOLFOG2_RANGE, - PARAM_VOLFOG2_INSCATTER, - PARAM_VOLFOG2_EXTINCTION, - PARAM_VOLFOG2_GLOBAL_FOG_VISIBILITY, - PARAM_VOLFOG2_FINAL_DENSITY_CLAMP, - - PARAM_SKYLIGHT_SUN_INTENSITY, - PARAM_SKYLIGHT_SUN_INTENSITY_MULTIPLIER, - - PARAM_SKYLIGHT_KM, - PARAM_SKYLIGHT_KR, - PARAM_SKYLIGHT_G, - - PARAM_SKYLIGHT_WAVELENGTH_R, - PARAM_SKYLIGHT_WAVELENGTH_G, - PARAM_SKYLIGHT_WAVELENGTH_B, - - PARAM_NIGHSKY_HORIZON_COLOR, - PARAM_NIGHSKY_HORIZON_COLOR_MULTIPLIER, - PARAM_NIGHSKY_ZENITH_COLOR, - PARAM_NIGHSKY_ZENITH_COLOR_MULTIPLIER, - PARAM_NIGHSKY_ZENITH_SHIFT, - - PARAM_NIGHSKY_START_INTENSITY, - - PARAM_NIGHSKY_MOON_COLOR, - PARAM_NIGHSKY_MOON_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_INNERCORONA_COLOR, - PARAM_NIGHSKY_MOON_INNERCORONA_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_INNERCORONA_SCALE, - PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, - PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_OUTERCORONA_SCALE, - - PARAM_CLOUDSHADING_SUNLIGHT_MULTIPLIER, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_MULTIPLIER, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_INFLUENCE, - - PARAM_SUN_SHAFTS_VISIBILITY, - PARAM_SUN_RAYS_VISIBILITY, - PARAM_SUN_RAYS_ATTENUATION, - PARAM_SUN_RAYS_SUNCOLORINFLUENCE, - PARAM_SUN_RAYS_CUSTOMCOLOR, - - PARAM_OCEANFOG_COLOR, // Remove when ocean related feature toggle is removed. - PARAM_OCEANFOG_COLOR_MULTIPLIER, // Remove when ocean related feature toggle is removed. - PARAM_OCEANFOG_DENSITY, // Remove when ocean related feature toggle is removed. - - PARAM_SKYBOX_MULTIPLIER, - - PARAM_HDR_FILMCURVE_SHOULDER_SCALE, - PARAM_HDR_FILMCURVE_LINEAR_SCALE, - PARAM_HDR_FILMCURVE_TOE_SCALE, - PARAM_HDR_FILMCURVE_WHITEPOINT, - - PARAM_HDR_COLORGRADING_COLOR_SATURATION, - PARAM_HDR_COLORGRADING_COLOR_BALANCE, - - PARAM_HDR_EYEADAPTATION_SCENEKEY, - PARAM_HDR_EYEADAPTATION_MIN_EXPOSURE, - PARAM_HDR_EYEADAPTATION_MAX_EXPOSURE, - PARAM_HDR_EYEADAPTATION_EV_MIN, - PARAM_HDR_EYEADAPTATION_EV_MAX, - PARAM_HDR_EYEADAPTATION_EV_AUTO_COMPENSATION, - PARAM_HDR_BLOOM_AMOUNT, - - PARAM_COLORGRADING_FILTERS_GRAIN, - PARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR, - PARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY, - - PARAM_COLORGRADING_DOF_FOCUSRANGE, - PARAM_COLORGRADING_DOF_BLURAMOUNT, - - PARAM_SHADOWSC0_BIAS, - PARAM_SHADOWSC0_SLOPE_BIAS, - PARAM_SHADOWSC1_BIAS, - PARAM_SHADOWSC1_SLOPE_BIAS, - PARAM_SHADOWSC2_BIAS, - PARAM_SHADOWSC2_SLOPE_BIAS, - PARAM_SHADOWSC3_BIAS, - PARAM_SHADOWSC3_SLOPE_BIAS, - PARAM_SHADOWSC4_BIAS, - PARAM_SHADOWSC4_SLOPE_BIAS, - PARAM_SHADOWSC5_BIAS, - PARAM_SHADOWSC5_SLOPE_BIAS, - PARAM_SHADOWSC6_BIAS, - PARAM_SHADOWSC6_SLOPE_BIAS, - PARAM_SHADOWSC7_BIAS, - PARAM_SHADOWSC7_SLOPE_BIAS, - - PARAM_SHADOW_JITTERING, - - PARAM_HDR_DYNAMIC_POWER_FACTOR, - PARAM_TERRAIN_OCCL_MULTIPLIER, - PARAM_SUN_COLOR_MULTIPLIER, - - PARAM_TOTAL - }; - - struct SPresetInfo - { - const char* m_pName; - bool m_bCurrent; - }; - - enum EVariableType - { - TYPE_FLOAT, - TYPE_COLOR - }; - struct SVariableInfo - { - const char* name; //!< Variable name. - const char* displayName; //!< Variable user readable name. - const char* group; //!< Group name. - int nParamId; - EVariableType type; - float fValue[3]; //!< Value of the variable (3 needed for color type). - ISplineInterpolator* pInterpolator; //!< Splines that control variable value. - }; - struct SAdvancedInfo - { - float fStartTime; - float fEndTime; - float fAnimSpeed; - }; - struct SEnvironmentInfo - { - SEnvironmentInfo() - : bSunLinkedToTOD(true) - , sunRotationLatitude(0) - , sunRotationLongitude(0){} - bool bSunLinkedToTOD; - float sunRotationLatitude; - float sunRotationLongitude; - }; - - // - virtual ~ITimeOfDay(){} - - virtual int GetPresetCount() const = 0; - virtual bool GetPresetsInfos(SPresetInfo* resultArray, unsigned int arraySize) const = 0; - virtual bool SetCurrentPreset(const char* szPresetName) = 0; - virtual bool AddNewPreset(const char* szPresetName) = 0; - virtual bool RemovePreset(const char* szPresetName) = 0; - virtual bool SavePreset(const char* szPresetName) const = 0; - virtual bool LoadPreset(const char* szFilePath) = 0; - virtual void ResetPreset(const char* szPresetName) = 0; - - virtual bool ImportPreset(const char* szPresetName, const char* szFilePath) = 0; - virtual bool ExportPreset(const char* szPresetName, const char* szFilePath) const = 0; - - //! Access to variables that control time of the day appearance. - virtual int GetVariableCount() const = 0; - virtual bool GetVariableInfo(int nIndex, SVariableInfo& varInfo) const = 0; - virtual void SetVariableValue(int nIndex, float fValue[3]) = 0; - - //! Editor interface. - virtual bool InterpolateVarInRange(int nIndex, float fMin, float fMax, unsigned int nCount, Vec3* resultArray) const = 0; - virtual uint GetSplineKeysCount(int nIndex, int nSpline) const = 0; - virtual bool GetSplineKeysForVar(int nIndex, int nSpline, SBezierKey* keysArray, unsigned int keysArraySize) const = 0; - virtual bool SetSplineKeysForVar(int nIndex, int nSpline, const SBezierKey* keysArray, unsigned int keysArraySize) = 0; - virtual bool UpdateSplineKeyForVar(int nIndex, int nSpline, float fTime, float newValue) = 0; - - virtual void ResetVariables() = 0; - - //! Sets the time of the day specified in hours. - virtual void SetTime(float fHour, bool bForceUpdate = false, bool bForceEnvUpdate = true) = 0; - virtual float GetTime() = 0; - - //! Sun position. - virtual void SetSunPos(float longitude, float latitude) = 0; - virtual float GetSunLatitude() = 0; - virtual float GetSunLongitude() = 0; - - //! Updates the current ToD. - virtual void Tick() = 0; - - - virtual void SetPaused(bool paused) = 0; - - virtual void SetAdvancedInfo(const SAdvancedInfo& advInfo) = 0; - virtual void GetAdvancedInfo(SAdvancedInfo& advInfo) = 0; - - //! Updates engine parameters after variable values have been changed. - virtual void Update(bool bInterpolate = true, bool bForceUpdate = false, bool bForceEnvUpdate = true) = 0; - virtual void SetUpdateCallback(ITimeOfDayUpdateCallback* pCallback) = 0; - - virtual void BeginEditMode() = 0; - virtual void EndEditMode() = 0; - - virtual void Serialize(XmlNodeRef& node, bool bLoading) = 0; - virtual void Serialize(TSerialize ser) = 0; - - virtual void SetTimer(ITimer* pTimer) = 0; - virtual void SetEnvironmentSettings(const SEnvironmentInfo& envInfo) = 0; - virtual void LerpWith(const ITimeOfDay& other, float lerpValue, ITimeOfDay& output) const = 0; - - //! Multiplayer serialization. - static const int NETSER_FORCESET = BIT(0); - static const int NETSER_COMPENSATELAG = BIT(1); - static const int NETSER_STATICPROPS = BIT(2); - virtual void NetSerialize(TSerialize ser, float lag, uint32 flags) = 0; -}; - -struct ITimeOfDayUpdateCallback -{ - // - virtual ~ITimeOfDayUpdateCallback(){} - virtual void BeginUpdate() = 0; - virtual bool GetCustomValue(ITimeOfDay::ETimeOfDayParamID paramID, int dim, float* pValues, float& blendWeight) = 0; - virtual void EndUpdate() = 0; - // -}; - diff --git a/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h b/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h deleted file mode 100644 index b0936ddbdd..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h +++ /dev/null @@ -1,528 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#include -#include -#include - -// the following was generated using google's python script to autogenerate mocks. -// however, it needed some hand-editing to make it work, so if you add functions to I3DEngine, -// it will probably be better to just manually add them here than try to run the script again. - -class I3DEngineMock - : public I3DEngine -{ -public: - // From IProcess - MOCK_METHOD1(SetFlags, - void(int)); - MOCK_METHOD0(GetFlags, - int(void)); - - // From I3DEngine - MOCK_METHOD0(Init, - bool()); - MOCK_METHOD1(SetLevelPath, - void(const char* szFolderName)); - MOCK_METHOD1(CheckMinSpec, - bool(uint32 nMinSpec)); - MOCK_METHOD1(PrepareOcclusion, - void(const CCamera& rCamera)); - MOCK_METHOD0(EndOcclusion, - void()); - MOCK_METHOD2(LoadLevel, - bool(const char* szFolderName, const char* szMissionName)); - MOCK_METHOD2(InitLevelForEditor, - bool(const char* szFolderName, const char* szMissionName)); - MOCK_METHOD0(LevelLoadingInProgress, - bool()); - MOCK_METHOD0(OnFrameStart, - void()); - MOCK_METHOD0(PostLoadLevel, - void()); - MOCK_METHOD0(LoadEmptyLevel, - void()); - MOCK_METHOD0(UnloadLevel, - void()); - MOCK_METHOD0(Update, - void()); - MOCK_CONST_METHOD0(GetRenderingCamera, - const CCamera&()); - MOCK_CONST_METHOD0(GetZoomFactor, - float()); - MOCK_METHOD0(Tick, - void()); - MOCK_METHOD0(UpdateShaderItems, - void()); - MOCK_METHOD0(Release, - void()); - MOCK_METHOD3(RenderWorld, - void(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName)); - MOCK_METHOD2(RenderSceneReflection, - void(int nRenderFlags, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(PreWorldStreamUpdate, - void(const CCamera& cam)); - MOCK_METHOD0(WorldStreamUpdate, - void()); - MOCK_METHOD0(ShutDown, - void()); - MOCK_METHOD7(LoadStatObjUnsafeManualRef, - IStatObj*(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject, - bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)); - MOCK_METHOD7(LoadStatObjAutoRef, - _smart_ptr(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject, - bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)); - MOCK_METHOD0(ProcessAsyncStaticObjectLoadRequests, - void()); - MOCK_METHOD5(LoadStatObjAsync, - void(LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName, bool bUseStreaming, unsigned long nLoadingFlags)); - MOCK_METHOD1(FindStatObjectByFilename, - IStatObj*(const char* filename)); - MOCK_METHOD0(GetGSMRange, - const float()); - MOCK_METHOD0(GetGSMRangeStep, - const float()); - MOCK_METHOD0(GetLoadedObjectCount, - int()); - MOCK_METHOD2(GetLoadedStatObjArray, - void(IStatObj** pObjectsArray, int& nCount)); - MOCK_METHOD1(GetObjectsStreamingStatus, - void(SObjectsStreamingStatus& outStatus)); - MOCK_METHOD2(GetStreamingSubsystemData, - void(int subsystem, SStremaingBandwidthData& outData)); - MOCK_METHOD3(RegisterEntity, - void(IRenderNode* pEntity, int nSID, int nSIDConsideredSafe)); - MOCK_METHOD1(SelectEntity, - void(IRenderNode* pEntity)); - MOCK_METHOD0(IsSunShadows, - bool()); - MOCK_METHOD2(MakeSystemMaterialFromShaderHelper - , _smart_ptr(const char* sShaderName, SInputShaderResources* Res)); - MOCK_METHOD1(CheckMinSpecHelper - , bool(uint32 nMinSpec)); - MOCK_METHOD1(OnCasterDeleted - , void(IShadowCaster* pCaster)); - MOCK_METHOD4(GetStatObjAndMatTables, - void(DynArray* pStatObjTable, DynArray<_smart_ptr>* pMatTable, DynArray* pStatInstGroupTable, uint32 nObjTypeMask)); -#ifndef _RELEASE - MOCK_METHOD1(AddObjToDebugDrawList, - void(SObjectInfoToAddToDebugDrawList& objInfo)); - MOCK_CONST_METHOD0(IsDebugDrawListEnabled, - bool()); -#endif - MOCK_METHOD1(UnRegisterEntityDirect, - void(IRenderNode* pEntity)); - MOCK_METHOD1(UnRegisterEntityAsJob, - void(IRenderNode* pEnt)); - MOCK_CONST_METHOD1(IsUnderWater, - bool(const Vec3& vPos)); - MOCK_METHOD1(SetOceanRenderFlags, - void(uint8 nFlags)); - MOCK_CONST_METHOD0(GetOceanRenderFlags, - uint8()); - MOCK_CONST_METHOD0(GetOceanVisiblePixelsCount, - uint32()); - MOCK_METHOD3(GetBottomLevel, - float(const Vec3& referencePos, float maxRelevantDepth, int objtypes)); - MOCK_METHOD2(GetBottomLevel, - float(const Vec3& referencePos, float maxRelevantDepth)); - MOCK_METHOD2(GetBottomLevel, - float(const Vec3& referencePos, int objflags)); - MOCK_METHOD0(GetWaterLevel, - float()); - MOCK_METHOD3(GetWaterLevel, - float(const Vec3* pvPos, IPhysicalEntity* pent, bool bAccurate)); - MOCK_CONST_METHOD1(GetAccurateOceanHeight, - float(const Vec3& pCurrPos)); - MOCK_CONST_METHOD0(GetCausticsParams, - CausticsParams()); - MOCK_CONST_METHOD0(GetOceanAnimationParams, - OceanAnimationData()); - MOCK_CONST_METHOD1(GetHDRSetupParams, - void(Vec4 pParams[5])); - MOCK_METHOD0(ResetParticlesAndDecals, - void()); - MOCK_METHOD1(CreateDecal, - void(const CryEngineDecalInfo& Decal)); - MOCK_METHOD2(DeleteDecalsInRange, - void(AABB* pAreaBox, IRenderNode* pEntity)); - MOCK_METHOD1(SetSunColor, - void(Vec3 vColor)); - MOCK_METHOD0(GetSunAnimColor, - Vec3()); - MOCK_METHOD1(SetSunAnimColor, - void(const Vec3& color)); - MOCK_METHOD0(GetSunAnimSpeed, - float()); - MOCK_METHOD1(SetSunAnimSpeed, - void(float sunAnimSpeed)); - MOCK_METHOD0(GetSunAnimPhase, - AZ::u8()); - MOCK_METHOD1(SetSunAnimPhase, - void(AZ::u8 sunAnimPhase)); - MOCK_METHOD0(GetSunAnimIndex, - AZ::u8()); - MOCK_METHOD1(SetSunAnimIndex, - void(AZ::u8 sunAnimIndex)); - MOCK_METHOD1(SetRainParams, - void(const SRainParams& rainParams)); - MOCK_METHOD1(GetRainParams, - bool(SRainParams& rainParams)); - MOCK_METHOD5(SetSnowSurfaceParams, - void(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing)); - MOCK_METHOD5(GetSnowSurfaceParams, - bool(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing)); - MOCK_METHOD7(SetSnowFallParams, - void(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq)); - MOCK_METHOD7(GetSnowFallParams, - bool(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq)); - MOCK_METHOD1(SetMaxViewDistanceScale, - void(float fScale)); - MOCK_METHOD1(GetMaxViewDistance, - float(bool)); - MOCK_CONST_METHOD0(GetFrameLodInfo, - const SFrameLodInfo&()); - MOCK_METHOD1(SetFrameLodInfo, - void(const SFrameLodInfo& frameLodInfo)); - MOCK_METHOD1(SetFogColor, - void(const Vec3& vFogColor)); - MOCK_METHOD0(GetFogColor, - Vec3()); - MOCK_METHOD6(GetSkyLightParameters, - void(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths)); - MOCK_METHOD7(SetSkyLightParameters, - void(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate)); - MOCK_CONST_METHOD0(GetLightsHDRDynamicPowerFactor, - float()); - MOCK_CONST_METHOD3(IsTessellationAllowed, - bool(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass)); - MOCK_METHOD3(SetRenderNodeMaterialAtPosition, - void(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat)); - MOCK_METHOD1(OverrideCameraPrecachePoint, - void(const Vec3& vPos)); - MOCK_METHOD4(AddPrecachePoint, - int(const Vec3& vPos, const Vec3& vDir, float fTimeOut, float fImportanceFactor)); - MOCK_METHOD1(ClearPrecachePoint, - void(int id)); - MOCK_METHOD0(ClearAllPrecachePoints, - void()); - MOCK_METHOD1(GetPrecacheRoundIds, - void(int pRoundIds[MAX_STREAM_PREDICTION_ZONES])); - MOCK_METHOD5(TraceFogVolumes, - void(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality)); - - MOCK_METHOD1(RemoveAllStaticObjects, - void(int)); - MOCK_METHOD3(SetStatInstGroup, - bool(int nGroupId, const IStatInstGroup& siGroup, int nSID)); - MOCK_METHOD3(GetStatInstGroup, - bool(int, IStatInstGroup&, int)); - MOCK_METHOD3(OnExplosion, - void(Vec3, float, bool)); - MOCK_METHOD1(SetPhysMaterialEnumerator, - void(IPhysMaterialEnumerator* pPhysMaterialEnumerator)); - MOCK_METHOD0(GetPhysMaterialEnumerator, - IPhysMaterialEnumerator*()); - MOCK_METHOD0(SetupDistanceFog, - void()); - MOCK_METHOD1(LoadMissionDataFromXMLNode, - void(const char* szMissionName)); - MOCK_METHOD2(LoadEnvironmentSettingsFromXML, - void(XmlNodeRef, int)); - MOCK_METHOD0(LoadCompiledOctreeForEditor, - bool()); - MOCK_CONST_METHOD0(GetSunDir, - Vec3()); - MOCK_CONST_METHOD0(GetSunDirNormalized, - Vec3()); - MOCK_CONST_METHOD0(GetRealtimeSunDirNormalized, - Vec3()); - MOCK_METHOD0(GetDistanceToSectorWithWater, - float()); - MOCK_CONST_METHOD0(GetSunColor, - Vec3()); - MOCK_CONST_METHOD0(GetSSAOAmount, - float()); - MOCK_CONST_METHOD0(GetSSAOContrast, - float()); - MOCK_METHOD1(FreeRenderNodeState, - void(IRenderNode* pEntity)); - MOCK_METHOD1(GetLevelFilePath, - const char*(const char* szFileName)); - MOCK_METHOD4(DisplayInfo, - void(float& fTextPosX, float& fTextPosY, float& fTextStepY, bool bEnhanced)); - MOCK_METHOD0(DisplayMemoryStatistics, - void()); - - // Can't mock methods with variable parameters so just create empty bodies for them. - void DrawTextRightAligned([[maybe_unused]] const float x, [[maybe_unused]] const float y, [[maybe_unused]] const char* format, ...) override {} - void DrawTextRightAligned([[maybe_unused]] const float x, [[maybe_unused]] const float y, [[maybe_unused]] const float scale, [[maybe_unused]] const ColorF& color, [[maybe_unused]] const char* format, ...) override {} - - MOCK_METHOD3(DrawBBoxHelper - , void (const Vec3& vMin, const Vec3& vMax, ColorB col)); - MOCK_METHOD2(DrawBBoxHelper - , void (const AABB& box, ColorB col)); - - MOCK_METHOD3(ActivatePortal, - void(const Vec3& vPos, bool bActivate, const char* szEntityName)); - MOCK_CONST_METHOD1(GetMemoryUsage, - void(ICrySizer* pSizer)); - MOCK_METHOD2(GetResourceMemoryUsage, - void(ICrySizer* pSizer, const AABB& cstAABB)); - MOCK_METHOD1(CreateVisArea, - IVisArea*(uint64 visGUID)); - MOCK_METHOD1(DeleteVisArea, - void(IVisArea* pVisArea)); - MOCK_METHOD6(UpdateVisArea, - void(IVisArea* pArea, const Vec3* pPoints, int nCount, const char* szName, const SVisAreaInfo& info, bool bReregisterObjects)); - MOCK_METHOD4(IsVisAreasConnected, - bool(IVisArea* pArea1, IVisArea* pArea2, int nMaxRecursion, bool bSkipDisabledPortals)); - MOCK_METHOD0(CreateClipVolume, - IClipVolume*()); - MOCK_METHOD1(DeleteClipVolume, - void(IClipVolume* pClipVolume)); - MOCK_METHOD7(UpdateClipVolume, - void(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName)); - MOCK_METHOD1(CreateRenderNode, - IRenderNode*(EERType type)); - MOCK_METHOD1(DeleteRenderNode, - void(IRenderNode* pRenderNode)); - MOCK_METHOD1(SetWind, - void(const Vec3& vWind)); - MOCK_CONST_METHOD2(GetWind, - Vec3(const AABB& box, bool bIndoors)); - MOCK_CONST_METHOD1(GetGlobalWind, - Vec3(bool bIndoors)); - MOCK_CONST_METHOD4(SampleWind, - bool(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors)); - MOCK_METHOD1(GetVisAreaFromPos, - IVisArea*(const Vec3& vPos)); - MOCK_METHOD2(IntersectsVisAreas, - bool(const AABB& box, void** pNodeCache)); - MOCK_METHOD4(ClipToVisAreas, - bool(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache)); - MOCK_METHOD1(EnableOceanRendering, - void(bool bOcean)); - MOCK_METHOD1(AddTextureLoadHandler, - void(ITextureLoadHandler* pHandler)); - MOCK_METHOD1(RemoveTextureLoadHandler, - void(ITextureLoadHandler* pHandler)); - MOCK_METHOD1(GetTextureLoadHandlerForImage, - ITextureLoadHandler*(const char* ext)); - MOCK_METHOD0(CreateLightSource, - struct ILightSource*()); - MOCK_METHOD1(DeleteLightSource, - void(ILightSource* pLightSource)); - MOCK_METHOD0(GetLightEntities, - const PodArray* ()); - MOCK_METHOD3(GetLightVolumes, - void(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols)); - MOCK_METHOD4(RegisterVolumeForLighting, - uint16(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(RestoreTerrainFromDisk, - bool(int)); - MOCK_METHOD1(GetFilePath, - const char*(const char* szFileName)); - MOCK_CONST_METHOD0(GetPostEffectGroups, - class IPostEffectGroupManager*()); - MOCK_CONST_METHOD0(GetPostEffectBaseGroup, - class IPostEffectGroup*()); - MOCK_CONST_METHOD3(SetPostEffectParam, - void(const char* pParam, float fValue, bool bForceValue)); - MOCK_CONST_METHOD3(SetPostEffectParamVec4, - void(const char* pParam, const Vec4& pValue, bool bForceValue)); - MOCK_CONST_METHOD2(SetPostEffectParamString, - void(const char* pParam, const char* pszArg)); - MOCK_CONST_METHOD2(GetPostEffectParam, - void(const char* pParam, float& fValue)); - MOCK_CONST_METHOD2(GetPostEffectParamVec4, - void(const char* pParam, Vec4& pValue)); - MOCK_CONST_METHOD2(GetPostEffectParamString, - void(const char* pParam, const char*& pszArg)); - MOCK_METHOD1(GetPostEffectID, - int32(const char* pPostEffectName)); - MOCK_METHOD1(ResetPostEffects, - void(bool)); - MOCK_METHOD0(DisablePostEffects, - void()); - MOCK_METHOD1(SetShadowsGSMCache, - void(bool bCache)); - MOCK_METHOD2(SetCachedShadowBounds, - void(const AABB& shadowBounds, float fAdditionalCascadesScale)); - MOCK_METHOD1(SetRecomputeCachedShadows, - void(uint)); - MOCK_METHOD0(CheckMemoryHeap, - void()); - MOCK_METHOD1(DeleteEntityDecals, - void(IRenderNode* pEntity)); - MOCK_METHOD0(LockCGFResources, - void()); - MOCK_METHOD0(UnlockCGFResources, - void()); - MOCK_METHOD0(FreeUnusedCGFResources, - void()); - MOCK_METHOD0(CreateStatObj, - IStatObj*()); - MOCK_METHOD1(CreateStatObjOptionalIndexedMesh, - IStatObj*(bool createIndexedMesh)); - MOCK_METHOD0(CreateIndexedMesh, - IIndexedMesh*()); - MOCK_METHOD1(SerializeState, - void(TSerialize ser)); - MOCK_METHOD1(PostSerialize, - void(bool bReading)); - MOCK_METHOD0(GetMaterialHelpers, - IMaterialHelpers&()); - MOCK_METHOD0(GetMaterialManager, - IMaterialManager*()); - MOCK_METHOD0(GetObjManager, - IObjManager*()); - MOCK_METHOD1(CreateChunkfileContent, - CContentCGF*(const char* filename)); - MOCK_METHOD1(ReleaseChunkfileContent, - void(CContentCGF*)); - MOCK_METHOD4(LoadChunkFileContent, - bool(CContentCGF* pCGF, const char* filename, bool bNoWarningMode, bool bCopyChunkFile)); - MOCK_METHOD6(LoadChunkFileContentFromMem, - bool(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode, bool bCopyChunkFile)); - MOCK_METHOD1(CreateChunkFile, - IChunkFile*(bool)); - MOCK_CONST_METHOD3(CreateChunkFileWriter, - ChunkFile::IChunkFileWriter*(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename)); - MOCK_CONST_METHOD1(ReleaseChunkFileWriter, - void(ChunkFile::IChunkFileWriter* p)); - MOCK_METHOD2(CreateOcean, - bool(_smart_ptr pTerrainWaterMat, float waterLevel)); - MOCK_METHOD0(DeleteOcean, - void()); - MOCK_METHOD1(ChangeOceanMaterial, - void(_smart_ptr pMat)); - MOCK_METHOD1(ChangeOceanWaterLevel, - void(float fWaterLevel)); - MOCK_METHOD1(InitMaterialDefautMappingAxis - , void(_smart_ptr pMat)); - MOCK_METHOD0(GetIVisAreaManager, - IVisAreaManager*()); - MOCK_METHOD3(PrecacheLevel, - void(bool bPrecacheAllVisAreas, Vec3* pPrecachePoints, int nPrecachePointsNum)); - MOCK_METHOD0(ProposeContentPrecache, - void()); - MOCK_METHOD0(GetTimeOfDay, - ITimeOfDay*()); - MOCK_METHOD1(SetSkyMaterialPath, - void(const string& skyMaterialPath)); - MOCK_METHOD1(SetSkyLowSpecMaterialPath, - void(const string& skyMaterialPath)); - MOCK_METHOD0(LoadSkyMaterial, - void()); - MOCK_METHOD0(GetSkyMaterial, - _smart_ptr()); - MOCK_METHOD1(SetSkyMaterial, - void(_smart_ptr pSkyMat)); - MOCK_METHOD2(SetGlobalParameter, - void(E3DEngineParameter param, const Vec3& v)); - MOCK_METHOD2(GetGlobalParameter, - void(E3DEngineParameter param, Vec3& v)); - MOCK_METHOD1(SetShadowMode, - void(EShadowMode shadowMode)); - MOCK_CONST_METHOD0(GetShadowMode, - EShadowMode()); - MOCK_METHOD6(AddPerObjectShadow, - void(IShadowCaster* pCaster, float fConstBias, float fSlopeBias, float fJitter, const Vec3& vBBoxScale, uint nTexSize)); - MOCK_METHOD1(RemovePerObjectShadow, - void(IShadowCaster* pCaster)); - MOCK_METHOD1(GetPerObjectShadow, - struct SPerObjectShadow*(IShadowCaster* pCaster)); - MOCK_METHOD2(GetCustomShadowMapFrustums, - void(struct ShadowMapFrustum*& arrFrustums, int& nFrustumCount)); - MOCK_METHOD2(SaveStatObj, - int(IStatObj* pStatObj, TSerialize ser)); - MOCK_METHOD1(LoadStatObj, - IStatObj*(TSerialize ser)); - MOCK_METHOD2(CheckIntersectClouds, - bool(const Vec3& p1, const Vec3& p2)); - MOCK_METHOD1(OnRenderMeshDeleted, - void(IRenderMesh* pRenderMesh)); - MOCK_METHOD0(DebugDraw_UpdateDebugNode, - void()); - MOCK_METHOD4(RayObjectsIntersection2D, - bool(Vec3 vStart, Vec3 vEnd, Vec3& vHitPoint, EERType eERType)); - MOCK_METHOD3(RenderMeshRayIntersection, - bool(IRenderMesh* pRenderMesh, SRayHitInfo& hitInfo, _smart_ptr pCustomMtl)); - MOCK_METHOD3(CheckCreateRNTmpData - , void(CRNTmpData** ppInfo, IRenderNode* pRNode, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(FreeRNTmpData, - void(CRNTmpData** ppInfo)); - MOCK_METHOD0(IsObjectTreeReady - , bool()); - MOCK_METHOD0(GetIObjectTree - , IOctreeNode*()); - MOCK_METHOD2(GetObjectsByType, - uint32(EERType, IRenderNode**)); - MOCK_METHOD4(GetObjectsByTypeInBox, - uint32(EERType objType, const AABB& bbox, IRenderNode** pObjects, ObjectTreeQueryFilterCallback filterCallback)); - MOCK_METHOD2(GetObjectsInBox, - uint32(const AABB& bbox, IRenderNode** pObjects)); - MOCK_METHOD2(GetObjectsByFlags, - uint32(uint, IRenderNode**)); - MOCK_METHOD4(GetObjectsByTypeInBox, - void(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback)); - MOCK_METHOD2(OnObjectModified, - void(IRenderNode* pRenderNode, uint dwFlags)); - MOCK_METHOD1(FillDebugFPSInfo, - void(SDebugFPSInfo&)); - MOCK_METHOD0(GetLevelFolder, - const char*()); - MOCK_METHOD0(IsAreaActivationInUse, - bool()); - MOCK_METHOD3(RenderRenderNode_ShadowPass, - void(IShadowCaster* pRNode, const SRenderingPassInfo& passInfo, AZ::LegacyJobExecutor* pJobExecutor)); - MOCK_METHOD0(GetOpticsManager, - IOpticsManager*()); - MOCK_METHOD0(SyncProcessStreamingUpdate, - void()); - MOCK_METHOD1(SetScreenshotCallback, - void(IScreenshotCallback* pCallback)); - MOCK_METHOD8(ActivateObjectsLayer, - void(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap, bool bCheckLayerActivation)); - MOCK_CONST_METHOD4(GetLayerMemoryUsage, - void(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals)); - MOCK_METHOD2(SkipLayerLoading, - void(uint16 nLayerId, bool bClearList)); - MOCK_METHOD2(PrecacheRenderNode, - void(IRenderNode* pObj, float fEntDistanceReal)); - MOCK_METHOD0(GetDeferredPhysicsEventManager, - IDeferredPhysicsEventManager*()); - MOCK_METHOD1(SetStreamableListener, - void(IStreamedObjectListener* pListener)); - MOCK_METHOD1(GetRenderingPassCamera, - CCamera*(const CCamera& rCamera)); - MOCK_METHOD3(GetSvoStaticTextures, - void(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D)); - MOCK_METHOD2(GetSvoBricksForUpdate, - void(PodArray& arrNodeInfo, bool getDynamic)); -#if defined(USE_GEOM_CACHES) - MOCK_METHOD1(LoadGeomCache, - IGeomCache*(const char* szFileName)); - MOCK_METHOD1(FindGeomCacheByFilename, - IGeomCache*(const char* szFileName)); -#endif - MOCK_METHOD3(LoadDesignerObject, - IStatObj*(int nVersion, const char* szBinaryStream, int size)); - - MOCK_METHOD0(WaitForCullingJobsCompletion, - void()); -}; - diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 2021e96172..757c586261 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -12,11 +12,15 @@ #pragma once #include -#include // needed for SRenderingPassInfo definition #include #include #include +struct SRendItemSorter {}; +struct SRenderingPassInfo {}; +struct SClipVolumeBlendInfo {}; +struct SFogVolumeData {}; + // the following was generated using google's python script to autogenerate mocks. // however, it needed some hand-editing to make it work, so if you add functions to IRenderer, // it will probably be better to just manually add them here than try to run the script again diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 5edd84fd75..4d2e80a2f3 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -37,12 +37,6 @@ public: void()); MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, bool()); - MOCK_METHOD0(Render, - void()); - MOCK_METHOD0(RenderBegin, - void()); - MOCK_METHOD2(RenderEnd, - void(bool, bool)); MOCK_METHOD2(SynchronousLoadingTick, void(const char* pFunc, int line)); MOCK_METHOD0(RenderStatistics, @@ -124,8 +118,6 @@ public: IMovieSystem * ()); MOCK_METHOD0(GetIAudioSystem, Audio::IAudioSystem * ()); - MOCK_METHOD0(GetI3DEngine, - I3DEngine * ()); MOCK_METHOD0(GetIConsole, ::IConsole * ()); MOCK_METHOD0(GetIRemoteConsole, diff --git a/Code/CryEngine/CryCommon/Mocks/StubTimer.h b/Code/CryEngine/CryCommon/Mocks/StubTimer.h index fe3a11fb42..cd275ac17b 100644 --- a/Code/CryEngine/CryCommon/Mocks/StubTimer.h +++ b/Code/CryEngine/CryCommon/Mocks/StubTimer.h @@ -11,6 +11,8 @@ */ #pragma once +#include + //! Simple stub timer that exposes a single simple interface for setting the current time. class StubTimer : public ITimer diff --git a/Code/CryEngine/CryCommon/WindowsUtils.h b/Code/CryEngine/CryCommon/WindowsUtils.h deleted file mode 100644 index 96b3a86606..0000000000 --- a/Code/CryEngine/CryCommon/WindowsUtils.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#if defined(WIN32) -#include "CryWindows.h" -#include "IRenderer.h" -#include "IImage.h" -#include "smartptr.h" -#include "ImageExtensionHelper.h" - -// Types supported by CreateResourceFromTexture -enum EResourceType -{ - eResourceType_IconBig, - eResourceType_IconSmall, - eResourceType_Cursor, -}; - -// Loads a (DDS) texture resource from the renderer into a Win32 GDI resource. -// Returns a HICON that must be closed with DestroyIcon(), or NULL on failure. -static HICON CreateResourceFromTexture(IRenderer* pRenderer, const char* path, EResourceType type) -{ - if (!pRenderer || !path || !*path) - { - // Invalid parameter passed - return NULL; - } - - // Find the target dimensions of the GDI resource - const int nRequestedWidth = GetSystemMetrics(type == eResourceType_IconBig ? SM_CXICON : type == eResourceType_IconSmall ? SM_CXSMICON : SM_CXCURSOR); - const int nRequestedHeight = GetSystemMetrics(type == eResourceType_IconBig ? SM_CYICON : type == eResourceType_IconSmall ? SM_CYSMICON : SM_CYCURSOR); - if (nRequestedWidth != nRequestedHeight || nRequestedHeight <= 0 || nRequestedWidth <= 0) - { - // Don't support non-squares icons or cursors - return NULL; - } - - // Load texture. - // in this case, we want to fall back on a null, not substiture the missing texture. - _smart_ptr pImage = pRenderer->EF_LoadImage(path, FIM_NOFALLBACKS); - if (!pImage || pImage->mfGet_depth() != 1 || pImage->mfGet_NumSides() != 1 || pImage->mfGetTileMode() != eTM_None) - { - // Can't load texture, or texture is a cube-map or volume texture, or uses tiling of some kind - return NULL; - } - byte* pImgRaw = pImage->mfGet_image(0); - const ETEX_Format texFormat = pImage->mfGetFormat(); - - // Pick first mip level smaller than the GDI resource - int nMip = 0; - size_t offset = 0; - int nMipWidth = pImage->mfGet_width(); - int nMipHeight = pImage->mfGet_height(); - while (nMipWidth > nRequestedWidth) - { - ++nMip; - offset += pRenderer->GetTextureFormatDataSize(nMipWidth, nMipHeight, 1, 1, texFormat); - nMipWidth = max(nMipWidth / 2, 1); - nMipHeight = max(nMipHeight / 2, 1); - } - pImgRaw += offset; - if (nMip >= pImage->mfGet_numMips()) - { - // No appropriate mip in the texture - // Note: Consider creating a full mip-chain on the texture so this can't happen - return NULL; - } - const size_t nRawSize = pRenderer->GetTextureFormatDataSize(nMipWidth, nMipHeight, 1, 1, texFormat); - -#if 0 - // Check that DDS indexing is correct here - offset += nRawSize; - for (int nIdx = nMip + 1; nIdx < pImage->mfGet_numMips(); ++nIdx) - { - const int w = max(nMipWidth >> (nIdx - nMip), 1); - const int h = max(nMipHeight >> (nIdx - nMip), 1); - offset += pRenderer->GetTextureFormatDataSize(w, h, 1, 1, texFormat); - } - assert(offset == pImage->mfGet_ImageSize()); -#endif - - // Type of bitmap to create - BITMAPV5HEADER bi = { 0 }; - bi.bV5Size = sizeof(BITMAPV5HEADER); - bi.bV5Width = nRequestedWidth; - bi.bV5Height = -nRequestedHeight; - bi.bV5Planes = 1; - bi.bV5BitCount = 32; - bi.bV5Compression = BI_BITFIELDS; - // The following mask specification specifies a supported 32 BPP alpha format for Windows XP+ - bi.bV5AlphaMask = 0xFF000000; - bi.bV5RedMask = 0x00FF0000; - bi.bV5GreenMask = 0x0000FF00; - bi.bV5BlueMask = 0x000000FF; - - // Create the DIB section with an alpha channel - const HDC hdc = GetDC(NULL); - void* lpBits; - const HBITMAP hBitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, &lpBits, NULL, 0); - ReleaseDC(NULL, hdc); - if (!hBitmap || !lpBits) - { - // Can't allocate OS bitmap - return NULL; - } - GdiFlush(); - - // Decompress texture - const bool bTryDecompress = texFormat != eTF_R8G8B8A8 && texFormat != eTF_B8G8R8A8 && texFormat != eTF_B8G8R8X8; - byte* const pImgDecomp = bTryDecompress ? new byte[nMipWidth * nMipHeight * sizeof(int32)] : pImgRaw; - const bool bImgDecompressed = bTryDecompress && pRenderer->DXTDecompress(pImgRaw, nRawSize, pImgDecomp, nMipWidth, nMipHeight, 1, texFormat, false, sizeof(int32)); - - // Check which conversions need to be performed - const bool bSRGB = (pImage->mfGet_Flags() & CImageExtensionHelper::EIF_SRGBRead) != 0; - const bool bSwap = (texFormat == eTF_R8G8B8A8) || bTryDecompress; - - HICON result = NULL; - if (!bTryDecompress || bImgDecompressed) - { - // Assign texture data with mismatching sizes - // Note: Any pixels not in the selected mip will become 100% transparent black, no resizing is performed - const size_t sourceRowStride = nMipWidth; - const size_t targetRowStride = nRequestedWidth; - const uint32* pSourceRow = (uint32*)pImgDecomp; - uint32* pTargetRow = (uint32*)lpBits; - - assert(sourceRowStride <= targetRowStride); - assert(nMipHeight <= nRequestedHeight); - assert(pSourceRow != pTargetRow); - assert(pSourceRow && pTargetRow); - - uint8 gammaTable[256]; - if (!bSRGB) - { - // Linear to sRGB table - const float gamma = 1.0f / 2.2f; - const float gammaMultiplier = 255.0f / powf(255.0f, gamma); - for (int i = 0; i < 256; ++i) - { - gammaTable[i] = uint8(powf(float(i), gamma) * gammaMultiplier); - } - } - else if (bSwap) - { - // sRGB to sRGB table (no change) - for (int i = 0; i < 256; ++i) - { - gammaTable[i] = uint8(i); - } - } - - for (int y = 0; y < nMipHeight; ++y, pSourceRow += sourceRowStride, pTargetRow += targetRowStride) - { - if (!bSwap && bSRGB) - { - memcpy(pTargetRow, pSourceRow, sourceRowStride * sizeof(uint32)); - } - else - { - const uint32* pSourceTexel = pSourceRow; - uint32* pTargetTexel = pTargetRow; - for (int x = 0; x < nMipWidth; ++x, ++pSourceTexel, ++pTargetTexel) - { - const uint8 red = gammaTable[uint8(*pSourceTexel >> 0)]; - const uint8 green = gammaTable[uint8(*pSourceTexel >> 8)]; - const uint8 blue = gammaTable[uint8(*pSourceTexel >> 16)]; - const uint32 alpha = *pSourceTexel & 0xFF000000; - *pTargetTexel = (red << (bSwap ? 16 : 0)) | (green << 8) | (blue << (bSwap ? 0 : 16)) | alpha; - } - } - - // Fill remaining columns with zeros - memset(pTargetRow + sourceRowStride, 0, (targetRowStride - sourceRowStride) * sizeof(uint32)); - } - - // Fill remaining rows with zeros - for (int y = nMipHeight; y < nRequestedHeight; ++y) - { - memset(pTargetRow, 0, targetRowStride * sizeof(uint32)); - pTargetRow += targetRowStride; - } - - // Convert to GDI icon - ICONINFO iconinfo = {0}; - iconinfo.fIcon = type == eResourceType_Cursor ? FALSE : TRUE; - iconinfo.hbmMask = ::CreateBitmap(nRequestedWidth, nRequestedHeight, 1, 1, NULL); - iconinfo.hbmColor = hBitmap; - result = ::CreateIconIndirect(&iconinfo); - DeleteObject(iconinfo.hbmMask); - } - - // Clean up - DeleteObject(hBitmap); - if (bTryDecompress) - { - delete[] pImgDecomp; - } - pImage.reset(); - - return result; -} - -#endif diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index ef49370c08..7d169c2643 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -14,9 +14,6 @@ set(FILES CryCommon.cpp Allocator.h FinalizingSpline.h - Gem.h - I3DEngine.h - I3DEngine_info.h IAudioInterfacesCommonData.h IAudioSystem.h IChunkFile.h @@ -86,7 +83,6 @@ set(FILES ITexture.h IThreadManager.h IThreadTask.h - ITimeOfDay.h ITimer.h IValidator.h IVideoRenderer.h @@ -143,7 +139,6 @@ set(FILES CryAssert.h CryCrc32.h CryCustomTypes.h - CryEngineDecalInfo.h CryFile.h CryFixedArray.h CryFixedString.h @@ -292,7 +287,6 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - WindowsUtils.h CryExtension/CryCreateClassInstance.h CryExtension/CryGUID.h CryExtension/CryTypeID.h @@ -317,7 +311,6 @@ set(FILES CryPool/STLWrapper.h CryPool/ThreadSafe.h stl/STLAlignedAlloc.h - ILocalMemoryUsage.h Serialization/Assert.h Serialization/BitVector.h Serialization/BitVectorImpl.h diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake index ca133c2497..d20a33f791 100644 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Mocks/I3DEngineMock.h Mocks/IAudioSystemMock.h Mocks/IConsoleMock.h Mocks/ICryPakMock.h diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h index 6cf4c6005a..b446199b4e 100644 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ b/Code/CryEngine/CrySystem/CrySystem_precompiled.h @@ -102,7 +102,6 @@ inline int RoundToClosestMB(size_t memSize) #include #include #include -#include #include #include #include @@ -127,7 +126,6 @@ namespace AZ::IO struct IArchive; } struct ICryFont; -struct I3DEngine; struct IMovieSystem; struct IAudioSystem; struct IPhysicalWorld; diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index 996dee7810..d31f122d9b 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -193,10 +193,6 @@ static void UnloadMap([[maybe_unused]] IConsoleCmdArgs* args) if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) { gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LoadEmptyLevel(); - } } } @@ -674,18 +670,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) pSpamDelay->Set(0.0f); } - if (gEnv->p3DEngine) - { - bool is3DEngineLoaded = gEnv->IsEditor() ? gEnv->p3DEngine->InitLevelForEditor(pLevelInfo->GetPath(), pLevelInfo->m_defaultGameTypeName.c_str()) - : gEnv->p3DEngine->LoadLevel(pLevelInfo->GetPath(), pLevelInfo->m_defaultGameTypeName.c_str()); - if (!is3DEngineLoaded) - { - OnLoadingError(levelName, "3DEngine failed to handle loading the level"); - - return 0; - } - } - // Parse level specific config data. AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); @@ -760,14 +744,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - ////////////////////////////////////////////////////////////////////////// - // Notify 3D engine that loading finished - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// gEnv->pConsole->SetScrollMax(600 / 2); @@ -991,18 +967,6 @@ void CLevelSystem::UnloadLevel() CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (p3DEngine) - { - IDeferredPhysicsEventManager* pPhysEventManager = p3DEngine->GetDeferredPhysicsEventManager(); - if (pPhysEventManager) - { - // clear deferred physics queues before renderer, since we could have jobs running - // which access a rendermesh - pPhysEventManager->ClearDeferredEvents(); - } - } - //AM: Flush render thread (Flush is not exposed - using EndFrame()) //We are about to delete resources that could be in use if (gEnv->pRenderer) @@ -1076,25 +1040,10 @@ void CLevelSystem::UnloadLevel() SAFE_RELEASE(m_pCurrentLevel); - /* - Force Lua garbage collection before p3DEngine->UnloadLevel() and pRenderer->FreeResources(flags) are called. - p3DEngine->UnloadLevel() will destroy particle emitters even if they're still referenced by Lua objects that are yet to be collected. - (as per comment in 3dEngineLoad.cpp (line 501) - "Force to clean all particles that are left, even if still referenced."). - Then, during the next GC cycle, Lua finally cleans up, the particle emitter smart pointers will be pointing to invalid memory). - Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event), which is too late - (after the render resources have been purged). - This extra GC step takes a few ms more level unload time, which is a small price for fixing nasty crashes. - If, however, we wanted to claim it back, we could potentially get rid of the GC step that is triggered by ESYSTEM_EVENT_LEVEL_POST_UNLOAD to break even. - */ - + // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). + // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Delete engine resources - if (p3DEngine) - { - p3DEngine->UnloadLevel(); - - } // Force to clean render resources left after deleting all objects and materials. IRenderer* pRenderer = gEnv->pRenderer; if (pRenderer) diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 67bf0a6c8e..4b6e210522 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -55,10 +55,6 @@ namespace LegacyLevelSystem if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) { gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LoadEmptyLevel(); - } } } @@ -262,22 +258,6 @@ namespace LegacyLevelSystem pSpamDelay->Set(0.0f); } - if (gEnv->p3DEngine) - { - AZ::IO::PathView levelPath(levelName); - AZStd::string parentPath(levelPath.ParentPath().Native()); - - static constexpr const char* defaultGameTypeName = "Mission0"; - bool is3DEngineLoaded = gEnv->IsEditor() ? gEnv->p3DEngine->InitLevelForEditor(parentPath.c_str(), defaultGameTypeName) - : gEnv->p3DEngine->LoadLevel(parentPath.c_str(), defaultGameTypeName); - if (!is3DEngineLoaded) - { - OnLoadingError(levelName, "3DEngine failed to handle loading the level"); - - return 0; - } - } - // Parse level specific config data. AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); @@ -340,14 +320,6 @@ namespace LegacyLevelSystem gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - ////////////////////////////////////////////////////////////////////////// - // Notify 3D engine that loading finished - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// gEnv->pConsole->SetScrollMax(600 / 2); @@ -569,18 +541,6 @@ namespace LegacyLevelSystem CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (p3DEngine) - { - IDeferredPhysicsEventManager* pPhysEventManager = p3DEngine->GetDeferredPhysicsEventManager(); - if (pPhysEventManager) - { - // clear deferred physics queues before renderer, since we could have jobs running - // which access a rendermesh - pPhysEventManager->ClearDeferredEvents(); - } - } - // AM: Flush render thread (Flush is not exposed - using EndFrame()) // We are about to delete resources that could be in use if (gEnv->pRenderer) @@ -644,25 +604,10 @@ namespace LegacyLevelSystem GetISystem()->GetIResourceManager()->UnloadLevel(); - /* - Force Lua garbage collection before p3DEngine->UnloadLevel() and pRenderer->FreeResources(flags) are called. - p3DEngine->UnloadLevel() will destroy particle emitters even if they're still referenced by Lua objects that are yet to be - collected. (as per comment in 3dEngineLoad.cpp (line 501) - "Force to clean all particles that are left, even if still referenced."). - Then, during the next GC cycle, Lua finally cleans up, the particle emitter smart pointers will be pointing to invalid memory). - Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event), which is too late - (after the render resources have been purged). - This extra GC step takes a few ms more level unload time, which is a small price for fixing nasty crashes. - If, however, we wanted to claim it back, we could potentially get rid of the GC step that is triggered by - ESYSTEM_EVENT_LEVEL_POST_UNLOAD to break even. - */ - + // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). + // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Delete engine resources - if (p3DEngine) - { - p3DEngine->UnloadLevel(); - } // Force to clean render resources left after deleting all objects and materials. IRenderer* pRenderer = gEnv->pRenderer; if (pRenderer) diff --git a/Code/CryEngine/CrySystem/PerfHUD.cpp b/Code/CryEngine/CrySystem/PerfHUD.cpp index 23a5fc0ced..2aeabe2650 100644 --- a/Code/CryEngine/CrySystem/PerfHUD.cpp +++ b/Code/CryEngine/CrySystem/PerfHUD.cpp @@ -22,7 +22,6 @@ #include "MiniGUI/MiniMenu.h" #include "MiniGUI/MiniTable.h" #include -#include #include #include "System.h" @@ -853,21 +852,6 @@ void CPerfHUD::SaveStatsCallback([[maybe_unused]] void* data, [[maybe_unused]] b // RENDER CALLBACKS ////////////////////////////////////////////////////////////////////////// -/* -void CPerfHUD::DisplayRenderInfoCallback(const Rect& rect) -{ - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface( cryiidof(),pGUI )) - { - //right aligned display - float x = rect.right; - float y = rect.top; - float step = 13.f; - - gEnv->p3DEngine->DisplayInfo(x, y, step, true); - } -}*/ - void CPerfHUD::EnableWidget(ICryPerfHUDWidget::EWidgetID id, int mode) { const int nWidgets = m_widgets.size(); @@ -1530,26 +1514,6 @@ void CRenderStatsWidget::Update() m_runtimeData.nFwdLights = 0; m_runtimeData.nFwdShadowLights = 0; - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - I3DEngine::SObjectsStreamingStatus objStats; - gEnv->p3DEngine->GetObjectsStreamingStatus(objStats); - - float fMeshRequiredMB = (float)(objStats.nMemRequired) / (1024 * 1024); - sprintf_s(entryBuffer, "Mesh Required: %.2f (%dMB)", fMeshRequiredMB, azlossy_cast(objStats.nMeshPoolSize)); - if (fMeshRequiredMB < objStats.nMeshPoolSize) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Geometry: %.2fMB", fMeshRequiredMB); - } - } - - ////////////////////////////////////////////////////////////////////////// if (gEnv->pRenderer) { @@ -1727,25 +1691,6 @@ CStreamingStatsWidget::CStreamingStatsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD ////////////////////////////////////////////////////////////////////////// void CStreamingStatsWidget::Update() { - char entryBuffer[CMiniInfoBox::MAX_TEXT_LENGTH] = {0}; - - //Clear old entries - m_pInfoBox->ClearEntries(); - - I3DEngine::SObjectsStreamingStatus objStats; - gEnv->p3DEngine->GetObjectsStreamingStatus(objStats); - - float fMeshRequiredMB = (float)(objStats.nMemRequired) / (1024 * 1024); - sprintf_s(entryBuffer, "Mesh Required: %.2f (%dMB)", fMeshRequiredMB, objStats.nMeshPoolSize); - if (fMeshRequiredMB < objStats.nMeshPoolSize) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Geometry: %.2fMB", fMeshRequiredMB); - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp b/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp deleted file mode 100644 index 7eb86de966..0000000000 --- a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp +++ /dev/null @@ -1,1389 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual helper for checking a local memory usage on maps - -/* - TODO: - - Procedural vegetation - - - Permanent mip-map problem (streaming will collect a permanent mip-maps when travelling) - - ? Foliage render nodes - - must make a decision about the local / global problem: - - Particle effects (must check the calculation) - - Characters (calculation is DONE) - - - StatObj LOD streaming (I think that there is no LOD streaming, but i'm not sure about this) - - Terrain texture streaming (not detail textures!) //It's not needed because this system using a fix-size pool - - Animation streaming: completely different system, not need to measure now - - IsoMesh streaming: completely different system, not need to measure now -*/ - - -#include "CrySystem_precompiled.h" - -#include "LocalMemoryUsage.h" - -#include -#include -#include -#include - -#include - -//#define MAX_LODS 6 // I want an engine-wide const :-( -#define MAX_SLOTS 100 // GetSlotCount() is not working :-( -#define BIG_NUMBER 1e20f - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace LocalMemoryUsageDrawHelper -{ - enum eDrawRectParams - { - DSP_YDIR = 0, - DSP_XDIR = 1, - DSP_REVERSE_TRIANGLES = 2, - DSP_REVERSE_ARROW = 4, - }; - - void DrawRect(IRenderer* pRenderer, const CCamera* camera, const Vec3& p1, const Vec3& p3, const ColorB& color, int params = 0) - { - Vec3 p2, p4, projectedPos; - if (!(params & DSP_REVERSE_TRIANGLES)) - { - if (params & DSP_XDIR) - { - p2 = Vec3(p1.x, p3.y, p1.z); - p4 = Vec3(p3.x, p1.y, p3.z); - } - else - { - p2 = Vec3(p1.x, p3.y, p3.z); - p4 = Vec3(p3.x, p1.y, p1.z); - } - } - else - { - if (params & DSP_XDIR) - { - p4 = Vec3(p1.x, p3.y, p1.z); - p2 = Vec3(p3.x, p1.y, p3.z); - } - else - { - p4 = Vec3(p1.x, p3.y, p3.z); - p2 = Vec3(p3.x, p1.y, p1.z); - } - } - - if (camera->Project(p1, projectedPos) || camera->Project(p2, projectedPos) || camera->Project(p3, projectedPos) || camera->Project(p4, projectedPos)) - { - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - pRenderAuxGeom->DrawTriangle(p1, color, p2, color, p3, color); - pRenderAuxGeom->DrawTriangle(p3, color, p4, color, p1, color); - } - } - - void DrawArrow(IRenderer* pRenderer, const CCamera* camera, Vec3 pStart, Vec3 pEnd, float width, float head, float lengthSub, const ColorB& color, int params = 0) - { - Vec3 p1, p2, p3, p4, p5, p6, p7, projectedPos; - - if (params & DSP_REVERSE_ARROW) - { - std::swap(pStart, pEnd); - } - - Vec3 vParallel((pEnd - pStart).GetNormalized()); - Vec3 vOrto = vParallel.Cross(Vec3(0, 0, 1)).GetNormalized(); - pStart += vParallel * lengthSub; - pEnd -= vParallel * lengthSub; - - p1 = pStart - (vOrto * width * 0.5f); - p2 = pStart + (vOrto * width * 0.5f); - p3 = (pEnd - vParallel * head) - (vOrto * width * 0.5f); - p4 = (pEnd - vParallel * head) + (vOrto * width * 0.5f); - p5 = (pEnd - vParallel * head * 1.5f) - (vOrto * head * 0.9f); - p6 = (pEnd - vParallel * head * 1.5f) + (vOrto * head * 0.9f); - p7 = pEnd; - - if (camera->Project(p1, projectedPos) || camera->Project(p7, projectedPos)) - { - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - pRenderAuxGeom->DrawTriangle(p1, color, p2, color, p4, color); - pRenderAuxGeom->DrawTriangle(p4, color, p3, color, p1, color); - pRenderAuxGeom->DrawTriangle(p3, color, p4, color, p7, color); - pRenderAuxGeom->DrawTriangle(p4, color, p6, color, p7, color); - pRenderAuxGeom->DrawTriangle(p5, color, p3, color, p7, color); - } - } - - #define DRAWHELPER_CIRCLE_POINT_NR 32 - - - static Vec3 s_CirclePoints[DRAWHELPER_CIRCLE_POINT_NR + 1]; - static bool s_CircleDataInited = false; - void InitCircleData() - { - s_CircleDataInited = true; - float angleDiff = 2.0f * 3.1415927f / DRAWHELPER_CIRCLE_POINT_NR; - - for (int i = 0; i < DRAWHELPER_CIRCLE_POINT_NR + 1; i++) - { - s_CirclePoints[i] = Vec3(cos(i * angleDiff), sin(i * angleDiff), 0.0f); - } - } - - void DrawCircle(IRenderer* pRenderer, [[maybe_unused]] const CCamera* camera, const Vec3& origo, float radius, float ratio, const ColorB& color1, const ColorB& color2) - { - if (!s_CircleDataInited) - { - InitCircleData(); - } - float radius2 = radius * 0.90f; - - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - Vec3 oldPoint = origo + s_CirclePoints[0] * radius; - Vec3 oldPoint2 = origo + s_CirclePoints[0] * radius2; - - for (int i = 0; i < DRAWHELPER_CIRCLE_POINT_NR; i++) - { - Vec3 newPoint = origo + s_CirclePoints[i + 1] * radius; - Vec3 newPoint2 = origo + s_CirclePoints[i + 1] * radius2; - if (i < ratio * DRAWHELPER_CIRCLE_POINT_NR) - { - pRenderAuxGeom->DrawTriangle(origo, color1, oldPoint, color1, newPoint, color1); - } - else - { - //pRenderAuxGeom->DrawTriangle( origo, color2, oldPoint, color2, newPoint, color2 ); - pRenderAuxGeom->DrawTriangle(oldPoint2, color2, oldPoint, color2, newPoint, color2); - pRenderAuxGeom->DrawTriangle(newPoint, color2, newPoint2, color2, oldPoint2, color2); - } - oldPoint = newPoint; - oldPoint2 = newPoint2; - } - } -} - -/* -namespace Distance -{ - // Distance: AABB_AABB - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a AABB to an another AABB in 3d-space. - // The function returns the squared distance. - // optionally the closest point on the hull is calculated - // - // Example: - // float result = Distance::Point_AABBSq( aabb1, aabb2 ); - //---------------------------------------------------------------------------------- - - ILINE float AABB_AABBSq( const AABB& aabb1, const AABB& aabb2 ) - { - float fDist2 = 0; - for(int i=0; i<3; ++i) - { - float max1 = aabb1.max[i]; - if(max1 < aabb2.min[i]) - { - fDist2 += sqr(max1-aabb2.min[i]); - } - else - { - float min1 = aabb1.min[i]; - if(min1 > aabb2.max[i]) - { - fDist2 += sqr(aabb2.max[i]-min1); - } - } - } - return fDist2; - } - - // Distance: AABB_AABB_2D - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a AABB to an another AABB in 2d-space. - // The function returns the squared distance. - // optionally the closest point on the hull is calculated - // - // Example: - // float result = Distance::AABB_AABB2DSq( aabb1, aabb2 ); - //---------------------------------------------------------------------------------- - - ILINE float AABB_AABB2DSq( const AABB& aabb1, const AABB& aabb2 ) - { - float fDist2 = 0; - for(int i=0; i<2; ++i) //We are using only 2 of the dimensions! - { - float max1 = aabb1.max[i]; - if(max1 < aabb2.min[i]) - { - fDist2 += sqr(max1-aabb2.min[i]); - } - else - { - float min1 = aabb1.min[i]; - if(min1 > aabb2.max[i]) - { - fDist2 += sqr(aabb2.max[i]-min1); - } - } - } - return fDist2; - } -} -*/ - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -int CLocalMemoryUsage::SResource::m_arrMemoryUsage[LOCALMEMORY_SECTOR_PER_PASS]; -int CLocalMemoryUsage::SResource::m_arrPieces[LOCALMEMORY_SECTOR_PER_PASS]; - - -CLocalMemoryUsage::SResource::SResource() -{ - m_used = true; -} - -void CLocalMemoryUsage::SResource::Init(CLocalMemoryUsage* pLocalMemoryUsage) -{ - m_pLocalMemoryUsage = pLocalMemoryUsage; - - StartChecking(); -} - -void CLocalMemoryUsage::SResource::StartChecking() -{ - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - float* pMipFactor = m_arrMipFactor; - for (int i = 0; i < actProcessedSectors.w * actProcessedSectors.h; i++) - { - *pMipFactor = BIG_NUMBER; - pMipFactor++; - } - bool* pRowDirty = m_arrRowDirty; - for (int i = 0; i < LOCALMEMORY_SECTOR_PER_PASS; i++) - { - *pRowDirty = false; - pRowDirty++; - } -} - -void CLocalMemoryUsage::SResource::CheckOnAllSectorsP1(const AABB& bounding, float maxViewDist, float scale, float mipFactor) -{ - //FRAME_PROFILER("! CLocalMemoryUsage::SResource::CheckOnAllSectorsP1", GetISystem(), PROFILE_SYSTEM); - - float modifiedmaxViewDist = maxViewDist; - float modifiedmaxViewDistSqr = sqr(modifiedmaxViewDist); - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - int xMin = (int)max(0, int((bounding.min.x - modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE ) - actProcessedSectors.x); - int xMax = (int)min(actProcessedSectors.w, int((bounding.max.x + modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE + 1) - actProcessedSectors.x); - int yMin = (int)max(0, int((bounding.min.y - modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE ) - actProcessedSectors.y); - int yMax = (int)min(actProcessedSectors.h, int((bounding.max.y + modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE + 1) - actProcessedSectors.y); - - AABB sectorBounding(AABB::RESET); - float sectorDistanceSqr; - float fDistYSqr; - - for (int y = yMin; y < yMax; y++) - { - float* pMipFactor = &m_arrMipFactor[actProcessedSectors.w * y + xMin]; - - sectorBounding.min.y = (y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_SIZE; - sectorBounding.max.y = sectorBounding.min.y + LOCALMEMORY_SECTOR_SIZE; - sectorBounding.min.x = (xMin + actProcessedSectors.x) * LOCALMEMORY_SECTOR_SIZE; - - assert(y < LOCALMEMORY_SECTOR_PER_PASS); - m_arrRowDirty[y] = true; - - //Calculating Y distance sqr - { - fDistYSqr = 0; - if (bounding.max.y < sectorBounding.min.y) - { - fDistYSqr += sqr(bounding.max.y - sectorBounding.min.y); - } - else - { - if (bounding.min.y > sectorBounding.max.y) - { - fDistYSqr += sqr(sectorBounding.max.y - bounding.min.y); - } - } - } - - for (int x = xMin; x < xMax; x++) - { - sectorBounding.max.x = sectorBounding.min.x + LOCALMEMORY_SECTOR_SIZE; - - //sectorDistanceSqr = Distance::AABB_AABB2DSq(bounding, sectorBounding); - - //Adding X distance sqr - { - sectorDistanceSqr = fDistYSqr; - if (bounding.max.x < sectorBounding.min.x) - { - sectorDistanceSqr += sqr(bounding.max.x - sectorBounding.min.x); - } - else - { - if (bounding.min.x > sectorBounding.max.x) - { - sectorDistanceSqr += sqr(sectorBounding.max.x - bounding.min.x); - } - } - } - - if (sectorDistanceSqr < modifiedmaxViewDistSqr) - { - *pMipFactor = min(*pMipFactor, sectorDistanceSqr * scale * scale * mipFactor); - } - - pMipFactor++; - - sectorBounding.min.x = sectorBounding.max.x; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::STextureInfo::STextureInfo() -{ - m_pTexture = NULL; - - //m_size = 0; - //m_xSize = 0; - //m_ySize = 0; - //m_numMips = 0; -} - -CLocalMemoryUsage::STextureInfo::~STextureInfo() -{ - if (m_pTexture) - { - m_pTexture->Release(); - } -} - -void CLocalMemoryUsage::STextureInfo::CheckOnAllSectorsP2() -{ - int x, y, nMip, nStreamableMipNr, memoryUsage, xOldMemoryUsage, xOldPieces; - bool nonZero; - ITexture* pTexture; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - bool wasDirty = false; - for (y = 0; y < actProcessedSectors.h; y++) - { - int* pMemoryUsage = m_arrMemoryUsage; - int* pPieces = m_arrPieces; - if (m_arrRowDirty[y] || (wasDirty)) - { - SSector* sector = &m_pLocalMemoryUsage->m_arrSectors[(y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_NR_X + actProcessedSectors.x]; - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - xOldMemoryUsage = 0; - xOldPieces = 0; - for (x = 0; x < actProcessedSectors.w; x++) - { - nonZero = (*pMipFactor != BIG_NUMBER); - if (nonZero) // One more row - { - pTexture = m_pTexture; - if (!nonZero) - { - memoryUsage = 0; - nStreamableMipNr = 0; - } - else - { - nMip = max(0, pTexture->StreamCalculateMipsSigned(*pMipFactor)); - memoryUsage = pTexture->GetStreamableMemoryUsage(nMip); - nStreamableMipNr = pTexture->GetStreamableMipNumber() - nMip; - } - - sector->m_memoryUsage_Textures += memoryUsage; - - xOldMemoryUsage = memoryUsage; - *pMemoryUsage = memoryUsage; - xOldPieces = nStreamableMipNr; - *pPieces = nStreamableMipNr; - } - else - { - xOldMemoryUsage = 0; - *pMemoryUsage = 0; - xOldPieces = 0; - *pPieces = 0; - } - sector++; - pMipFactor++; - pMemoryUsage++; - pPieces++; - } - wasDirty = m_arrRowDirty[y]; - } - else - { - for (x = 0; x < actProcessedSectors.w; x++) - { - *pMemoryUsage = 0; - pMemoryUsage++; - *pPieces = 0; - pPieces++; - } - wasDirty = false; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SMaterialInfo::SMaterialInfo() -{ -} - -void CLocalMemoryUsage::SMaterialInfo::AddTextureInfo(STextureInfoAndTilingFactor textureInfo) -{ - m_textures.push_back(textureInfo); -} - -void CLocalMemoryUsage::SMaterialInfo::CheckOnAllSectorsP2() -{ - int x, y; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - for (y = 0; y < actProcessedSectors.h; y++) - { - if (m_arrRowDirty[y]) - { - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - for (x = 0; x < actProcessedSectors.w; x++) - { - if (*pMipFactor != BIG_NUMBER) - { - //(Spidy) Send the material MinDistance values to textures - for (TTextureVector::iterator it = m_textures.begin(); it != m_textures.end(); ++it) - { - STextureInfoAndTilingFactor& textureInfo = *it; - textureInfo.m_pTextureInfo->m_arrRowDirty[y] = true; - - float& textureMipFactor = textureInfo.m_pTextureInfo->m_arrMipFactor[actProcessedSectors.w * y + x]; - textureMipFactor = min(textureMipFactor, *pMipFactor * textureInfo.m_tilingFactor); - } - } - pMipFactor++; - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SStatObjInfo::SStatObjInfo() -{ - m_streamableContentMemoryUsage = 0; - - m_bSubObject = false; - /* - m_lodNr = 0; - m_vertices = 0; - m_indices = 0; - m_meshSize = 0; - m_physProxySize = 0; - m_physPrimitives = 0; - for( int i=0; i < MAX_LODS; i++) - { - m_indicesPerLod[i]=0; - } - */ -} - -void CLocalMemoryUsage::SStatObjInfo::CheckOnAllSectorsP2() -{ - int x, y, memoryUsage, pieces, xOldMemoryUsage, xOldPieces; - bool nonZero; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - bool wasDirty = false; - for (y = 0; y < actProcessedSectors.h; y++) - { - int* pMemoryUsage = m_arrMemoryUsage; - int* pPieces = m_arrPieces; - if (m_arrRowDirty[y]) - { - SSector* sector = &m_pLocalMemoryUsage->m_arrSectors[(y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_NR_X + actProcessedSectors.x]; - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - xOldMemoryUsage = 0; - xOldPieces = 0; - for (x = 0; x < actProcessedSectors.w; x++) - { - nonZero = (*pMipFactor != BIG_NUMBER); - if (nonZero) // One more row - { - /* - memoryUsage = 0; - float minDistance = sqrt_tpl(minDistanceSqr); - CStatObj* pStatObj = (CStatObj*)(m_pStatObj.get()); //(Spidy) Huh... - - //Iterate on all subobjects, like CStatObj::UpdateStreamableComponents - float fSubObjectScale = 1.0f; - //float fSubObjectScale = matSubObject.GetColumn0().GetLength(); //TODO - int lod = pStatObj->GetLodFromScale(1.0f, fSubObjectScale, minDistance, false); - //(Spidy) az objMatrix scale es a fLodRatioNorm mar bele vannak szamolva a minDistance-ba! - memoryUsage = m_streamableContentMemoryUsage; - */ - memoryUsage = m_streamableContentMemoryUsage; - pieces = 1; - - if (!nonZero) - { - memoryUsage = 0; - pieces = 0; - } - - sector->m_memoryUsage_Geometry += memoryUsage; - - xOldMemoryUsage = memoryUsage; - *pMemoryUsage = memoryUsage; - xOldPieces = pieces; - *pPieces = pieces; - } - else - { - xOldMemoryUsage = 0; - *pMemoryUsage = 0; - xOldPieces = 0; - *pPieces = 0; - } - sector++; - pMipFactor++; - pMemoryUsage++; - pPieces++; - } - wasDirty = m_arrRowDirty[y]; - } - else - { - for (x = 0; x < actProcessedSectors.w; x++) - { - *pMemoryUsage = 0; - pMemoryUsage++; - *pPieces = 0; - pPieces++; - } - wasDirty = false; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SSector::SSector() -{ - StartChecking(); -} - -void CLocalMemoryUsage::SSector::StartChecking() -{ - m_memoryUsage_Textures = 0; - m_memoryUsage_Geometry = 0; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::CLocalMemoryUsage() -{ - REGISTER_CVAR(sys_LocalMemoryTextureLimit, 64, VF_NULL, "LocalMemoryUsage tool: Set the texture memory limit to check streaming (Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryGeometryLimit, 32, VF_NULL, "LocalMemoryUsage tool: Set the statobj geometry memory limit to check streaming (Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryTextureStreamingSpeedLimit, 10, VF_NULL, "LocalMemoryUsage tool: Texture streaming speed limit (approx, Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryGeometryStreamingSpeedLimit, 10, VF_NULL, "LocalMemoryUsage tool: Stat object geometry streaming speed limit (approx, Mb/sec)"); - - REGISTER_CVAR(sys_LocalMemoryWarningRatio, 0.8f, VF_NULL, "LocalMemoryUsage tool: Warning ratio for streaming"); - REGISTER_CVAR(sys_LocalMemoryOuterViewDistance, 500.f, VF_NULL, "LocalMemoryUsage tool: View distance for debug draw"); - REGISTER_CVAR(sys_LocalMemoryInnerViewDistance, 100.f, VF_NULL, "LocalMemoryUsage tool: View distance for detailed debug draw"); - - REGISTER_CVAR(sys_LocalMemoryStreamingSpeedObjectLength, 10.f, VF_NULL, "LocalMemoryUsage tool: Length of the streaming speed debug object"); - REGISTER_CVAR(sys_LocalMemoryStreamingSpeedObjectWidth, 1.5f, VF_NULL, "LocalMemoryUsage tool: Width of the streaming speed debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectWidth, 6.f, VF_NULL, "LocalMemoryUsage tool: Width of the streaming buffer debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectHeight, 2.f, VF_NULL, "LocalMemoryUsage tool: Height of the streaming buffer debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectAlpha, 128, VF_NULL, "LocalMemoryUsage tool: Color alpha of the debug objects"); - - REGISTER_CVAR(sys_LocalMemoryDiagramWidth, 0.5f, VF_NULL, "LocalMemoryUsage tool: Width of the diagrams OBSOLATE"); - - REGISTER_CVAR(sys_LocalMemoryDiagramRadius, 2.5f, VF_NULL, "LocalMemoryUsage tool: Radius of the diagram"); - REGISTER_CVAR(sys_LocalMemoryDiagramDistance, -5.5f, VF_NULL, "LocalMemoryUsage tool: Distance of the diagram from the main debug object"); - REGISTER_CVAR(sys_LocalMemoryDiagramStreamingSpeedRadius, 1.0f, VF_NULL, "LocalMemoryUsage tool: Radius of the streaming speed diagram"); - REGISTER_CVAR(sys_LocalMemoryDiagramStreamingSpeedDistance, 2.2f, VF_NULL, "LocalMemoryUsage tool: Distance of the streaming speed diagram from the streaming speed debug line"); - REGISTER_CVAR(sys_LocalMemoryDiagramAlpha, 255, VF_NULL, "LocalMemoryUsage tool: Color alpha of the diagrams"); - - REGISTER_CVAR(sys_LocalMemoryDrawText, 0, VF_NULL, "LocalMemoryUsage tool: If != 0, it will draw the numeric values"); - REGISTER_CVAR(sys_LocalMemoryLogText, 0, VF_NULL, "LocalMemoryUsage tool: If != 0, it will log the numeric values"); - - REGISTER_CVAR(sys_LocalMemoryOptimalMSecPerSec, 100, VF_NULL, "LocalMemoryUsage tool: Optimal calculation time (MSec) per secundum"); - REGISTER_CVAR(sys_LocalMemoryMaxMSecBetweenCalls, 1000, VF_NULL, "LocalMemoryUsage tool: Maximal time difference (MSec) between calls"); - - m_pStreamCgfPredicitionDistance = 0; - m_pDebugDraw = 0; - if (gEnv->pConsole) - { - m_pStreamCgfPredicitionDistance = gEnv->pConsole->GetCVar("e_StreamCgfPredicitionDistance"); - m_pDebugDraw = gEnv->pConsole->GetCVar("e_DebugDraw"); - } - - m_sectorNr.zero(); - - m_actProcessedSectors = RectI(0, 0, 0, 0); - m_actDrawedSectors = RectI(0, 0, 0, 0); - - m_AverageUpdateTime = 0.01f; - - m_sectorNr.x = LOCALMEMORY_SECTOR_NR_X; //TODO Check size of the world - m_sectorNr.y = LOCALMEMORY_SECTOR_NR_Y; -} - -CLocalMemoryUsage::~CLocalMemoryUsage() -{ - DeleteGlobalData(); -} - -void CLocalMemoryUsage::DeleteGlobalData() -{ - m_globalTextures.clear(); - m_globalMaterials.clear(); - m_globalStatObjs.clear(); -} - -void CLocalMemoryUsage::OnRender(IRenderer* pRenderer, const CCamera* camera) -{ - if (!m_pDebugDraw || (m_pDebugDraw->GetIVal() != 17)) - { - return; - } - - const Matrix34& mat = camera->GetMatrix(); - Vec3 pos; - Vec3 projectedPos; - SSector* sector; - - SAuxGeomRenderFlags auxGeomRenderFlagsClose(e_Mode3D | e_AlphaBlended | e_DrawInFrontOn | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOff); - SAuxGeomRenderFlags auxGeomRenderFlagsFar(e_Mode3D | e_AlphaBlended | e_DrawInFrontOff | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); - - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - Vec3 cameraPos = mat.GetTranslation(); - - int xMin = max(0, int((cameraPos.x - sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE)); - int xMax = min(LOCALMEMORY_SECTOR_PER_PASS - 1, int((cameraPos.x + sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE + 1)); - int yMin = max(0, int((cameraPos.y - sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE)); - int yMax = min(LOCALMEMORY_SECTOR_PER_PASS - 1, int((cameraPos.y + sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE + 1)); - m_actDrawedSectors.x = xMin; - m_actDrawedSectors.y = yMin; - m_actDrawedSectors.w = xMax - xMin + 1; - m_actDrawedSectors.h = yMax - yMin + 1; - - CTimeValue actTime = gEnv->pTimer->GetAsyncTime(); - float timeSin = sin_tpl(actTime.GetSeconds() * 10.0f) * 0.5f + 0.5f; - - ColorB color; - ColorB colorOK(LOCALMEMORY_COLOR_OK, sys_LocalMemoryObjectAlpha); - ColorB colorWarning(LOCALMEMORY_COLOR_WARNING, sys_LocalMemoryObjectAlpha); - ColorB colorError(LOCALMEMORY_COLOR_ERROR, uint8(sys_LocalMemoryObjectAlpha * timeSin)); - ColorB colorTexture(LOCALMEMORY_COLOR_TEXTURE, sys_LocalMemoryDiagramAlpha); - ColorB colorGeometry(LOCALMEMORY_COLOR_GEOMETRY, sys_LocalMemoryDiagramAlpha); - ColorB colorBlack(LOCALMEMORY_COLOR_BLACK); - f32 fColorOK[4] = {LOCALMEMORY_FCOLOR_OK, 1}; - f32 fColorWarning[4] = {LOCALMEMORY_FCOLOR_WARNING, 1}; - f32 fColorError[4] = {LOCALMEMORY_FCOLOR_ERROR, 1}; - f32 fColorOther[4] = {LOCALMEMORY_FCOLOR_OTHER, 1}; - - f32* pColor; - Vec3 v0, v1, v2, v3, v4, vTextureDiagram, vTextureDiagram2, vGeometryDiagram, vGeometryDiagram2; - - float localMemoryTextureLimit = sys_LocalMemoryTextureLimit * 1024.f * 1024.f; - float localMemoryGeometryLimit = sys_LocalMemoryGeometryLimit * 1024.f * 1024.f; - - //The assumption is that this is called on Main Thread, otherwise the loop - //Should be wrapped inside a EnumerateHandlers lambda. - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - const float defaultTerrainHeight = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight(); - - for (int y = yMin; y < yMax; y++) - { - sector = &m_arrSectors[xMin + y * LOCALMEMORY_SECTOR_NR_X]; - for (int x = xMin; x < xMax; x++) - { - pos.x = (x + 0.5f) * LOCALMEMORY_SECTOR_SIZE; - pos.y = (y + 0.5f) * LOCALMEMORY_SECTOR_SIZE; - pos.z = terrain ? terrain->GetHeightFromFloats(pos.x, pos.y) : defaultTerrainHeight; - - if (m_pDebugDraw->GetIVal() == 17) - { - float textureRatio = sector->m_memoryUsage_Textures / localMemoryTextureLimit; - float geometryRatio = sector->m_memoryUsage_Geometry / localMemoryGeometryLimit; - float maxRatio = max(textureRatio, geometryRatio); - - v0 = pos; - v1 = pos + Vec3(-sys_LocalMemoryObjectWidth, -sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v2 = pos + Vec3(sys_LocalMemoryObjectWidth, -sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v3 = pos + Vec3(sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v4 = pos + Vec3(-sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - - if (camera->Project(v1, projectedPos) || camera->Project(v2, projectedPos) || camera->Project(v3, projectedPos) || camera->Project(v4, projectedPos)) - { - vTextureDiagram = pos + Vec3(0.f, sys_LocalMemoryObjectWidth + sys_LocalMemoryDiagramDistance + sys_LocalMemoryDiagramRadius, sys_LocalMemoryObjectHeight); - vGeometryDiagram = pos + Vec3(0.f, -sys_LocalMemoryObjectWidth - sys_LocalMemoryDiagramDistance - sys_LocalMemoryDiagramRadius, sys_LocalMemoryObjectHeight); - - if (maxRatio < sys_LocalMemoryWarningRatio) - { - color = colorOK; - pColor = fColorOK; - } - else if (maxRatio < 1.0f) - { - color = colorWarning; - pColor = fColorWarning; - } - else - { - color = colorError; - pColor = fColorError; - } - - bool close = (Distance::Point_Point2D(cameraPos, pos) < sys_LocalMemoryInnerViewDistance); - if (close) - { - pRenderAuxGeom->SetRenderFlags(auxGeomRenderFlagsClose); - - static int xDebug = 14; - static int yDebug = 19; - - if (sys_LocalMemoryDrawText) - { - camera->Project(pos, projectedPos); - - pRenderer->Draw2dLabel(projectedPos.x, projectedPos.y, 1.2f, pColor, true, "Text: %.2fMb Geom: %.2fMb", sector->m_memoryUsage_Textures / (1024.f * 1024.f), sector->m_memoryUsage_Geometry / (1024.f * 1024.f)); - /* For sector debugging - pRenderer->Draw2dLabel(projectedPos.x, projectedPos.y, 1.2f, pColor, true, "Text: %.1fMb Geom: %.1fMb - %d : %d", sector->m_memoryUsage_Textures/(1024.f*1024.f), sector->m_memoryUsage_Geometry/(1024.f*1024.f), x, y); - - if( xDebug == x && yDebug == y ) - { - float sx = projectedPos.x-80; - float sy = projectedPos.y; - - for( TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it ) - { - SStatObjInfo *statObjInfo = &it->second; - IStatObj* pStatObj = statObjInfo->m_pStatObj; - - int memoryUsage = 0; - float mipFactor = statObjInfo->m_arrMipFactor[y * m_actProcessedSectors.w + x]; - if( mipFactor != BIG_NUMBER ) - { - memoryUsage = statObjInfo->m_streamableContentMemoryUsage; - } - sy+=15.f; - pRenderer->Draw2dLabel(sx, sy, 1.2f, pColor, false, "Geom: %.2fMb %.4f Act:%s Orig:%s %s", memoryUsage/(1024.f*1024.f), mipFactor, pStatObj->GetFilePath(), statObjInfo->m_filePath, statObjInfo->m_bSubObject ? " SUBOBJECT" : ""); - //pRenderer->Draw2dLabel(sx, sy, 1.2f, pColor, false, "Geom: %.2fMb %.4f", memoryUsage/(1024.f*1024.f), mipFactor); - } - } - //*/ - } - if (sys_LocalMemoryLogText) - { - if (xDebug == x && yDebug == y) - { - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - STextureInfo* textureObjInfo = &it->second; - ITexture* pTexture = textureObjInfo->m_pTexture; - - float mipFactor = textureObjInfo->m_arrMipFactor[y * m_actProcessedSectors.w + x]; - if (mipFactor != BIG_NUMBER) - { - CryLog("Texture: %s %dX%d mipfactor:%.4f", pTexture->GetName(), pTexture->GetWidth(), pTexture->GetHeight(), mipFactor); - } - } - sys_LocalMemoryLogText = false; //Log only once! - } - } - } - else - { - pRenderAuxGeom->SetRenderFlags(auxGeomRenderFlagsFar); - } - - pRenderAuxGeom->DrawTriangle(v1, color, v2, color, v3, color); - pRenderAuxGeom->DrawTriangle(v3, color, v4, color, v1, color); - - pRenderAuxGeom->DrawTriangle(v0, color, v1, color, v4, color); - pRenderAuxGeom->DrawTriangle(v0, color, v2, color, v1, color); - pRenderAuxGeom->DrawTriangle(v0, color, v3, color, v2, color); - pRenderAuxGeom->DrawTriangle(v0, color, v4, color, v3, color); - - if (close) - { - LocalMemoryUsageDrawHelper::DrawCircle(pRenderer, camera, vTextureDiagram, sys_LocalMemoryDiagramRadius, textureRatio, colorTexture, colorBlack); - LocalMemoryUsageDrawHelper::DrawCircle(pRenderer, camera, vGeometryDiagram, sys_LocalMemoryDiagramRadius, geometryRatio, colorGeometry, colorBlack); - } - } - } - - sector++; - } - } -} - -void CLocalMemoryUsage::OnUpdate() -{ - if (!m_pDebugDraw || (m_pDebugDraw->GetIVal() != 17)) - { - return; - } - - //CryLogAlways("OnUpdate start-----------------------------------------"); - CTimeValue actTime = gEnv->pTimer->GetAsyncTime(); - - float callTimeDiff = (actTime - m_LastCallTime).GetSeconds(); - float neededCallTimeDiff = m_AverageUpdateTime / (sys_LocalMemoryOptimalMSecPerSec / 1000.f); - - if (callTimeDiff < neededCallTimeDiff && callTimeDiff < sys_LocalMemoryMaxMSecBetweenCalls / 1000.f) - { - return; - } - - DeleteUnusedResources(); - - m_LastCallTime = actTime; - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Start", GetISystem(), PROFILE_SYSTEM); - //StartChecking(RectI(0,0,m_sectorNr.x, m_sectorNr.y)); - StartChecking(m_actDrawedSectors); - } - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - CollectGeometry P1", GetISystem(), PROFILE_SYSTEM); - CollectGeometryP1(); - } - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Materials P2", GetISystem(), PROFILE_SYSTEM); - //We must iterate on materials first - for (TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Textures P2", GetISystem(), PROFILE_SYSTEM); - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - { - FRAME_PROFILER("! LocalMemoryUsege::Update - StatObjects P2", GetISystem(), PROFILE_SYSTEM); - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - - CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - m_AverageUpdateTime = LERP(m_AverageUpdateTime, (endTime - actTime).GetSeconds(), 0.5f); - - //CryLogAlways("OnUpdate end***"); -} - -void CLocalMemoryUsage::DeleteUnusedResources() -{ - FRAME_PROFILER("! LocalMemoryUsege::Update - Deleting unused resources", GetISystem(), PROFILE_SYSTEM); - - // Clear the used flags - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - it->second.m_used = false; - } - - // Iterate on used StatObjs - int nCount; - gEnv->p3DEngine->GetLoadedStatObjArray(NULL, nCount); - std::vector objectsArray; - objectsArray.resize(nCount); - if (nCount > 0) - { - gEnv->p3DEngine->GetLoadedStatObjArray(&objectsArray[0], nCount); - } - - for (std::vector::iterator it = objectsArray.begin(); it != objectsArray.end(); ++it) - { - IStatObj* pStatObj = *it; - TStatObjMap::iterator findIt = m_globalStatObjs.find((INT_PTR)pStatObj); - - if (findIt != m_globalStatObjs.end() && strcmp(pStatObj->GetFilePath(), findIt->second.m_filePath) == 0 && !findIt->second.m_bSubObject) - { - findIt->second.m_used = true; - } - - if (pStatObj->GetFlags() & STATIC_OBJECT_COMPOUND) - { - for (int k = 0; k < pStatObj->GetSubObjectCount(); k++) - { - if (!pStatObj->GetSubObject(k)) - { - continue; - } - - IStatObj* pSubStatObj = pStatObj->GetSubObject(k)->pStatObj; - - if (pSubStatObj) - { - findIt = m_globalStatObjs.find((INT_PTR)pSubStatObj); - - if (findIt != m_globalStatObjs.end() && strcmp(pSubStatObj->GetFilePath(), findIt->second.m_filePath) == 0 && findIt->second.m_bSubObject) - { - findIt->second.m_used = true; - } - } - } - } - } - - // Erase non-used StatObjs - bool changed = true; - while (changed) - { - changed = false; - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - if (!it->second.m_used) - { - m_globalStatObjs.erase(it); - changed = true; - break; - } - } - } - /* - for( TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it ) - it->second.m_used = false; - - bool changed = true; - while( changed ) - { - changed = false; - for( TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it ) - { - if( !it->second.m_used ) - { - m_globalTextures.erase(it); - changed = true; - break; - } - } - } - - for( TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it ) - it->second.m_used = false; - - changed = true; - while( changed ) - { - changed = false; - for( TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it ) - { - if( !it->second.m_used ) - { - m_globalMaterials.erase(it); - changed = true; - break; - } - } - } - //*/ -} -void CLocalMemoryUsage::StartChecking(const RectI& actProcessedSectors) -{ - m_actProcessedSectors = actProcessedSectors; - - for (int y = 0; y < m_sectorNr.y; y++) - { - SSector* sector = &m_arrSectors[y * LOCALMEMORY_SECTOR_NR_X]; - for (int x = 0; x < m_sectorNr.x; x++) - { - sector->StartChecking(); - sector++; - } - } - - { - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - Textures", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } - { - for (TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - Materials", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } - { - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - StatObjects", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } -} - -void CLocalMemoryUsage::CollectGeometryP1() -{ - ISystem* pSystem = GetISystem(); - I3DEngine* p3DEngine = pSystem->GetI3DEngine(); - - // iterate through all instances - std::vector renderNodes; - - uint32 dwCount = 0; - - dwCount += p3DEngine->GetObjectsByType(eERType_Light); - - dwCount += p3DEngine->GetObjectsByType(eERType_RenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_SkinnedMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_DynamicMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_Decal); - - if (dwCount > 0) - { - renderNodes.resize(dwCount + 1); - dwCount = 0; - - dwCount += p3DEngine->GetObjectsByType(eERType_Light, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_RenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_DynamicMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_SkinnedMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_Decal, &renderNodes[dwCount]); - - AABB objBox; - - for (uint32 dwI = 0; dwI < dwCount; ++dwI) - { - IRenderNode* pRenderNode = renderNodes[dwI]; - - if (pRenderNode->m_fWSMaxViewDist < 0.01f) - { - continue; - } - - float objScale = 1.f; - if (pRenderNode->GetRenderNodeType() == eERType_Decal) - { - IDecalRenderNode* pDecal = (IDecalRenderNode*)pRenderNode; - objScale = max(0.001f, pDecal->GetMatrix().GetColumn0().GetLength()); - } - else if (pRenderNode->GetRenderNodeType() == eERType_FogVolume) - { - objScale = max(0.001f, ((IFogVolumeRenderNode*)pRenderNode)->GetMatrix().GetColumn0().GetLength()); - } - - float maxViewDist = pRenderNode->m_fWSMaxViewDist; - pRenderNode->FillBBox(objBox); - - _smart_ptr pRenderNodeMat = pRenderNode->GetMaterialOverride(); - - { - IStatObj* pStatObj = pRenderNode->GetEntityStatObj(); - - if (pStatObj != NULL) - { - CheckStatObjMaterialP1(pStatObj, pRenderNodeMat, objBox, maxViewDist, objScale); - } - else - { - CheckMeshMaterialP1(pRenderNode->GetRenderMesh(0), pRenderNodeMat, objBox, maxViewDist, objScale); - } - } - - for (int dwSlot = 0; dwSlot < pRenderNode->GetSlotCount(); ++dwSlot) - { - _smart_ptr pSlotMat = pRenderNode->GetEntitySlotMaterial(dwSlot); - if (!pSlotMat) - { - pSlotMat = pRenderNodeMat; - } - - Matrix34A matParent; - - if (IStatObj* pStatObj = pRenderNode->GetEntityStatObj(dwSlot, 0, &matParent, true)) - { - CheckStatObjP1(pStatObj, pRenderNode, objBox, maxViewDist, objScale); - - _smart_ptr pStatObjMat = pStatObj->GetMaterial(); - CheckStatObjMaterialP1(pStatObj, pSlotMat ? pSlotMat : pStatObjMat, objBox, maxViewDist, objScale); - } - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262); -CLocalMemoryUsage::SStatObjInfo* CLocalMemoryUsage::CheckStatObjP1(IStatObj* pStatObj, [[maybe_unused]] IRenderNode* pRenderNode, AABB bounding, float maxViewDist, float scale) -{ - if (!pStatObj) - { - return NULL; - } - - if (strncmp(pStatObj->GetFilePath(), "%level%", 7) == 0) //HACK %LEVEL% brushes - { - return NULL; - } - - SStatObjInfo* pStatObjInfo = NULL; - - TStatObjMap::iterator iter = m_globalStatObjs.find((INT_PTR)pStatObj); - if (iter != m_globalStatObjs.end()) - { - pStatObjInfo = &iter->second; - pStatObjInfo->m_streamableContentMemoryUsage = pStatObj->GetStreamableContentMemoryUsage(); //TODO TEMP - } - else - { - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckStatObjP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pStatObjInfo = &m_globalStatObjs[(INT_PTR)pStatObj]; - } - - pStatObjInfo->Init(this); - pStatObjInfo->m_streamableContentMemoryUsage = pStatObj->GetStreamableContentMemoryUsage(); - //pStatObjInfo->m_pStatObj = pStatObj; - pStatObjInfo->m_filePath = pStatObj->GetFilePath(); - pStatObjInfo->m_bSubObject = pStatObj->IsSubObject(); - //CollectStatObjInfo_Recursive( pStatObjInfo, pStatObj ); - } - - pStatObjInfo->CheckOnAllSectorsP1(bounding, maxViewDist, scale, 1.0f); - - return pStatObjInfo; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, float mipFactor) -{ - if (pMaterial) - { - SMaterialInfo* pMaterialInfo = NULL; - - TMaterialMap::iterator iter = m_globalMaterials.find((INT_PTR)pMaterial.get()); - if (iter != m_globalMaterials.end()) - { - pMaterialInfo = &iter->second; - } - else - { - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckMaterialP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pMaterialInfo = &m_globalMaterials[(INT_PTR)pMaterial.get()]; - } - pMaterialInfo->Init(this); - //pMaterialInfo->m_pMaterial=pMaterial; - CollectMaterialInfo_Recursive(pMaterialInfo, pMaterial); - } - - pMaterialInfo->CheckOnAllSectorsP1(bounding, maxViewDist, scale, mipFactor); - } -} - -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckChunkMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, CRenderChunk* pRenderChunk) -{ - _smart_ptr pCurrentMaterial = pMaterial; - - if (pRenderChunk != NULL) - { - if (pRenderChunk->m_nMatID < pMaterial->GetSubMtlCount()) - { - pCurrentMaterial = pMaterial->GetSubMtl(pRenderChunk->m_nMatID); - } - - if (pCurrentMaterial != NULL) - { - CheckMaterialP1(pCurrentMaterial, bounding, maxViewDist, scale, pRenderChunk->m_texelAreaDensity); - } - } - else - { - CheckMaterialP1(pCurrentMaterial, bounding, maxViewDist, scale, 1.f); - } -} - -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckMeshMaterialP1(IRenderMesh* pRenderMesh, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale) -{ - if (pRenderMesh) - { - if (pMaterial) - { - TRenderChunkArray* pChunks = &pRenderMesh->GetChunks(); - - if (pChunks != NULL) - { - for (unsigned int i = 0; i < pChunks->size(); i++) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, &(*pChunks)[i]); - } - } - - pChunks = &pRenderMesh->GetChunksSkinned(); - for (unsigned int i = 0; i < pChunks->size(); i++) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, &(*pChunks)[i]); - } - } - } - else - { - if (pMaterial) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, NULL); - } - } -} - -void CLocalMemoryUsage::CheckStatObjMaterialP1(IStatObj* pStatObj, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale) -{ - if (pStatObj) - { - for (int i = 0; i < pStatObj->GetSubObjectCount(); i++) - { - CheckStatObjMaterialP1(pStatObj->GetSubObject(i)->pStatObj, pMaterial, bounding, scale, maxViewDist); - } - - CheckMeshMaterialP1(pStatObj->GetRenderMesh(), pMaterial, bounding, maxViewDist, scale); - } -} - -void CLocalMemoryUsage::CollectMaterialInfo_Recursive(SMaterialInfo* materialInfo, _smart_ptr pMaterial) -{ - SShaderItem& rItem = pMaterial->GetShaderItem(); - - uint32 dwSubMatCount = pMaterial->GetSubMtlCount(); - - for (uint32 dwSubMat = 0; dwSubMat < dwSubMatCount; ++dwSubMat) - { - _smart_ptr pSub = pMaterial->GetSubMtl(dwSubMat); - - if (pSub) - { - CollectMaterialInfo_Recursive(materialInfo, pSub); - } - } - - // this pMaterial - if (rItem.m_pShaderResources) - { - for (auto iter = rItem.m_pShaderResources->GetTexturesResourceMap()->begin(); - iter != rItem.m_pShaderResources->GetTexturesResourceMap()->end(); ++iter) - { - const SEfResTexture* pTextureRes = &iter->second; - - if (pTextureRes->m_Sampler.m_pITex) - { - ITexture* pTexture = pTextureRes->m_Sampler.m_pITex; - if (pTexture && pTexture->GetStreamableMipNumber() > 0) - { - STextureInfoAndTilingFactor textureInfo; - - textureInfo.m_pTextureInfo = GetTextureInfo(pTexture); - textureInfo.m_tilingFactor = pTextureRes->GetTiling(0) * pTextureRes->GetTiling(1); - - materialInfo->AddTextureInfo(textureInfo); - } - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262) -CLocalMemoryUsage::STextureInfo * CLocalMemoryUsage::GetTextureInfo(ITexture * pTexture) -{ - if (!pTexture) - { - return NULL; - } - - TTextureMap::iterator iter = m_globalTextures.find((INT_PTR)pTexture); - if (iter != m_globalTextures.end()) - { - return &iter->second; - } - - //FUNCTION_PROFILER(GetISystem(), PROFILE_SYSTEM); - STextureInfo* pTextureInfo; - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckStatObjP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pTextureInfo = &m_globalTextures[(INT_PTR)pTexture]; - } - pTextureInfo->Init(this); - pTextureInfo->m_pTexture = pTexture; - pTexture->AddRef(); - - //Collect informations - //pTextureInfo->m_size = pTexture->GetDeviceDataSize(); - //pTextureInfo->m_xSize = pTexture->GetWidth(); - //pTextureInfo->m_ySize = pTexture->GetHeight(); - //pTextureInfo->m_numMips = pTexture->GetNumMips(); - - return pTextureInfo; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h b/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h deleted file mode 100644 index 450e2eb2f9..0000000000 --- a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual helper for checking a local memory usage on maps - - -#ifndef CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H -#define CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H -#pragma once - - -#include "../CryCommon/Cry_Geo.h" -#include "ILocalMemoryUsage.h" -#include "TimeValue.h" - -#define LOCALMEMORY_SECTOR_SIZE 32.f //Size of one sector -#define LOCALMEMORY_SECTOR_NR_X 128 //4096 / LOCALMEMORY_SECTOR_SIZE Sector number of the world (x) -#define LOCALMEMORY_SECTOR_NR_Y 128 //4096 / LOCALMEMORY_SECTOR_SIZE Sector number of the world (y) -#define LOCALMEMORY_SECTOR_PER_PASS 128 //4096 / 32 Sector nr for one calculation pass. Now it is the whole world; - -//Sector number must be = LOCALMEMORY_SECTOR_PER_PASS * n - -#define LOCALMEMORY_COLOR_OK 0, 255, 0 -#define LOCALMEMORY_COLOR_WARNING 255, 255, 0 -#define LOCALMEMORY_COLOR_ERROR 255, 0, 0 -#define LOCALMEMORY_COLOR_TEXTURE 0, 0, 255 -#define LOCALMEMORY_COLOR_GEOMETRY 0, 0, 0 -#define LOCALMEMORY_COLOR_BLACK 0, 0, 0, 192 -#define LOCALMEMORY_FCOLOR_OK 0, 1, 0 -#define LOCALMEMORY_FCOLOR_WARNING 1, 1, 0 -#define LOCALMEMORY_FCOLOR_ERROR 1, 0, 0 -#define LOCALMEMORY_FCOLOR_OTHER 0, 0, 1 - -struct IMaterial; -struct IStatObj; -struct IRenderMesh; -struct IRenderNode; -struct CRenderChunk; -class CCamera; - -#include - -struct CLocalMemoryUsage - : public ILocalMemoryUsage -{ -private: - - struct STextureInfo; - struct SMaterialInfo; - struct SStatObjInfo; - - typedef std__hash_map TTextureMap; // Type: hash map of textures - typedef std__hash_map TMaterialMap; // Type: hash map of materials - typedef std__hash_map TStatObjMap; // Type: hash map of stat objects - - //******************* - - struct SResource - { - CLocalMemoryUsage* m_pLocalMemoryUsage; // Inner pointer to the singleton (we can use gEnv->pLocalMemoryUsage with type cast instead this) - - float m_arrMipFactor[LOCALMEMORY_SECTOR_PER_PASS * LOCALMEMORY_SECTOR_PER_PASS]; // Mipmap factor based on minimum distance of the resource from the sector (bounding box distance) - bool m_arrRowDirty[LOCALMEMORY_SECTOR_PER_PASS]; // Dirty flag for m_arrMipFactor rows - bool m_used; - - static int m_arrMemoryUsage[LOCALMEMORY_SECTOR_PER_PASS]; // Memory usage of the resource in sectors (last row) - static int m_arrPieces[LOCALMEMORY_SECTOR_PER_PASS]; // Pieces nr of the resource in sectors (last row) - - virtual void StartChecking(); // Called every frame first - void CheckOnAllSectorsP1(const AABB& bounding, float maxViewDist, float viewDistMultiplierForLOD, float mipFactor); // Calculates the minimum of sector bounding vs renderobject bounding distances - - SResource(); - virtual void Init(CLocalMemoryUsage* pLocalMemoryUsage); - //If we will needed a destructor, it must be virtual! - }; - - //******************* - - struct STextureInfo - : public SResource - { - ITexture* m_pTexture; // Texture pointer - //int m_size; // For later use - Used memory - //int m_xSize; // For later use - Texture x size - //int m_ySize; // For later use - Texture y size - //int m_numMips; // For later use - Number of mip maps - - void CheckOnAllSectorsP2(); // Calculate memory usage using distances - - STextureInfo(); - ~STextureInfo(); - }; - - //******************* - - struct STextureInfoAndTilingFactor - { - STextureInfo* m_pTextureInfo; - float m_tilingFactor; - }; - - typedef std::vector TTextureVector; // Type: vector of textures - - struct SMaterialInfo - : public SResource - { - //_smart_ptr m_pMaterial; // For later use - TTextureVector m_textures; // Used textures - - SMaterialInfo(); - - void AddTextureInfo(STextureInfoAndTilingFactor texture);// Add a new texture (unique) - void CheckOnAllSectorsP2(); // Forward distance informations to textures - }; - - //******************* - - struct SStatObjInfo - : public SResource - { - int m_streamableContentMemoryUsage; // Total streamable memory usage - //IStatObj *m_pStatObj; //TODO kiszedni - string m_filePath; // The original file name and path of the StatObj - bool m_bSubObject; // Is the original StatObj a subobject? - /* - int m_lodNr; // For later use - int m_vertices; - int m_meshSize; - int m_physProxySize; - int m_physPrimitives; - int m_indices; - int m_indicesPerLod[MAX_LODS]; - */ - - SStatObjInfo(); - void CheckOnAllSectorsP2(); // Calculate memory usage using distances - }; - - //******************* - - struct SSector - { - SSector(); - - void StartChecking(); // Called every frame first - - int m_memoryUsage_Textures; // Sum of texture memory usage - - int m_memoryUsage_Geometry; // Sum of geometry memory usage - }; - - //******************* - PREFAST_SUPPRESS_WARNING(6262); - TTextureMap m_globalTextures; // Hash map of resources: textures - PREFAST_SUPPRESS_WARNING(6262); - TMaterialMap m_globalMaterials; // Hash map of resources: materials - PREFAST_SUPPRESS_WARNING(6262); - TStatObjMap m_globalStatObjs; // Hash map of resources: stat objects - - ICVar* m_pStreamCgfPredicitionDistance; // Config: additional object distance for streaming - ICVar* m_pDebugDraw; // Config: debug draw mode - - int sys_LocalMemoryTextureLimit; // Config: texture limit for streaming - int sys_LocalMemoryGeometryLimit; // Config: stat object geometry limit for streaming - int sys_LocalMemoryTextureStreamingSpeedLimit; // Config: texture streaming speed limit (approx) - int sys_LocalMemoryGeometryStreamingSpeedLimit; // Config: stat object geometry streaming speed limit (approx) - - float sys_LocalMemoryWarningRatio; // Config: Warning ratio for streaming - float sys_LocalMemoryOuterViewDistance; // Config: View distance for debug draw - float sys_LocalMemoryInnerViewDistance; // Config: View distance for detailed debug draw - - float sys_LocalMemoryObjectWidth; // Config: Width of the debug object - float sys_LocalMemoryObjectHeight; // Config: Height of the debug object - int sys_LocalMemoryObjectAlpha; // Config: Color alpha of the debug object - - float sys_LocalMemoryStreamingSpeedObjectLength; // Config: Length of the streaming speed debug object - float sys_LocalMemoryStreamingSpeedObjectWidth; // Config: Width of the streaming speed debug object - - float sys_LocalMemoryDiagramWidth; // Config: Width of the diagram - - float sys_LocalMemoryDiagramRadius; // Config: Radius of the diagram - float sys_LocalMemoryDiagramDistance; // Config: Distance of the diagram from the main debug object - float sys_LocalMemoryDiagramStreamingSpeedRadius; // Config: Radius of the streaming speed diagram - float sys_LocalMemoryDiagramStreamingSpeedDistance; // Config: Distance of the streaming speed diagram from the streaming speed debug line - int sys_LocalMemoryDiagramAlpha; // Config: Color alpha of the diagram - - int sys_LocalMemoryDrawText; // Config: If != 0, it will draw the numeric values - int sys_LocalMemoryLogText; // Config: If != 0, it will log the numeric values - - int sys_LocalMemoryOptimalMSecPerSec; // Config: Optimal calculation time (MSec) per secundum - int sys_LocalMemoryMaxMSecBetweenCalls; // Config: Maximal time difference (MSec) between calls - - RectI m_actProcessedSectors; // Processed sectors (now it is the whole world) - RectI m_actDrawedSectors; // Processed sectors (now it is the whole world) - - Vec2i m_sectorNr; // Sector x and y number - - float m_AverageUpdateTime; // Avarage Update() time (MSec) - CTimeValue m_LastCallTime; // Last call time of Update() - - SSector m_arrSectors[LOCALMEMORY_SECTOR_NR_X * LOCALMEMORY_SECTOR_NR_Y]; // Sectors - -public: - - CLocalMemoryUsage(); - ~CLocalMemoryUsage(); - - virtual void OnRender(IRenderer* pRenderer, const CCamera* camera); - virtual void OnUpdate(); - virtual void DeleteGlobalData(); // Deletes the m_globalXXX hash maps - -private: - void DeleteUnusedResources(); // Delete the non-used resources (especially StatObjs) - void StartChecking(const RectI& actProcessedSectors); // Called every frame first - void CollectGeometryP1(); // Calculates the minimum of sector bounding vs renderobject bounding distances - - // Get / create StatObjInfo then run Pass1 - SStatObjInfo* CheckStatObjP1(IStatObj* pStatObj, IRenderNode* pRenderNode, AABB bounding, float maxViewDist, float scale); - //void CollectStatObjInfo_Recursive( SStatObjInfo* statObjInfo, IStatObj *pStatObj ); - //void CollectGeometryInfo( SStatObjInfo* statObjInfo, IStatObj *pStatObj ); - - // Get / create MaterialInfo then run Pass1 - void CheckMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, float mipFactor); - void CheckChunkMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, CRenderChunk* pRenderChunk); - void CheckMeshMaterialP1(IRenderMesh* pRenderMesh, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale); - void CheckStatObjMaterialP1(IStatObj* pStatObj, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale); - // Collects textures used by the material - void CollectMaterialInfo_Recursive(SMaterialInfo* materialInfo, _smart_ptr pMaterial); - - // Get / create TextureInfo - STextureInfo* GetTextureInfo(ITexture* pTexture); -}; - -#undef MAX_LODS -#endif // CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 827a393103..af9b674f6a 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -119,8 +119,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include AZ_RESTRICTED_FILE(System_cpp) #endif - -#include #include #include #include @@ -131,7 +129,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "VisRegTest.h" #include -#include #include @@ -154,7 +151,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "Serialization/ArchiveHost.h" #include "SystemEventDispatcher.h" #include "ServerThrottle.h" -#include "ILocalMemoryUsage.h" #include "ResourceManager.h" #include "HMDBus.h" #include "OverloadSceneManager/OverloadSceneManager.h" @@ -682,15 +678,6 @@ void CSystem::ShutDown() // Shutdown any running VR devices. EBUS_EVENT(AZ::VR::HMDInitRequestBus, Shutdown); - - ////////////////////////////////////////////////////////////////////////// - // Clear 3D Engine resources. - if (m_env.p3DEngine) - { - m_env.p3DEngine->UnloadLevel(); - } - ////////////////////////////////////////////////////////////////////////// - // Shutdown resource manager. m_pResourceManager->Shutdown(); @@ -706,7 +693,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_env.pServiceNetwork); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); - SAFE_RELEASE(m_env.p3DEngine); // depends on EntitySystem if (m_env.pConsole) { ((CXConsole*)m_env.pConsole)->FreeRenderResources(); @@ -1231,8 +1217,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } - RenderBegin(); - #ifndef EXCLUDE_UPDATE_ON_CONSOLE // do the dedicated sleep earlier than the frame profiler to avoid having it counted if (gEnv->IsDedicated()) @@ -1295,11 +1279,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) GetIRemoteConsole()->Update(); #endif - if (gEnv->pLocalMemoryUsage != NULL) - { - gEnv->pLocalMemoryUsage->OnUpdate(); - } - if (!gEnv->IsEditor() && gEnv->pRenderer) { // If the dimensions of the render target change, @@ -1490,11 +1469,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) //update time subsystem m_Time.UpdateOnFrameStart(); - if (m_env.p3DEngine) - { - m_env.p3DEngine->OnFrameStart(); - } - ////////////////////////////////////////////////////////////////////// // update rate limiter for dedicated server if (m_pServerThrottle.get()) @@ -1651,7 +1625,7 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } ////////////////////////////////////////////////////////////////////// -bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) +bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) { CTimeValue updateStart = gEnv->pTimer->GetAsyncTime(); @@ -1663,44 +1637,6 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) UpdateMovieSystem(updateFlags, fMovieFrameTime, false); } - ////////////////////////////////////////////////////////////////////// - //update process (3D engine) - if (!(updateFlags & ESYSUPDATE_EDITOR) && !m_bNoUpdate && m_env.p3DEngine) - { - FRAME_PROFILER("SysUpdate:Update3DEngine", this, PROFILE_SYSTEM); - - if (ITimeOfDay* pTOD = m_env.p3DEngine->GetTimeOfDay()) - { - pTOD->Tick(); - } - - if (m_env.p3DEngine) - { - m_env.p3DEngine->Tick(); // clear per frame temp data - } - if (m_pProcess && (m_pProcess->GetFlags() & PROC_3DENGINE)) - { - if ((nPauseMode != 1)) - { - if (!IsEquivalent(m_ViewCamera.GetPosition(), Vec3(0, 0, 0), VEC_EPSILON)) - { - if (m_env.p3DEngine) - { - // m_env.p3DEngine->SetCamera(m_ViewCamera); - m_pProcess->Update(); - } - } - } - } - else - { - if (m_pProcess) - { - m_pProcess->Update(); - } - } - } - ////////////////////////////////////////////////////////////////////// //update sound system part 2 if (!g_cvars.sys_deferAudioUpdateOptim && !m_bNoUpdate) @@ -1748,41 +1684,8 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) gEnv->pCryPak->DisableRuntimeFileAccess(true); } - // If it's in editing mode (in editor) the render is done in RenderViewport so we skip rendering here. - if (!gEnv->IsEditing() && gEnv->pRenderer && gEnv->p3DEngine) - { - if (GetIViewSystem()) - { - GetIViewSystem()->Update(min(gEnv->pTimer->GetFrameTime(), 0.1f)); - } - - // Begin occlusion job after setting the correct camera. - gEnv->p3DEngine->PrepareOcclusion(GetViewCamera()); - - CrySystemNotificationBus::Broadcast(&CrySystemNotifications::OnPreRender); - - // Also broadcast for anyone else that needs to draw global debug to do so now - AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo); - - Render(); - - gEnv->p3DEngine->EndOcclusion(); - - CrySystemNotificationBus::Broadcast(&CrySystemNotifications::OnPostRender); - - RenderEnd(); - - gEnv->p3DEngine->SyncProcessStreamingUpdate(); - - if (NeedDoWorkDuringOcclusionChecks()) - { - DoWorkDuringOcclusionChecks(); - } - - // Sync the work that must be done in the main thread by the end of frame. - gEnv->pRenderer->GetGenerateShadowRendItemJobExecutor()->WaitForCompletion(); - gEnv->pRenderer->GetGenerateRendItemJobExecutor()->WaitForCompletion(); - } + // Also broadcast for anyone else that needs to draw global debug to do so now + AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo); return !IsQuitting(); } diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index e4fcc82552..f5235f2ea8 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -408,13 +408,6 @@ public: virtual void DoWorkDuringOcclusionChecks(); virtual bool NeedDoWorkDuringOcclusionChecks() { return m_bNeedDoWorkDuringOcclusionChecks; } - //! Begin rendering frame. - void RenderBegin(); - //! Render subsystems. - void Render(); - //! End rendering frame and swap back buffer. - void RenderEnd(bool bRenderStats = true, bool bMainWindow = true); - //Called when the renderer finishes rendering the scene void OnScene3DEnd() override; @@ -429,11 +422,6 @@ public: //! Update screen and call some important tick functions during loading. void SynchronousLoadingTick(const char* pFunc, int line); - //! Renders the statistics; this is called from RenderEnd, but if the - //! Host application (Editor) doesn't employ the Render cycle in ISystem, - //! it may call this method to render the essential statistics - void RenderStatistics() override; - uint32 GetUsedMemory(); virtual void DumpMemoryUsageStatistics(bool bUseKB); @@ -469,7 +457,6 @@ public: AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; IConsole* GetIConsole() { return m_env.pConsole; }; IRemoteConsole* GetIRemoteConsole(); - I3DEngine* GetI3DEngine(){ return m_env.p3DEngine; } IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; IMemoryManager* GetIMemoryManager(){ return m_pMemoryManager; } IThreadManager* GetIThreadManager() override {return m_env.pThreadManager; } @@ -696,9 +683,6 @@ private: void CreateRendererVars(const SSystemInitParams& startupParams); void CreateSystemVars(); void CreateAudioVars(); - void RenderStats(); - void RenderOverscanBorders(); - void RenderMemStats(); AZStd::unique_ptr LoadDLL(const char* dllName); diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 826810ef8a..22445ec4a5 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -86,7 +86,6 @@ #endif //WIN32 -#include #include #include #include @@ -107,7 +106,6 @@ #include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "Statistics/LocalMemoryUsage.h" #include "ThreadConfigManager.h" #include "Validator.h" #include "ServerThrottle.h" @@ -768,11 +766,6 @@ static void LoadDetectedSpec(ICVar* pVar) GetISystem()->SetConfigSpec(static_cast(spec), platform, false); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetMaterialManager()->RefreshMaterialRuntime(); - } - no_recursive = false; } @@ -2788,12 +2781,6 @@ AZ_POP_DISABLE_WARNING m_env.pRenderer->TryFlush(); } -#if !defined(RELEASE) - m_env.pLocalMemoryUsage = new CLocalMemoryUsage(); -#else - m_env.pLocalMemoryUsage = nullptr; -#endif - if (g_cvars.sys_float_exceptions > 0) { if (g_cvars.sys_float_exceptions == 3 && gEnv->IsEditor()) // Turn off float exceptions in editor if sys_float_exceptions = 3 diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index a544cef4a5..68045a86ea 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -31,7 +31,6 @@ #include #include "Log.h" #include "XConsole.h" -#include #include #include "PhysRenderer.h" #include @@ -222,92 +221,6 @@ void CSystem::CreateRendererVars(const SSystemInitParams& startupParams) "Usage: r_OverscanBordersDrawDebugView [0=off/1=show]"); } -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderBegin() -{ - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - if (m_bIgnoreUpdates) - { - return; - } - - bool rndAvail = m_env.pRenderer != 0; - - ////////////////////////////////////////////////////////////////////// - //start the rendering pipeline - if (rndAvail) - { - m_env.pRenderer->BeginFrame(); - } - - gEnv->nMainFrameID = (rndAvail) ? m_env.pRenderer->GetFrameID(false) : 0; -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderEnd([[maybe_unused]] bool bRenderStats, bool bMainWindow) -{ - { - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - if (m_bIgnoreUpdates) - { - return; - } - - if (!m_env.pRenderer) - { - return; - } - - if (bMainWindow) // we don't do this in UI Editor window for example - { -#if !defined (_RELEASE) - // Flush render data and swap buffers. - m_env.pRenderer->RenderDebug(bRenderStats); -#endif - -#if defined(USE_PERFHUD) - if (m_pPerfHUD) - { - m_pPerfHUD->Draw(); - } - if (m_pMiniGUI) - { - m_pMiniGUI->Draw(); - } -#endif - - if (!gEnv->pSystem->GetILevelSystem() || !gEnv->pSystem->GetILevelSystem()->IsLevelLoaded()) - { - IConsole* console = GetIConsole(); - - //Same goes for the console. When no level is loaded, it's okay to render it outside of the renderer - //so that users can load maps or change settings. - if (console != nullptr) - { - console->Draw(); - } - } - } - - m_env.pRenderer->ForceGC(); // XXX Rename this - m_env.pRenderer->EndFrame(); - - - if (IConsole* pConsole = GetIConsole()) - { - // if we have pending cvar calculation, execute it here - // since we know cvars will be correct here after ->EndFrame(). - if (!pConsole->IsHashCalculated()) - { - pConsole->CalcCheatVarHash(); - } - } - } -} - void CSystem::OnScene3DEnd() { //Render Console @@ -391,231 +304,3 @@ void CSystem::DisplayErrorMessage(const char* acMessage, #endif m_ErrorMessages.push_back(message); } - -//! Renders the statistics; this is called from RenderEnd, but if the -//! Host application (Editor) doesn't employ the Render cycle in ISystem, -//! it may call this method to render the essential statistics -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderStatistics() -{ - RenderStats(); -} - -////////////////////////////////////////////////////////////////////// -void CSystem::Render() -{ - if (m_bIgnoreUpdates) - { - return; - } - - //check what is the current process - if (!m_pProcess) - { - return; //should never happen - } - //check if the game is in pause or - //in menu mode - //bool bPause=false; - //if (m_pProcess->GetFlags() & PROC_MENU) - // bPause=true; - - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - ////////////////////////////////////////////////////////////////////// - //draw - m_env.p3DEngine->PreWorldStreamUpdate(m_ViewCamera); - - if (m_pProcess) - { - if (m_pProcess->GetFlags() & PROC_3DENGINE) - { - if (!gEnv->IsEditing()) // Editor calls it's own rendering update - { - if (m_env.p3DEngine && !m_env.IsFMVPlaying()) - { - if (!IsEquivalent(m_ViewCamera.GetPosition(), Vec3(0, 0, 0), VEC_EPSILON) || // never pass undefined camera to p3DEngine->RenderWorld() - gEnv->IsDedicated() || (gEnv->pRenderer && gEnv->pRenderer->IsPost3DRendererEnabled())) - { - GetIRenderer()->SetViewport(0, 0, GetIRenderer()->GetWidth(), GetIRenderer()->GetHeight()); - m_env.p3DEngine->RenderWorld(SHDF_ALLOW_WATER | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOWHDR | SHDF_ZPASS | SHDF_ALLOW_AO, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_ViewCamera), __FUNCTION__); - } - else - { - if (gEnv->pRenderer) - { - // force rendering of black screen to be sure we don't only render the clear color (which is the fog color by default) - gEnv->pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - gEnv->pRenderer->Draw2dImage(0, 0, 800, 600, -1, 0.0f, 0.0f, 1.0f, 1.0f, 0.f, - 0.0f, 0.0f, 0.0f, 1.0f, 0.f); - } - } - } -#if !defined(_RELEASE) - if (m_pVisRegTest) - { - m_pVisRegTest->AfterRender(); - } -#endif - - if (m_env.pMovieSystem) - { - m_env.pMovieSystem->Render(); - } - } - } - else - { - GetIRenderer()->SetViewport(0, 0, GetIRenderer()->GetWidth(), GetIRenderer()->GetHeight()); - m_pProcess->RenderWorld(SHDF_ALLOW_WATER | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOWHDR | SHDF_ZPASS | SHDF_ALLOW_AO, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_ViewCamera), __FUNCTION__); - } - } - - m_env.p3DEngine->WorldStreamUpdate(); - - gEnv->pRenderer->SwitchToNativeResolutionBackbuffer(); -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderStats() -{ -#if defined(ENABLE_PROFILING_CODE) -#ifndef _RELEASE - // if we rendered an error message on screen during the last frame, then sleep now - // to force hard stall for 3sec - if (m_bHasRenderedErrorMessage && !gEnv->IsEditor() && !IsLoading()) - { - // DO NOT REMOVE OR COMMENT THIS OUT! - // If you hit this, then you most likely have invalid (synchronous) file accesses - // which must be fixed in order to not stall the entire game. - Sleep(3000); - m_bHasRenderedErrorMessage = false; - } -#endif - - // render info messages on screen - float fTextPosX = 5.0f; - float fTextPosY = -10; - float fTextStepY = 13; - - float fFrameTime = gEnv->pTimer->GetRealFrameTime(); - TErrorMessages::iterator itnext; - for (TErrorMessages::iterator it = m_ErrorMessages.begin(); it != m_ErrorMessages.end(); it = itnext) - { - itnext = it; - ++itnext; - SErrorMessage& message = *it; - - SDrawTextInfo ti; - ti.flags = eDrawText_FixedSize | eDrawText_2D | eDrawText_Monospace; - memcpy(ti.color, message.m_Color, 4 * sizeof(float)); - ti.xscale = ti.yscale = 1.4f; - m_env.pRenderer->DrawTextQueued(Vec3(fTextPosX, fTextPosY += fTextStepY, 1.0f), ti, message.m_Message.c_str()); - - if (!IsLoading()) - { - message.m_fTimeToShow -= fFrameTime; - } - - if (message.m_HardFailure) - { - m_bHasRenderedErrorMessage = true; - } - - if (message.m_fTimeToShow < 0.0f) - { - m_ErrorMessages.erase(it); - } - } -#endif - - if (!m_env.pConsole) - { - return; - } - -#ifndef _RELEASE - if (m_rOverscanBordersDrawDebugView) - { - RenderOverscanBorders(); - } -#endif - - int iDisplayInfo = m_rDisplayInfo->GetIVal(); - if (iDisplayInfo == 0) - { - return; - } - - // Draw engine stats - if (m_env.p3DEngine) - { - // Draw 3dengine stats and get last text cursor position - float nTextPosX = 101 - 20, nTextPosY = -2, nTextStepY = 3; - m_env.p3DEngine->DisplayInfo(nTextPosX, nTextPosY, nTextStepY, iDisplayInfo != 1); - - // Dump Open 3D Engine CPU and GPU memory statistics to screen - m_env.p3DEngine->DisplayMemoryStatistics(); - - #if defined(ENABLE_LW_PROFILERS) - if (m_rDisplayInfo->GetIVal() == 2) - { - m_env.pRenderer->TextToScreen(nTextPosX, nTextPosY += nTextStepY, "SysMem %.1f mb", - float(DumpMMStats(false)) / 1024.f); - } - #endif - - #if 0 - for (int i = 0; i < NUM_POOLS; ++i) - { - int used = (g_pPakHeap->m_iBigPoolUsed[i] ? (int)g_pPakHeap->m_iBigPoolSize[i] : 0); - int size = (int)g_pPakHeap->m_iBigPoolSize[i]; - float fC1[4] = {1, 1, 0, 1}; - m_env.pRenderer->Draw2dLabel(10, 100.0f + i * 16, 2.1f, fC1, false, "BigPool %d: %d bytes of %d bytes used", i, used, size); - } - #endif - } -} - -void CSystem::RenderOverscanBorders() -{ -#ifndef _RELEASE - - if (m_env.pRenderer && m_rOverscanBordersDrawDebugView) - { - int iOverscanBordersDrawDebugView = m_rOverscanBordersDrawDebugView->GetIVal(); - if (iOverscanBordersDrawDebugView) - { - const int texId = -1; - const float uv = 0.0f; - const float rot = 0.0f; - const int whiteTextureId = m_env.pRenderer->GetWhiteTextureId(); - - const float r = 1.0f; - const float g = 1.0f; - const float b = 1.0f; - const float a = 0.2f; - - Vec2 overscanBorders = Vec2(0.0f, 0.0f); - m_env.pRenderer->EF_Query(EFQ_OverscanBorders, overscanBorders); - - const float overscanBorderWidth = overscanBorders.x * VIRTUAL_SCREEN_WIDTH; - const float overscanBorderHeight = overscanBorders.y * VIRTUAL_SCREEN_HEIGHT; - - const float xPos = overscanBorderWidth; - const float yPos = overscanBorderHeight; - const float width = VIRTUAL_SCREEN_WIDTH - (2.0f * overscanBorderWidth); - const float height = VIRTUAL_SCREEN_HEIGHT - (2.0f * overscanBorderHeight); - - m_env.pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - m_env.pRenderer->Draw2dImage(xPos, yPos, - width, height, - whiteTextureId, - uv, uv, uv, uv, - rot, - r, g, b, a); - } - } -#endif -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index 974e578f38..ce352966ac 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -15,7 +15,6 @@ #include "System.h" #include -#include #include #include #include @@ -302,23 +301,6 @@ void CSystem::CollectMemStats (ICrySizer* pSizer, MemStatsPurposeEnum nPurpose, } } - - if (m_env.p3DEngine) - { - SIZER_COMPONENT_NAME(pSizer, "Cry3DEngine"); - { - m_env.p3DEngine->GetMemoryUsage (pSizer); - { - SIZER_COMPONENT_NAME (pSizer, "$Allocations waste"); - const SmallModuleInfo* info = FindModuleInfo(stats, "Cry3DEngine.dll"); - if (info) - { - pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested); - } - } - } - } - if (m_env.pRenderer) { SIZER_COMPONENT_NAME(pSizer, "CryRenderer"); diff --git a/Code/CryEngine/CrySystem/ViewSystem/View.cpp b/Code/CryEngine/CrySystem/ViewSystem/View.cpp index 384d1c76f5..f8b84bea19 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/View.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/View.cpp @@ -98,7 +98,7 @@ void CView::Update(float frameTime, bool isActive) //see if the view have to use a custom near clipping plane const float nearPlane = (m_viewParams.nearplane >= CAMERA_MIN_NEAR) ? (m_viewParams.nearplane) : fNearZ; - const float farPlane = (m_viewParams.farplane > 0.f) ? m_viewParams.farplane : gEnv->p3DEngine->GetMaxViewDistance(); + const float farPlane = (m_viewParams.farplane > 0.f) ? m_viewParams.farplane : DEFAULT_FAR; float fov = (m_viewParams.fov < 0.001f) ? DEFAULT_FOV : m_viewParams.fov; // [VR] specific diff --git a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp index 65581662c3..13f7f5b82d 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp @@ -533,11 +533,6 @@ void CViewSystem::BeginCutScene(IAnimSequence* pSeq, [[maybe_unused]] unsigned l { m_cutsceneCount++; - if (m_cutsceneCount == 1) - { - gEnv->p3DEngine->ResetPostEffects(); - } - VS_CALL_LISTENERS(OnBeginCutScene(pSeq, bResetFX)); } @@ -546,11 +541,6 @@ void CViewSystem::EndCutScene(IAnimSequence* pSeq, [[maybe_unused]] unsigned lon { m_cutsceneCount -= (m_cutsceneCount > 0); - if (m_cutsceneCount == 0) - { - gEnv->p3DEngine->ResetPostEffects(); - } - ClearCutsceneViews(); VS_CALL_LISTENERS(OnEndCutScene(pSeq)); diff --git a/Code/CryEngine/CrySystem/VisRegTest.cpp b/Code/CryEngine/CrySystem/VisRegTest.cpp index 81ef205b47..206d8f349a 100644 --- a/Code/CryEngine/CrySystem/VisRegTest.cpp +++ b/Code/CryEngine/CrySystem/VisRegTest.cpp @@ -18,7 +18,6 @@ #include "VisRegTest.h" #include "ISystem.h" -#include "I3DEngine.h" #include "IRenderer.h" #include "IConsole.h" #include "ITimer.h" diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 23ad644041..bfc7b092fd 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -57,7 +57,6 @@ set(FILES UnixConsole.h SystemInit.h Serialization/MemoryReader.h - Statistics/LocalMemoryUsage.h MemoryFragmentationProfiler.h XML/ReadWriteXMLSink.h Serialization/ArchiveHost.h @@ -151,7 +150,6 @@ set(FILES MiniGUI/MiniInfoBox.h MiniGUI/MiniMenu.h MiniGUI/MiniTable.h - Statistics/LocalMemoryUsage.cpp ZLibCompressor.cpp ZLibCompressor.h SoftCode/SoftCodeMgr.cpp diff --git a/Code/Sandbox/Editor/2DViewport.cpp b/Code/Sandbox/Editor/2DViewport.cpp index d86ea03bdf..0487c9381f 100644 --- a/Code/Sandbox/Editor/2DViewport.cpp +++ b/Code/Sandbox/Editor/2DViewport.cpp @@ -650,114 +650,6 @@ void Q2DViewport::OnDestroy() ////////////////////////////////////////////////////////////////////////// void Q2DViewport::Render() { - if (GetIEditor()->IsInGameMode()) - { - return; - } - - if (!m_renderer) - { - return; - } - - if (!isVisible()) - { - return; - } - - if (!GetIEditor()->GetDocument()->IsDocumentReady()) - { - return; - } - - if (m_renderer->IsStereoEnabled()) - { - return; - } - - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - QRect rc = rect(); - if (rc.isEmpty()) - { - return; - } - - CalculateViewTM(); - - // Render - WIN_HWND priorContext = m_renderer->GetCurrentContextHWND(); - - m_renderer->SetCurrentContext(renderOverlayHWND()); - m_renderer->BeginFrame(); - m_renderer->ChangeViewport(0, 0, rc.right(), rc.bottom(), true); - - CScopedWireFrameMode scopedWireFrame(m_renderer, R_SOLID_MODE); - auto colorf = Rgb2ColorF(m_colorBackground); - m_renderer->ClearTargetsLater(FRT_CLEAR, colorf); - - ////////////////////////////////////////////////////////////////////////// - // 2D Mode. - ////////////////////////////////////////////////////////////////////////// - if (rc.right() != 0 && rc.bottom() != 0) - { - TransformationMatrices backupSceneMatrices; - - m_renderer->Set2DMode(rc.right(), rc.bottom(), backupSceneMatrices); - - ////////////////////////////////////////////////////////////////////////// - // Draw viewport elements here. - ////////////////////////////////////////////////////////////////////////// - // Calc world bounding box for objects rendering. - m_displayBounds = GetWorldBounds(QPoint(0, 0), QPoint(rc.width(), rc.height())); - - // Draw all objects. - DisplayContext& dc = m_displayContext; - dc.settings = GetIEditor()->GetDisplaySettings(); - dc.view = this; - dc.renderer = m_renderer; - dc.engine = GetIEditor()->Get3DEngine(); - dc.flags = DISPLAY_2D; - dc.box = m_displayBounds; - dc.camera = &GetIEditor()->GetSystem()->GetViewCamera(); - - if (!dc.settings->IsDisplayLabels() || !dc.settings->IsDisplayHelpers()) - { - dc.flags |= DISPLAY_HIDENAMES; - } - if (dc.settings->IsDisplayLinks() && dc.settings->IsDisplayHelpers()) - { - dc.flags |= DISPLAY_LINKS; - } - if (m_bDegradateQuality) - { - dc.flags |= DISPLAY_DEGRADATED; - } - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(GetIEditor()->GetSystem()->GetViewCamera()); - - m_renderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->EF_StartEf(passInfo); - - dc.SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); - Draw(dc); - - m_renderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); - - m_renderer->EF_RenderTextMessages(); - - // Return back from 2D mode. - m_renderer->Unset2DMode(backupSceneMatrices); - - m_renderer->RenderDebug(false); - - ProcessRenderLisneters(m_displayContext); - - m_renderer->EndFrame(); - } - - GetIEditor()->GetRenderer()->SetCurrentContext(priorContext); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp index 0c99e63c47..c8bd157b65 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp @@ -50,8 +50,6 @@ #include "Include/IObjectManager.h" #include "CryEditDoc.h" #include "QtViewPaneManager.h" -#include "AzAssetBrowser/Preview/LegacyPreviewerFactory.h" - namespace AzAssetBrowserRequestHandlerPrivate { @@ -230,18 +228,15 @@ namespace AzAssetBrowserRequestHandlerPrivate } AzAssetBrowserRequestHandler::AzAssetBrowserRequestHandler() - : m_previewerFactory(aznew LegacyPreviewerFactory) { using namespace AzToolsFramework::AssetBrowser; AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzQtComponents::DragAndDropEventsBus::Handler::BusConnect(AzQtComponents::DragAndDropContexts::EditorViewport); - AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusConnect(); } AzAssetBrowserRequestHandler::~AzAssetBrowserRequestHandler() { - AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzQtComponents::DragAndDropEventsBus::Handler::BusDisconnect(); } @@ -527,15 +522,6 @@ void AzAssetBrowserRequestHandler::Drop(QDropEvent* event, AzQtComponents::DragA } } -const AzToolsFramework::AssetBrowser::PreviewerFactory* AzAssetBrowserRequestHandler::GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - if (m_previewerFactory->IsEntrySupported(entry)) - { - return m_previewerFactory.get(); - } - return nullptr; -} - void AzAssetBrowserRequestHandler::AddSourceFileOpeners(const char* fullSourceFileName, const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) { using namespace AzToolsFramework; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h index 5b7e10f2a1..707b9041ae 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h @@ -37,12 +37,9 @@ namespace AzToolsFramework } } -class LegacyPreviewerFactory; - class AzAssetBrowserRequestHandler : protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler , protected AzQtComponents::DragAndDropEventsBus::Handler - , protected AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler { public: AzAssetBrowserRequestHandler(); @@ -66,16 +63,8 @@ protected: void DragLeave(QDragLeaveEvent* event) override; void Drop(QDropEvent* event, AzQtComponents::DragAndDropContextBase& context) override; - ////////////////////////////////////////////////////////////////////////// - // PreviewerRequestBus::Handler - ////////////////////////////////////////////////////////////////////////// - const AzToolsFramework::AssetBrowser::PreviewerFactory* GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - bool CanAcceptDragAndDropEvent( QDropEvent* event, AzQtComponents::DragAndDropContextBase& context, AZStd::optional*> outSources = AZStd::nullopt, AZStd::optional*> outProducts = AZStd::nullopt) const; - -private: - AZStd::unique_ptr m_previewerFactory; }; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp deleted file mode 100644 index 19938db676..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorDefs.h" - -#include "LegacyPreviewer.h" - -// AzToolsFramework -#include -#include -#include - -// Editor -#include "Util/Image.h" -#include "Util/ImageUtil.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - -static const int s_CharWidth = 6; -const QString LegacyPreviewer::Name{ QStringLiteral("LegacyPreviewer") }; - -LegacyPreviewer::LegacyPreviewer(QWidget* parent) - : Previewer(parent) - , m_ui(new Ui::LegacyPreviewerClass()) - , m_textureType(TextureType::RGB) -{ - m_ui->setupUi(this); - m_ui->m_comboBoxRGB->addItems(QStringList() << "RGB" << "RGBA" << "Alpha"); - m_ui->m_previewCtrl->SetAspectRatio(4.0f / 3.0f); - connect(m_ui->m_comboBoxRGB, static_cast(&QComboBox::activated), this, - [=](int index) - { - m_textureType = static_cast(index); - UpdateTextureType(); - }); - Clear(); -} - -LegacyPreviewer::~LegacyPreviewer() -{ -} - -void LegacyPreviewer::Clear() const -{ - m_ui->m_previewCtrl->ReleaseObject(); - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->hide(); - m_ui->m_fileInfoCtrl->hide(); -} - -void LegacyPreviewer::Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (!entry) - { - Clear(); - return; - } - - switch (entry->GetEntryType()) - { - case AssetBrowserEntry::AssetEntryType::Source: - { - const SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry); - DisplaySource(sourceEntry); - break; - } - case AssetBrowserEntry::AssetEntryType::Product: - DisplayProduct(static_cast(entry)); - break; - default: - Clear(); - } -} - -const QString& LegacyPreviewer::GetName() const -{ - return Name; -} - -void LegacyPreviewer::resizeEvent(QResizeEvent* /*event*/) -{ - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); -} - -bool LegacyPreviewer::DisplayProduct(const AzToolsFramework::AssetBrowser::ProductAssetBrowserEntry* product) -{ - m_ui->m_fileInfoCtrl->show(); - - m_fileinfo = QString::fromUtf8(product->GetName().c_str()); - - m_fileinfo += GetFileSize(product->GetRelativePath().c_str()); - - EBusFindAssetTypeByName meshAssetTypeResult("Static Mesh"); - AZ::AssetTypeInfoBus::BroadcastResult(meshAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - QString filename(product->GetRelativePath().c_str()); - - // Find item. - if (product->GetAssetType() == meshAssetTypeResult.GetAssetType()) - { - m_ui->m_modelPreviewWidget->show(); - m_ui->m_texturePreviewWidget->hide(); - m_ui->m_previewCtrl->LoadFile(filename); - - int nVertexCount = m_ui->m_previewCtrl->GetVertexCount(); - int nFaceCount = m_ui->m_previewCtrl->GetFaceCount(); - int nMaxLod = m_ui->m_previewCtrl->GetMaxLod(); - int nMtls = m_ui->m_previewCtrl->GetMtlCount(); - if (nFaceCount > 0) - { - m_fileinfo += tr("\r\n%1 Faces\r\n%2 Verts\r\n%3 MaxLod\r\n%4 Materials").arg(nFaceCount).arg(nVertexCount).arg(nMaxLod).arg(nMtls); - } - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - updateGeometry(); - return true; - } - - EBusFindAssetTypeByName textureAssetTypeResult("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - if (product->GetAssetType() == textureAssetTypeResult.GetAssetType()) - { - // Get full product file path - const char* assetCachePath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@assets@"); - AZStd::string productFullPath; - AzFramework::StringFunc::Path::Join(assetCachePath, product->GetRelativePath().c_str(), productFullPath); - if (AZ::IO::FileIOBase::GetInstance()->Exists(productFullPath.c_str())) - { - // Try to display it in modern dds image loader, if no one exists, use the legacy image loader - bool foundPixmap = DisplayTextureProductModern(productFullPath.c_str()); - return foundPixmap ? foundPixmap : DisplayTextureLegacy(productFullPath.c_str()); - } - else - { - // If we cannot find the product file, means it's not treated as an asset, display its source - return DisplayTextureLegacy(product->GetFullPath().c_str()); - } - } - - Clear(); - return false; -} - -void LegacyPreviewer::DisplaySource(const AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* source) -{ - using namespace AzToolsFramework::AssetBrowser; - - EBusFindAssetTypeByName textureAssetType("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetType, &AZ::AssetTypeInfo::GetAssetType); - - if (source->GetPrimaryAssetType() == textureAssetType.GetAssetType()) - { - m_ui->m_fileInfoCtrl->show(); - m_fileinfo = QString::fromUtf8(source->GetName().c_str()); - m_fileinfo += GetFileSize(source->GetFullPath().c_str()); - const char* fullSourcePath = source->GetFullPath().c_str(); - // If it's a source dds file, try to display it using modern way - if (AzFramework::StringFunc::Path::IsExtension(fullSourcePath, "dds", false)) - { - if (DisplayTextureProductModern(fullSourcePath)) - { - return; - } - } - DisplayTextureLegacy(source->GetFullPath().c_str()); - } - else - { - AZStd::vector products; - source->GetChildrenRecursively(products); - if (products.empty()) - { - Clear(); - } - else - { - for (auto* product : products) - { - if (DisplayProduct(product)) - { - break; - } - } - } - } -} - -QString LegacyPreviewer::GetFileSize(const char* path) -{ - QString fileSizeStr; - AZ::u64 fileSizeResult = 0; - if (AZ::IO::FileIOBase::GetInstance()->Size(path, fileSizeResult)) - { - static double kb = 1024.0f; - static double mb = kb * 1024.0; - static double gb = mb * 1024.0; - - static QString byteStr = "B"; - static QString kbStr = "KB"; - static QString mbStr = "MB"; - static QString gbStr = "GB"; - -#if AZ_TRAIT_OS_PLATFORM_APPLE - kb = 1000.0; - mb = kb * 1000.0; - gb = mb * 1000.0; - - kbStr = "kB"; - mbStr = "mB"; - gbStr = "gB"; -#endif // AZ_TRAIT_OS_PLATFORM_APPLE - - if (fileSizeResult < kb) - { - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(fileSizeResult), byteStr); - } - else if (fileSizeResult < mb) - { - double size = fileSizeResult / kb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), kbStr); - } - else if (fileSizeResult < gb) - { - double size = fileSizeResult / mb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), mbStr); - } - else - { - double size = fileSizeResult / gb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), gbStr); - } - } - return fileSizeStr; -} - -bool LegacyPreviewer::DisplayTextureLegacy(const char* fullImagePath) -{ - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->show(); - - bool foundPixmap = false; - if (!AZ::IO::FileIOBase::GetInstance()->IsDirectory(fullImagePath)) - { - QString strLoadFilename = QString(fullImagePath); - if (CImageUtil::LoadImage(strLoadFilename, m_previewImageSource)) - { - m_fileinfo += QStringLiteral("\r\n%1x%2\r\n%3") - .arg(m_previewImageSource.GetWidth()) - .arg(m_previewImageSource.GetHeight()) - .arg(m_previewImageSource.GetFormatDescription()); - - m_fileinfoAlphaTexture = m_fileinfo; - UpdateTextureType(); - foundPixmap = true; - } - } - - if (!foundPixmap) - { - m_ui->m_previewImageCtrl->setPixmap(QPixmap()); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - } - - updateGeometry(); - - return foundPixmap; -} - -bool LegacyPreviewer::DisplayTextureProductModern(const char* fullProductImagePath) -{ - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->show(); - - bool foundPixmap = false; - QImage previewImage; - AZStd::string productInfo; - AZStd::string productAlphaInfo; - AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::BroadcastResult(foundPixmap, &AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequests::GetProductTexturePreview, fullProductImagePath, previewImage, productInfo, productAlphaInfo); - - if (foundPixmap) - { - QPixmap pix = QPixmap::fromImage(previewImage); - m_ui->m_previewImageCtrl->setPixmap(pix); - m_ui->m_previewImageCtrl->updateGeometry(); - CImageUtil::QImageToImage(previewImage, m_previewImageSource); - - m_fileinfo += QStringLiteral("\r\n%1x%2\r\n%3") - .arg(m_previewImageSource.GetWidth()) - .arg(m_previewImageSource.GetHeight()) - .arg(m_previewImageSource.GetFormatDescription()); - - m_fileinfoAlphaTexture = m_fileinfo; - - m_fileinfo += QString(productInfo.c_str()); - if (productAlphaInfo.empty()) - { - // If there is no separate info for alpha, use the image info - m_fileinfoAlphaTexture += QString(productInfo.c_str()); - } - else - { - m_fileinfoAlphaTexture += QString(productAlphaInfo.c_str()); - } - - - UpdateTextureType(); - } - else - { - m_ui->m_previewImageCtrl->setPixmap(QPixmap()); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - } - - updateGeometry(); - return foundPixmap; -} - -void LegacyPreviewer::UpdateTextureType() -{ - m_previewImageUpdated.Copy(m_previewImageSource); - - switch (m_textureType) - { - case TextureType::RGB: - { - m_previewImageUpdated.SwapRedAndBlue(); - m_previewImageUpdated.FillAlpha(); - break; - } - case TextureType::RGBA: - { - m_previewImageUpdated.SwapRedAndBlue(); - break; - } - case TextureType::Alpha: - { - for (int h = 0; h < m_previewImageUpdated.GetHeight(); h++) - { - for (int w = 0; w < m_previewImageUpdated.GetWidth(); w++) - { - int a = m_previewImageUpdated.ValueAt(w, h) >> 24; - m_previewImageUpdated.ValueAt(w, h) = RGB(a, a, a) | 0xFF000000; - } - } - break; - } - } - // note that Qt will not deep copy the data, so WE MUST KEEP THE IMAGE DATA AROUND! - QPixmap qtPixmap = QPixmap::fromImage( - QImage(reinterpret_cast(m_previewImageUpdated.GetData()), m_previewImageUpdated.GetWidth(), m_previewImageUpdated.GetHeight(), QImage::Format_ARGB32)); - m_ui->m_previewImageCtrl->setPixmap(qtPixmap); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_textureType == TextureType::Alpha? m_fileinfoAlphaTexture: m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - m_ui->m_previewImageCtrl->updateGeometry(); -} - -bool LegacyPreviewer::FileInfoCompare(const FileInfo& f1, const FileInfo& f2) -{ - if ((f1.attrib & _A_SUBDIR) && !(f2.attrib & _A_SUBDIR)) - { - return true; - } - if (!(f1.attrib & _A_SUBDIR) && (f2.attrib & _A_SUBDIR)) - { - return false; - } - - return QString::compare(f1.filename, f2.filename, Qt::CaseInsensitive) < 0; -} - -QString LegacyPreviewer::WordWrap(const QString& string, int maxLength) -{ - QString result; - int length = 0; - - for (auto c : string) - { - if (c == '\n') - { - length = 0; - } - else if (length > maxLength) - { - result.append('\n'); - length = 0; - } - else - { - length++; - } - result.append(c); - } - return result; -} - -#include diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h deleted file mode 100644 index 0035f23442..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include - -#include -#include -#endif - -namespace Ui -{ - class LegacyPreviewerClass; -} - -namespace AzToolsFramework -{ - namespace AssetBrowser - { - class ProductAssetBrowserEntry; - class SourceAssetBrowserEntry; - class AssetBrowserEntry; - } -} - -class QResizeEvent; - -class LegacyPreviewer - : public AzToolsFramework::AssetBrowser::Previewer -{ - Q_OBJECT -public: - AZ_CLASS_ALLOCATOR(LegacyPreviewer, AZ::SystemAllocator, 0); - - explicit LegacyPreviewer(QWidget* parent = nullptr); - ~LegacyPreviewer(); - - ////////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::Previewer - ////////////////////////////////////////////////////////////////////////// - void Clear() const override; - void Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) override; - const QString& GetName() const override; - - static const QString Name; - -protected: - void resizeEvent(QResizeEvent * event) override; - -private: - struct FileInfo - { - QString filename; - unsigned attrib; - time_t time_create; /* -1 for FAT file systems */ - time_t time_access; /* -1 for FAT file systems */ - time_t time_write; - _fsize_t size; - }; - - enum class TextureType - { - RGB, - RGBA, - Alpha - }; - - QScopedPointer m_ui; - CImageEx m_previewImageSource; - CImageEx m_previewImageUpdated; - TextureType m_textureType; - QString m_fileinfo; - QString m_fileinfoAlphaTexture; - - bool DisplayProduct(const AzToolsFramework::AssetBrowser::ProductAssetBrowserEntry* product); - void DisplaySource(const AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* source); - - QString GetFileSize(const char* path); - - bool DisplayTextureLegacy(const char* fullImagePath); - bool DisplayTextureProductModern(const char* fullProductImagePath); - - void UpdateTextureType(); - - static bool FileInfoCompare(const FileInfo& f1, const FileInfo& f2); - //! QLabel word wrap does not break long words such as filenames, so manual word wrap needed - static QString WordWrap(const QString& string, int maxLength); -}; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui deleted file mode 100644 index 649192d60f..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui +++ /dev/null @@ -1,176 +0,0 @@ - - - LegacyPreviewerClass - - - - 0 - 0 - 148 - 282 - - - - Preview - - - - 0 - - - 5 - - - 0 - - - 5 - - - 0 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - - 0 - 0 - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - - - Qt::AutoText - - - false - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - CPreviewModelCtrl - QWidget -
Controls/PreviewModelCtrl.h
- 1 -
- - AzToolsFramework::AspectRatioAwarePixmapWidget - QWidget -
AzToolsFramework/UI/UICore/AspectRatioAwarePixmapWidget.hxx
- 1 -
-
- - -
diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp deleted file mode 100644 index 93620d26a6..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorDefs.h" - -#include "LegacyPreviewerFactory.h" - -// AzToolsFramework -#include // for AssetBrowserEntry::AssetEntryType -#include // for EBusFindAssetTypeByName - -// Editor -#include "LegacyPreviewer.h" - - -AzToolsFramework::AssetBrowser::Previewer* LegacyPreviewerFactory::CreatePreviewer(QWidget* parent) const -{ - return new LegacyPreviewer(parent); -} - -bool LegacyPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - using namespace AzToolsFramework::AssetBrowser; - - EBusFindAssetTypeByName meshAssetTypeResult("Static Mesh"); - AZ::AssetTypeInfoBus::BroadcastResult(meshAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - EBusFindAssetTypeByName textureAssetTypeResult("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - switch (entry->GetEntryType()) - { - case AssetBrowserEntry::AssetEntryType::Source: - { - const auto* source = azrtti_cast < const SourceAssetBrowserEntry * > (entry); - if (source->GetPrimaryAssetType() == textureAssetTypeResult.GetAssetType()) - { - return true; - } - AZStd::vector < const ProductAssetBrowserEntry * > products; - source->GetChildrenRecursively < ProductAssetBrowserEntry > (products); - for (auto* product : products) - { - if (product->GetAssetType() == textureAssetTypeResult.GetAssetType() || - product->GetAssetType() == meshAssetTypeResult.GetAssetType()) - { - return true; - } - } - break; - } - case AssetBrowserEntry::AssetEntryType::Product: - const auto* product = azrtti_cast < const ProductAssetBrowserEntry * > (entry); - return product->GetAssetType() == textureAssetTypeResult.GetAssetType() || - product->GetAssetType() == meshAssetTypeResult.GetAssetType(); - } - return false; -} - -const QString& LegacyPreviewerFactory::GetName() const -{ - return LegacyPreviewer::Name; -} diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h deleted file mode 100644 index e6b133cb97..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include - -class QString; - -class LegacyPreviewerFactory final - : public AzToolsFramework::AssetBrowser::PreviewerFactory -{ -public: - AZ_CLASS_ALLOCATOR(LegacyPreviewerFactory, AZ::SystemAllocator, 0); - - LegacyPreviewerFactory() = default; - ~LegacyPreviewerFactory() = default; - - ////////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::PreviewerFactory - ////////////////////////////////////////////////////////////////////////// - AzToolsFramework::AssetBrowser::Previewer* CreatePreviewer(QWidget* parent = nullptr) const override; - bool IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - const QString& GetName() const override; -}; diff --git a/Code/Sandbox/Editor/BaseLibraryManager.cpp b/Code/Sandbox/Editor/BaseLibraryManager.cpp index 61c6354b1a..d9017c1be8 100644 --- a/Code/Sandbox/Editor/BaseLibraryManager.cpp +++ b/Code/Sandbox/Editor/BaseLibraryManager.cpp @@ -826,9 +826,6 @@ void CBaseLibraryManager::OnEditorNotifyEvent(EEditorNotifyEvent event) SetSelectedItem(0); ClearAll(); break; - case eNotify_OnMissionChange: - SetSelectedItem(0); - break; case eNotify_OnCloseScene: SetSelectedItem(0); ClearAll(); diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp deleted file mode 100644 index 9b07f59e6a..0000000000 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp +++ /dev/null @@ -1,1194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "PreviewModelCtrl.h" - -// AzQtComponents -#include - -// Editor -#include "Settings.h" -#include "Util/Image.h" -#include "Include/IIconManager.h" - -struct CPreviewModelCtrl::SPreviousContext -{ - CCamera renderCamera; - CCamera systemCamera; - int width; - int height; - HWND window; - bool isMainViewport; -}; - -CPreviewModelCtrl::CPreviewModelCtrl(QWidget* parent, Qt::WindowFlags f) - : QWidget(parent, f) -{ - OnCreate(); -} - -void CPreviewModelCtrl::OnCreate() -{ - m_bShowObject = true; - m_pRenderer = 0; - m_pObj = 0; - m_pEntity = 0; - m_nTimer = 0; - m_size = Vec3(0, 0, 0); - - m_bRotate = false; - m_rotateAngle = 0; - - m_backgroundTextureId = 0; - - m_pRenderer = GetIEditor()->GetRenderer(); - - m_fov = 60; - m_camera.SetFrustum(800, 600, DEG2RAD(m_fov), 0.02f, 10000.0f); - - m_bInRotateMode = false; - m_bInMoveMode = false; - - CDLight l; - - float L = 1.0f; - l.m_fRadius = 10000; - l.m_Flags |= DLF_SUN | DLF_DIRECTIONAL; - l.SetLightColor(ColorF(L, L, L, 1)); - l.SetPosition(Vec3(100, 100, 100)); - m_lights.push_back(l); - - m_bUseBacklight = false; - m_bContextCreated = false; - m_bHaveAnythingToRender = false; - m_bGrid = true; - m_bAxis = true; - m_bAxisParticleEditor = false; - m_bUpdate = false; - m_bShowNormals = false; - m_bShowPhysics = false; - m_bShowRenderInfo = false; - - m_cameraAngles.Set(0, 0, 0); - - m_clearColor.Set(0.5f, 0.5f, 0.5f); - m_ambientColor.Set(1.0f, 1.0f, 1.0f); - m_ambientMultiplier = 0.5f; - - m_cameraChangeCallback = NULL; - m_bPrecacheMaterial = false; - m_bDrawWireFrame = false; - - m_tileX = 0.0f; - m_tileY = 0.0f; - m_tileSizeX = 1.0f; - m_tileSizeY = 1.0f; - - m_aabb = AABB(2); - FitToScreen(); - - setAttribute(Qt::WA_NativeWindow); - setAttribute(Qt::WA_PaintOnScreen); - setAttribute(Qt::WA_OpaquePaintEvent); - - GetIEditor()->RegisterNotifyListener(this); -} - -CPreviewModelCtrl::~CPreviewModelCtrl() -{ - OnDestroy(); - ReleaseObject(); - GetIEditor()->UnregisterNotifyListener(this); -} - -bool CPreviewModelCtrl::CreateContext() -{ - // Create context. - if (m_pRenderer && !m_bContextCreated) - { - StorePreviousContext(); - m_bContextCreated = true; - - // save the old context, because CreateContext sets it, and we don't actually want that: - StorePreviousContext(); - m_pRenderer->CreateContext(m_hWnd); - - RestorePreviousContext(); - return true; - } - return false; -} - -void CPreviewModelCtrl::ReleaseObject() -{ - m_pObj = NULL; - m_pEntity = 0; - m_bHaveAnythingToRender = false; -} - -void CPreviewModelCtrl::LoadFile(const QString& modelFile, bool changeCamera) -{ - m_bHaveAnythingToRender = false; - if (!m_hWnd) - { - return; - } - if (!m_pRenderer) - { - return; - } - - ReleaseObject(); - - if (modelFile.isEmpty()) - { - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - - m_loadedFile = modelFile; - - QString strFileExt = QFileInfo(modelFile).suffix(); - const bool isSKEL = strFileExt.compare(QStringLiteral(CRY_SKEL_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isSKIN = strFileExt.compare(QStringLiteral(CRY_SKIN_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCDF = strFileExt.compare(QStringLiteral(CRY_CHARACTER_DEFINITION_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCGA = strFileExt.compare(QStringLiteral(CRY_ANIM_GEOMETRY_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCGF = strFileExt.compare(QStringLiteral(CRY_GEOMETRY_FILE_EXT), Qt::CaseInsensitive) == 0; - - if (isCGF) - { - // Load object. - m_pObj = GetIEditor()->Get3DEngine()->LoadStatObjAutoRef(modelFile.toUtf8().data(), NULL, NULL, false); - if (!m_pObj) - { - Warning("Loading of geometry object %s failed.", modelFile.toUtf8().constData()); - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - m_aabb.min = m_pObj->GetBoxMin(); - m_aabb.max = m_pObj->GetBoxMax(); - } - else - { - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - - m_bHaveAnythingToRender = true; - - if (changeCamera) - { - FitToScreen(); - } - - update(); -} - -void CPreviewModelCtrl::SetAspectRatio(float aspectRatio) -{ - if (aspectRatio != m_aspectRatio) - { - m_aspectRatio = aspectRatio; - m_useAspectRatio = true; - updateGeometry(); - } -} - -bool CPreviewModelCtrl::hasHeightForWidth() const -{ - return m_useAspectRatio; -} - -int CPreviewModelCtrl::heightForWidth(int w) const -{ - if (m_useAspectRatio) - { - return static_cast(static_cast(w) / m_aspectRatio); - } - - return QWidget::heightForWidth(w); -} - -void CPreviewModelCtrl::SetEntity(IRenderNode* entity) -{ - m_bHaveAnythingToRender = false; - if (m_pEntity != entity) - { - m_pEntity = entity; - if (m_pEntity) - { - m_bHaveAnythingToRender = true; - m_aabb = m_pEntity->GetBBox(); - } - update(); - } -} - -void CPreviewModelCtrl::SetObject(IStatObj* pObject) -{ - if (m_pObj != pObject) - { - m_bHaveAnythingToRender = false; - m_pObj = pObject; - if (m_pObj) - { - m_bHaveAnythingToRender = true; - m_aabb = m_pObj->GetAABB(); - } - update(); - } -} - -void CPreviewModelCtrl::SetCameraRadius(float fRadius) -{ - m_cameraRadius = fRadius; - - Matrix34 m = m_camera.GetMatrix(); - Vec3 dir = m.TransformVector(Vec3(0, 1, 0)); - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - tm.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(tm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::SetCameraLookAt(float fRadiusScale, const Vec3& fromDir) -{ - m_cameraTarget = m_aabb.GetCenter(); - m_cameraRadius = m_aabb.GetRadius() * fRadiusScale; - - Vec3 dir = fromDir.GetNormalized(); - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - tm.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(tm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -CCamera& CPreviewModelCtrl::GetCamera() -{ - return m_camera; -} - -void CPreviewModelCtrl::UseBackLight(bool bEnable) -{ - if (bEnable) - { - m_lights.resize(1); - CDLight l; - l.SetPosition(Vec3(-100, 100, -100)); - float L = 0.5f; - l.SetLightColor(ColorF(L, L, L, 1)); - l.m_fRadius = 1000; - l.m_Flags |= DLF_POINT; - m_lights.push_back(l); - } - else - { - m_lights.resize(1); - } - m_bUseBacklight = bEnable; -} - -void CPreviewModelCtrl::SetCamera(CCamera& cam) -{ - m_camera.SetPosition(cam.GetPosition()); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - const int w = width() * ratio * m_tileSizeX; - const int h = height() * ratio * m_tileSizeY; - m_camera.SetFrustum(w, h, DEG2RAD(m_fov), m_camera.GetNearPlane(), m_camera.GetFarPlane()); - - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::SetOrbitAngles([[maybe_unused]] const Ang3& ang) -{ - assert(0); -} - -bool CPreviewModelCtrl::Render() -{ - const int w = width(); - const int h = height(); - - if (h < 2 || w < 2) - { - return false; - } - - if (!m_bContextCreated) - { - if (!CreateContext()) - { - return false; - } - } - - _smart_ptr pMaterial; - - if (m_bPrecacheMaterial) - { - // Precache material - This loads/creates the material, shader and textures - // Moving this to the top of Render() so precaching precedes current and future - // rendering code - - _smart_ptr pCurMat = pMaterial; - - if (!pCurMat) - { - pCurMat = GetCurrentMaterial(); - } - - if (pCurMat) - { - pCurMat->PrecacheMaterial(0.0f, NULL, true, true); - } - } - - SetCamera(m_camera); - - m_pRenderer->SetClearColor(Vec3(m_clearColor.r, m_clearColor.g, m_clearColor.b)); - m_pRenderer->BeginFrame(); - SetCurrentContext(); - m_pRenderer->SetRenderTile(m_tileX, m_tileY, m_tileSizeX, m_tileSizeY); - - // Render grid. Explicitly clear color and depth buffer first - // (otherwise ->EndEf3D() will do that and thereby clear the grid). - m_pRenderer->ClearTargetsImmediately(FRT_CLEAR, m_clearColor); - - DrawBackground(); - if (m_bGrid || m_bAxis) - { - DrawGrid(); - } - - // save some cvars - int showNormals = gEnv->pConsole->GetCVar("r_ShowNormals")->GetIVal(); - int showInfo = gEnv->pConsole->GetCVar("r_displayInfo")->GetIVal(); - - gEnv->pConsole->GetCVar("r_ShowNormals")->Set((int)m_bShowNormals); - gEnv->pConsole->GetCVar("r_displayInfo")->Set((int)m_bShowRenderInfo); - - // Render object. - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - m_pRenderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_pRenderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_pRenderer->EF_StartEf(passInfo); - m_pRenderer->ResetToDefault(); - - - { - CScopedWireFrameMode scopedWireFrame(m_pRenderer, m_bDrawWireFrame ? R_WIREFRAME_MODE : R_SOLID_MODE); - - // Add lights. - for (size_t i = 0; i < m_lights.size(); i++) - { - m_pRenderer->EF_ADDDlight(&m_lights[i], passInfo); - } - - if (m_bShowObject) - { - RenderObject(pMaterial, passInfo); - } - - m_pRenderer->EF_EndEf3D(SHDF_NOASYNC | SHDF_STREAM_SYNC, -1, -1, passInfo); - } - - m_pRenderer->EF_RenderTextMessages(); - m_pRenderer->RenderDebug(false); - m_pRenderer->EndFrame(); - m_pRenderer->SetRenderTile(); - - // Restore main context. - RestorePreviousContext(); - - gEnv->pConsole->GetCVar("r_ShowNormals")->Set(showNormals); - gEnv->pConsole->GetCVar("r_displayInfo")->Set(showInfo); - - return true; -} - -void CPreviewModelCtrl::RenderObject(_smart_ptr pMaterial, SRenderingPassInfo& passInfo) -{ - SRendParams rp; - rp.dwFObjFlags = 0; - rp.AmbientColor = m_ambientColor * m_ambientMultiplier; - rp.dwFObjFlags |= FOB_NO_FOG; - rp.pMaterial = pMaterial; - - Matrix34 tm; - tm.SetIdentity(); - rp.pMatrix = &tm; - - if (m_bRotate) - { - tm.SetRotationXYZ(Ang3(0, 0, m_rotateAngle)); - m_rotateAngle += 0.1f; - } - - if (m_pObj) - { - m_pObj->Render(rp, passInfo); - } - - if (m_pEntity) - { - m_pEntity->Render(rp, passInfo); - } -} - -void CPreviewModelCtrl::DrawGrid() -{ - // Draw grid. - float step = 0.1f; - float XR = 5; - float YR = 5; - - IRenderAuxGeom* pRag = m_pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags nRendFlags = pRag->GetRenderFlags(); - - pRag->SetRenderFlags(e_Def3DPublicRenderflags); - SAuxGeomRenderFlags nNewFlags = pRag->GetRenderFlags(); - nNewFlags.SetAlphaBlendMode(e_AlphaBlended); - pRag->SetRenderFlags(nNewFlags); - - int nGridAlpha = 40; - if (m_bGrid) - { - // Draw grid. - for (float x = -XR; x < XR; x += step) - { - if (fabs(x) > 0.01) - { - pRag->DrawLine(Vec3(x, -YR, 0), ColorB(150, 150, 150, nGridAlpha), Vec3(x, YR, 0), ColorB(150, 150, 150, nGridAlpha)); - } - } - for (float y = -YR; y < YR; y += step) - { - if (fabs(y) > 0.01) - { - pRag->DrawLine(Vec3(-XR, y, 0), ColorB(150, 150, 150, nGridAlpha), Vec3(XR, y, 0), ColorB(150, 150, 150, nGridAlpha)); - } - } - } - - nGridAlpha = 60; - if (m_bAxis) - { - // Draw axis. - pRag->DrawLine(Vec3(0, 0, 0), ColorB(255, 0, 0, nGridAlpha), Vec3(XR, 0, 0), ColorB(255, 0, 0, nGridAlpha)); - pRag->DrawLine(Vec3(0, 0, 0), ColorB(0, 255, 0, nGridAlpha), Vec3(0, YR, 0), ColorB(0, 255, 0, nGridAlpha)); - pRag->DrawLine(Vec3(0, 0, 0), ColorB(0, 0, 255, nGridAlpha), Vec3(0, 0, YR), ColorB(0, 0, 255, nGridAlpha)); - } - pRag->Flush(); - pRag->SetRenderFlags(nRendFlags); -} - -void CPreviewModelCtrl::timerEvent(QTimerEvent* event) -{ - if (isVisible()) - { - if (m_bHaveAnythingToRender) - { - update(); - } - } - - QWidget::timerEvent(event); -} - -void CPreviewModelCtrl::SetCameraTM(const Matrix34& cameraTM) -{ - m_camera.SetMatrix(cameraTM); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::GetCameraTM(Matrix34& cameraTM) -{ - cameraTM = m_camera.GetMatrix(); -} - -void CPreviewModelCtrl::DeleteRenderContex() -{ - ReleaseObject(); - - // Destroy render context. - if (m_pRenderer && m_bContextCreated) - { - m_pRenderer->DeleteContext(m_hWnd); - m_bContextCreated = false; - } -} - -void CPreviewModelCtrl::OnDestroy() -{ - DeleteRenderContex(); - - if (m_nTimer) - { - killTimer(m_nTimer); - } -} - -void CPreviewModelCtrl::OnLButtonDown(QPoint point) -{ - m_bInRotateMode = true; - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; - - setFocus(); - update(); -} - -void CPreviewModelCtrl::OnLButtonUp(QPoint point) -{ - m_bInRotateMode = false; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::OnMButtonDown(QPoint point) -{ - m_bInPanMode = true; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::OnMButtonUp(QPoint point) -{ - m_bInPanMode = false; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::mouseMoveEvent(QMouseEvent* event) -{ - // TODO: Add your message handler code here and/or call default - QWidget::mouseMoveEvent(event); - - const QPoint& point = event->pos(); - if (point == m_previousMousePosition) - { - return; - } - - if (m_bInMoveMode) - { - // Zoom. - Matrix34 m = m_camera.GetMatrix(); - Vec3 xdir(0, 0, 0); - Vec3 zdir = m.GetColumn1().GetNormalized(); - - float step = 0.002f; - float dx = (point.x() - m_previousMousePosition.x()); - float dy = (point.y() - m_previousMousePosition.y()); - m_camera.SetPosition(m_camera.GetPosition() + step * xdir * dx + step * zdir * dy); - SetCamera(m_camera); - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } - else if (m_bInRotateMode) - { - Vec3 pos = m_camera.GetMatrix().GetTranslation(); - m_cameraRadius = Vec3(m_camera.GetMatrix().GetTranslation() - m_cameraTarget).GetLength(); - // Look - Ang3 angles(-point.y() + m_previousMousePosition.y(), 0, -point.x() + m_previousMousePosition.x()); - angles = angles * 0.002f; - - Matrix34 camtm = m_camera.GetMatrix(); - Matrix33 Rz = Matrix33::CreateRotationXYZ(Ang3(0, 0, angles.z)); // Rotate around vertical axis. - Matrix33 Rx = Matrix33::CreateRotationAA(angles.x, camtm.GetColumn0()); // Rotate with angle around x axis in camera space. - - Vec3 dir = camtm.TransformVector(Vec3(0, 1, 0)); - Vec3 newdir = (Rx * Rz).TransformVector(dir).GetNormalized(); - camtm = Matrix34(Matrix33::CreateRotationVDir(newdir, 0), m_cameraTarget - newdir * m_cameraRadius); - m_camera.SetMatrix(camtm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } - else if (m_bInPanMode) - { - // Slide. - float speedScale = 0.001f; - Matrix34 m = m_camera.GetMatrix(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - - Vec3 pos = m_cameraTarget; - pos += 0.1f * xdir * (point.x() - m_previousMousePosition.x()) * speedScale + 0.1f * zdir * (m_previousMousePosition.y() - point.y()) * speedScale; - m_cameraTarget = pos; - - Vec3 dir = m.TransformVector(Vec3(0, 1, 0)); - m.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(m); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } -} - -void CPreviewModelCtrl::OnRButtonDown(QPoint point) -{ - m_bInMoveMode = true; - m_mousePosition = point; - m_previousMousePosition = point; - update(); -} - -void CPreviewModelCtrl::OnRButtonUp(QPoint point) -{ - m_bInMoveMode = false; - - m_mousePosition = point; - m_previousMousePosition = point; - - update(); -} - -void CPreviewModelCtrl::wheelEvent(QWheelEvent* event) -{ - const short zDelta = event->angleDelta().y(); - // TODO: Add your message handler code here and/or call default - Matrix34 m = m_camera.GetMatrix(); - Vec3 zdir = m.GetColumn1().GetNormalized(); - - //m_camera.SetPosition( m_camera.GetPos() + ydir*(m_mousePos.y-point.y),xdir*(m_mousePos.x-point.x) ); - m_camera.SetPosition(m_camera.GetPosition() + 0.002f * zdir * (zDelta)); - SetCamera(m_camera); - update(); -} - -void CPreviewModelCtrl::EnableUpdate(bool bUpdate) -{ - m_bUpdate = bUpdate; - if (m_bUpdate && !m_nTimer) - { - m_nTimer = startTimer(1000); - } - else if (!m_bUpdate && m_nTimer) - { - killTimer(m_nTimer), m_nTimer = 0; - } -} - -void CPreviewModelCtrl::Update(bool bForceUpdate) -{ - ProcessKeys(); - - if (m_bUpdate && m_bHaveAnythingToRender || bForceUpdate) - { - if (isVisible()) - { - update(); - } - } -} - -void CPreviewModelCtrl::SetRotation(bool bEnable) -{ - m_bRotate = bEnable; -} - -void CPreviewModelCtrl::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnIdleUpdate: - Update(); - break; - } -} - -void CPreviewModelCtrl::GetImageOffscreen(CImageEx& image, const QSize& customSize) -{ - // hiding a window can cause this to be dropped, since it no longer associates with - // an actual operating system window handle. - if (!m_hWnd) - { - return; - } - if (!m_pRenderer) - { - return; - } - - m_pRenderer->EnableSwapBuffers(false); - Render(); - m_pRenderer->EnableSwapBuffers(true); - - int w; - int h; - - if (customSize.isValid()) - { - w = customSize.width(); - h = customSize.height(); - } - else - { - w = width(); - h = height(); - } - - image.Allocate(w, h); - - // the renderer will read the frame buffer of the current render context, so we need to set ours as the current before we execute this command. - SetCurrentContext(); - m_pRenderer->ReadFrameBufferFast(image.GetData(), w, h); - RestorePreviousContext(); -} - -void CPreviewModelCtrl::SetClearColor(const ColorF& color) -{ - m_clearColor = color; -} - - -namespace PreviewModelControl -{ - struct MaterialId - { - const void* ptr; - int id; - - MaterialId(const void* a_ptr, int a_id) - : ptr(a_ptr) - , id(a_id) - { - } - - bool operator<(const MaterialId& a) const - { - return ptr < a.ptr || id < a.id; - } - }; - - static int GetFaceCountRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - if (p->GetRenderMesh()) - { - n += p->GetRenderMesh()->GetIndicesCount() / 3; - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - n += GetFaceCountRecursively(pS->pStatObj); - } - } - return n; - } - - static int GetVertexCountRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - if (p->GetRenderMesh()) - { - n += p->GetRenderMesh()->GetVerticesCount(); - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - n += GetVertexCountRecursively(pS->pStatObj); - } - } - return n; - } - - static int GetMaxLodRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - for (int i = 1; i < 10; i++) - { - if (p->GetLodObject(i)) - { - n = i; - } - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - const int n2 = GetMaxLodRecursively(pS->pStatObj); - n = (n < n2) ? n2 : n; - } - } - return n; - } - - static void CollectMaterialsRecursively(std::set& mats, IStatObj* p) - { - if (!p) - { - return; - } - if (p->GetRenderMesh()) - { - TRenderChunkArray& ch = p->GetRenderMesh()->GetChunks(); - for (size_t i = 0; i < ch.size(); ++i) - { - mats.insert(PreviewModelControl::MaterialId(p->GetMaterial(), ch[i].m_nMatID)); - } - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - CollectMaterialsRecursively(mats, pS->pStatObj); - } - } - } -} - - -int CPreviewModelCtrl::GetFaceCount() -{ - if (m_pObj) - { - return PreviewModelControl::GetFaceCountRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetVertexCount() -{ - if (m_pObj) - { - return PreviewModelControl::GetVertexCountRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetMaxLod() -{ - if (m_pObj) - { - return PreviewModelControl::GetMaxLodRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetMtlCount() -{ - if (m_pObj) - { - std::set mats; - CollectMaterialsRecursively(mats, m_pObj); - return (int)mats.size(); - } - return 0; -} - -void CPreviewModelCtrl::FitToScreen() -{ - SetCameraLookAt(2.0f, Vec3(1, 1, -0.5)); -} - -void CPreviewModelCtrl::ProcessKeys() -{ - if (!hasFocus()) - { - return; - } - - int moveSpeed = 1; - - Matrix34 m = m_camera.GetMatrix(); - - Vec3 ydir = m.GetColumn2().GetNormalized(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - - Vec3 pos = m.GetTranslation(); - - float speedScale = 60.0f * GetIEditor()->GetSystem()->GetITimer()->GetFrameTime(); - if (speedScale > 20) - { - speedScale = 20; - } - - speedScale *= 0.04f; - - if (CheckVirtualKey(Qt::Key_Shift)) - { - speedScale *= gSettings.cameraFastMoveSpeed; - } - - bool isDirty = false; - - if (CheckVirtualKey(Qt::Key_Up) || CheckVirtualKey(Qt::Key_W)) - { - // move forward - m_camera.SetPosition(pos + speedScale * moveSpeed * ydir); - SetCamera(m_camera); - isDirty = true; - } - - if (CheckVirtualKey(Qt::Key_Down) || CheckVirtualKey(Qt::Key_S)) - { - // move backward - m_camera.SetPosition(pos - speedScale * moveSpeed * ydir); - SetCamera(m_camera); - isDirty = true; - } - - if (isDirty) - { - if (!m_bUpdate) - { - // if we're not going to be autoupdating then we need to do a one-time invalidation here. - update(); - } - } -} - -void CPreviewModelCtrl::SetBackgroundTexture(const QString& textureFilename) -{ - m_backgroundTextureId = GetIEditor()->GetIconManager()->GetIconTexture(textureFilename.toUtf8().constData()); -} - -void CPreviewModelCtrl::DrawBackground() -{ - if (!m_backgroundTextureId) - { - return; - } - - int rcw = width(); - int rch = height(); - - TransformationMatrices backupSceneMatrices; - - m_pRenderer->Set2DMode(rcw, rch, backupSceneMatrices, 0.0f, 1.0f); - - m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - - float uvs[4], uvt[4]; - uvs[3] = 0; - uvt[3] = 1; - uvs[2] = 1; - uvt[2] = 1; - uvs[1] = 1; - uvt[1] = 0; - uvs[0] = 0; - uvt[0] = 0; - - float color[4] = {1, 1, 1, 1}; - - m_pRenderer->DrawImageWithUV(0, 0, 0.5f, rcw, rch, m_backgroundTextureId, uvs, uvt, color[0], color[1], color[2], color[3]); - m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); - - m_pRenderer->Unset2DMode(backupSceneMatrices); -} - -_smart_ptr CPreviewModelCtrl::GetCurrentMaterial() -{ - if (m_pObj) - { - return m_pObj->GetMaterial(); - } - else if (m_pEntity) - { - return m_pEntity->GetMaterial(); - } - - return NULL; -} - -void CPreviewModelCtrl::StorePreviousContext() -{ - SPreviousContext previous; - previous.width = m_pRenderer->GetWidth(); - previous.height = m_pRenderer->GetHeight(); - previous.window = (HWND)m_pRenderer->GetCurrentContextHWND(); - previous.renderCamera = m_pRenderer->GetCamera(); - previous.systemCamera = gEnv->pSystem->GetViewCamera(); - previous.isMainViewport = m_pRenderer->IsCurrentContextMainVP(); - m_previousContexts.push_back(previous); -} - -// Copied from the non-crashing QViewport.cpp -void CPreviewModelCtrl::SetCurrentContext() -{ - StorePreviousContext(); - - m_pRenderer->SetCurrentContext(m_hWnd); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - m_pRenderer->ChangeViewport(0, 0, width() * ratio, height() * ratio); - m_pRenderer->SetCamera(m_camera); - gEnv->pSystem->SetViewCamera(m_camera); -} - -void CPreviewModelCtrl::RestorePreviousContext() -{ - if (m_previousContexts.empty()) - { - assert(0); - return; - } - - SPreviousContext x = m_previousContexts.back(); - m_previousContexts.pop_back(); - m_pRenderer->SetCurrentContext(x.window); - m_pRenderer->ChangeViewport(0, 0, x.width, x.height, x.isMainViewport); - m_pRenderer->SetCamera(x.renderCamera); - gEnv->pSystem->SetViewCamera(x.systemCamera); -} - -void CPreviewModelCtrl::showEvent([[maybe_unused]] QShowEvent* event) -{ - m_hWnd = reinterpret_cast(effectiveWinId()); -} - -QSize CPreviewModelCtrl::minimumSizeHint() const -{ - return QSize(50, 50); -} - -QPaintEngine* CPreviewModelCtrl::paintEngine() const -{ - return nullptr; -} - -void CPreviewModelCtrl::paintEvent(QPaintEvent* event) -{ - event->accept(); - Render(); -} - -void CPreviewModelCtrl::mousePressEvent(QMouseEvent* event) -{ - switch (event->button()) - { - case Qt::LeftButton: - OnLButtonDown(event->pos()); - break; - case Qt::MiddleButton: - OnMButtonDown(event->pos()); - break; - case Qt::RightButton: - OnRButtonDown(event->pos()); - break; - } -} - -void CPreviewModelCtrl::mouseReleaseEvent(QMouseEvent* event) -{ - switch (event->button()) - { - case Qt::LeftButton: - OnLButtonUp(event->pos()); - break; - case Qt::MiddleButton: - OnMButtonUp(event->pos()); - break; - case Qt::RightButton: - OnRButtonUp(event->pos()); - break; - } -} - -#include diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h deleted file mode 100644 index 6388be9fd5..0000000000 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H -#define CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include - -#include - -#endif - -struct IRenderNode; -class CImageEx; - -class CPreviewModelCtrl - : public QWidget - , public IEditorNotifyListener -{ - Q_OBJECT -public: - explicit CPreviewModelCtrl(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - - QSize minimumSizeHint() const override; - -public: - void LoadFile(const QString& modelFile, bool changeCamera = true); - Vec3 GetSize() const { return m_size; }; - QString GetLoadedFile() const { return m_loadedFile; } - - void SetEntity(IRenderNode* entity); - void SetObject(IStatObj* pObject); - IStatObj* GetObject() { return m_pObj; } - void SetCameraLookAt(float fRadiusScale, const Vec3& dir = Vec3(0, 1, 0)); - void SetCameraRadius(float fRadius); - CCamera& GetCamera(); - void SetGrid(bool bEnable) { m_bGrid = bEnable; } - void SetAxis(bool bEnable, bool forParticleEditor = false) { m_bAxis = bEnable; m_bAxisParticleEditor = forParticleEditor; } - void SetRotation(bool bEnable); - void SetClearColor(const ColorF& color); - void SetBackgroundTexture(const QString& textureFilename); - void UseBackLight(bool bEnable); - bool UseBackLight() const { return m_bUseBacklight; } - void SetShowNormals(bool bShow) { m_bShowNormals = bShow; } - void SetShowPhysics(bool bShow) { m_bShowPhysics = bShow; } - void SetShowRenderInfo(bool bShow) { m_bShowRenderInfo = bShow; } - - void EnableUpdate(bool bEnable); - bool IsUpdateEnabled() const { return m_bUpdate; } - void Update(bool bForceUpdate = false); - void ProcessKeys(); - - // this turns on and off aspect-ratio-maintaining. Use it when the widget is free to resize itself. - void SetAspectRatio(float newAspectRatio); - int heightForWidth(int w) const override; - bool hasHeightForWidth() const override; - - void GetImageOffscreen(CImageEx& image, const QSize& customSize = QSize(0, 0)); - - void GetCameraTM(Matrix34& cameraTM); - void SetCameraTM(const Matrix34& cameraTM); - - // Place camera so that whole object fits on screen. - void FitToScreen(); - - // Get information about the preview model. - int GetFaceCount(); - int GetVertexCount(); - int GetMaxLod(); - int GetMtlCount(); - - void SetShowObject(bool bShowObject) {m_bShowObject = bShowObject; } - bool GetShowObject() {return m_bShowObject; } - - void SetAmbient(ColorF amb) { m_ambientColor = amb; } - void SetAmbientMultiplier(f32 multiplier) { m_ambientMultiplier = multiplier; } - - typedef void (* CameraChangeCallback)(void* m_userData, CPreviewModelCtrl* m_currentCamera); - void SetCameraChangeCallback(CameraChangeCallback callback, void* userData) { m_cameraChangeCallback = callback, m_pCameraChangeUserData = userData; } - - void EnableMaterialPrecaching(bool bPrecacheMaterial) { m_bPrecacheMaterial = bPrecacheMaterial; } - void EnableWireframeRendering(bool bDrawWireframe) { m_bDrawWireFrame = bDrawWireframe; } - -public: - ~CPreviewModelCtrl(); - - bool CreateContext(); - void ReleaseObject(); - void DeleteRenderContex(); - -protected: - void OnCreate(); - void OnDestroy(); - void OnLButtonDown(QPoint point); - void OnLButtonUp(QPoint point); - void OnMButtonDown(QPoint point); - void OnMButtonUp(QPoint point); - void OnRButtonUp(QPoint point); - void OnRButtonDown(QPoint point); - - QPaintEngine* paintEngine() const override; - void showEvent(QShowEvent* event) override; - void paintEvent(QPaintEvent* event) override; - void timerEvent(QTimerEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void wheelEvent(QWheelEvent* event) override; - - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - -protected: - virtual bool Render(); - virtual void SetCamera(CCamera& cam); - - virtual void RenderObject(_smart_ptr pMaterial, SRenderingPassInfo& passInfo); - - HWND m_hWnd; - CCamera m_camera; - float m_fov; - - struct SPreviousContext; - std::vector m_previousContexts; - - void SetOrbitAngles(const Ang3& ang); - void DrawGrid(); - void DrawBackground(); - _smart_ptr GetCurrentMaterial(); - - _smart_ptr m_pObj; - - IRenderer* m_pRenderer; - bool m_bContextCreated; - - Vec3 m_size; - Vec3 m_pos; - int m_nTimer; - bool m_useAspectRatio = false; - float m_aspectRatio = 1.0f; - - QString m_loadedFile; - std::vector m_lights; - - AABB m_aabb; - Vec3 m_cameraTarget; - float m_cameraRadius; - Vec3 m_cameraAngles; - bool m_bInRotateMode; - bool m_bInMoveMode; - bool m_bInPanMode; - QPoint m_mousePosition; - QPoint m_previousMousePosition; - IRenderNode* m_pEntity; - bool m_bHaveAnythingToRender; - bool m_bGrid; - bool m_bAxis; - bool m_bAxisParticleEditor; - bool m_bUpdate; - bool m_bRotate; - float m_rotateAngle; - ColorF m_clearColor; - ColorF m_ambientColor; - f32 m_ambientMultiplier; - bool m_bUseBacklight; - bool m_bShowObject; - bool m_bPrecacheMaterial; - bool m_bDrawWireFrame; - bool m_bShowNormals; - bool m_bShowPhysics; - bool m_bShowRenderInfo; - int m_backgroundTextureId; - float m_tileX; - float m_tileY; - float m_tileSizeX; - float m_tileSizeY; - CameraChangeCallback m_cameraChangeCallback; - void* m_pCameraChangeUserData; - -protected: - void StorePreviousContext(); - void SetCurrentContext(); - void RestorePreviousContext(); -}; -#endif // CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H diff --git a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp b/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp deleted file mode 100644 index 9b2b62d6f5..0000000000 --- a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : implementation file - - -#include "EditorDefs.h" - -#include "TimeOfDaySlider.h" - -QString TimeOfDaySlider::hoverValueText(int sliderValue) const -{ - return QString::fromLatin1("%1:%2").arg(static_cast(sliderValue / 60)).arg(sliderValue % 60, 2, 10, QLatin1Char('0')); -} - -#include diff --git a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h b/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h deleted file mode 100644 index 72c4c08394..0000000000 --- a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H -#define CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H -#pragma once - - -#if !defined(Q_MOC_RUN) -#include -#endif - -class TimeOfDaySlider - : public AzQtComponents::SliderInt -{ - Q_OBJECT -public: - using AzQtComponents::SliderInt::SliderInt; - -protected: - QString hoverValueText(int sliderValue) const override; -}; - -#endif // CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index aa255e185d..9ad57d6581 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -78,7 +78,6 @@ AZ_POP_DISABLE_WARNING #include // CryCommon -#include #include #include #include @@ -99,7 +98,6 @@ AZ_POP_DISABLE_WARNING #include "GridSettingsDialog.h" #include "LayoutConfigDialog.h" #include "ViewManager.h" -#include "ModelViewport.h" #include "FileTypeUtils.h" #include "PluginManager.h" @@ -109,14 +107,12 @@ AZ_POP_DISABLE_WARNING #include "GameEngine.h" #include "StartupTraceHandler.h" -#include "ThumbnailGenerator.h" #include "ToolsConfigPage.h" #include "Objects/SelectionGroup.h" #include "Include/IObjectManager.h" #include "WaitProgress.h" #include "ToolBox.h" -#include "Geometry/EdMesh.h" #include "LevelInfo.h" #include "EditorPreferencesDialog.h" #include "GraphicsSettingsDialog.h" @@ -392,7 +388,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_RESAVESLICES, OnFileResaveSlices) ON_COMMAND(ID_FILE_EDITEDITORINI, OnFileEditEditorini) ON_COMMAND(ID_PREFERENCES, OnPreferences) - ON_COMMAND(ID_RELOAD_GEOMETRY, OnReloadGeometry) ON_COMMAND(ID_REDO, OnRedo) ON_COMMAND(ID_TOOLBAR_WIDGET_REDO, OnRedo) ON_COMMAND(ID_RELOAD_TEXTURES, OnReloadTextures) @@ -401,7 +396,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_NEW_SLICE, OnCreateSlice) ON_COMMAND(ID_FILE_OPEN_SLICE, OnOpenSlice) #endif - ON_COMMAND(ID_RESOURCES_GENERATECGFTHUMBNAILS, OnGenerateCgfThumbnails) ON_COMMAND(ID_SWITCH_PHYSICS, OnSwitchPhysics) ON_COMMAND(ID_GAME_SYNCPLAYER, OnSyncPlayer) ON_COMMAND(ID_RESOURCES_REDUCEWORKINGSET, OnResourcesReduceworkingset) @@ -457,7 +451,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_SAVELEVELRESOURCES, OnFileSavelevelresources) ON_COMMAND(ID_CLEAR_REGISTRY, OnClearRegistryData) ON_COMMAND(ID_VALIDATELEVEL, OnValidatelevel) - ON_COMMAND(ID_TOOLS_VALIDATEOBJECTPOSITIONS, OnValidateObjectPositions) ON_COMMAND(ID_TOOLS_PREFERENCES, OnToolsPreferences) ON_COMMAND(ID_GRAPHICS_SETTINGS, OnGraphicsSettings) ON_COMMAND(ID_SWITCHCAMERA_DEFAULTCAMERA, OnSwitchToDefaultCamera) @@ -471,8 +464,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_DISPLAY_SHOWHELPERS, OnShowHelpers) ON_COMMAND(ID_OPEN_TRACKVIEW, OnOpenTrackView) ON_COMMAND(ID_OPEN_UICANVASEDITOR, OnOpenUICanvasEditor) - ON_COMMAND(ID_TERRAIN_TIMEOFDAY, OnTimeOfDay) - ON_COMMAND(ID_TERRAIN_TIMEOFDAYBUTTON, OnTimeOfDay) ON_COMMAND_RANGE(ID_GAME_PC_ENABLELOWSPEC, ID_GAME_PC_ENABLEVERYHIGHSPEC, OnChangeGameSpec) @@ -1912,11 +1903,6 @@ void CCryEditApp::LoadFile(QString fileName) { return; } - CViewport* vp = GetIEditor()->GetViewManager()->GetView(0); - if (CModelViewport* mvp = viewport_cast(vp)) - { - mvp->LoadObject(fileName, 1); - } LoadTagLocations(); @@ -2952,43 +2938,6 @@ void CCryEditApp::OnReloadTextures() GetIEditor()->GetRenderer()->EF_ReloadTextures(); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnReloadGeometry() -{ - CErrorsRecorder errRecorder(GetIEditor()); - CWaitProgress wait("Reloading static geometry"); - - CLogFile::WriteLine("Reloading Static objects geometries."); - CEdMesh::ReloadAllGeometries(); - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_UNLOAD_GEOM); - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_RELOAD_GEOM); - GetIEditor()->Notify(eNotify_OnReloadTrackView); - - // Rephysicalize viewport meshes - for (int i = 0; i < GetIEditor()->GetViewManager()->GetViewCount(); ++i) - { - CViewport* vp = GetIEditor()->GetViewManager()->GetView(i); - if (CModelViewport* mvp = viewport_cast(vp)) - { - mvp->RePhysicalize(); - } - } - - IRenderNode** plist = new IRenderNode*[ - gEnv->p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent,0) - ]; - for (const EERType type : AZStd::array{eERType_Dummy_10, eERType_StaticMeshRenderComponent}) - { - for (int j = gEnv->p3DEngine->GetObjectsByType(type, plist) - 1; j >= 0; j--) - { - plist[j]->Physicalize(true); - } - } - delete[] plist; -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUndo() { @@ -3153,15 +3102,6 @@ void CCryEditApp::OnSyncPlayerUpdate(QAction* action) action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition()); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnGenerateCgfThumbnails() -{ - qApp->setOverrideCursor(Qt::BusyCursor); - CThumbnailGenerator gen; - gen.GenerateForDirectory("Objects\\"); - qApp->restoreOverrideCursor(); -} - void CCryEditApp::OnUpdateNonGameMode(QAction* action) { action->setEnabled(!GetIEditor()->IsInGameMode()); @@ -3263,7 +3203,6 @@ CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelNam GetIEditor()->GetGameEngine()->LoadLevel(GetIEditor()->GetGameEngine()->GetMissionName(), true, true); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - GetIEditor()->GetGameEngine()->ReloadEnvironment(); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0); } @@ -3882,119 +3821,6 @@ void CCryEditApp::OnValidatelevel() levelInfo.Validate(); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnValidateObjectPositions() -{ - IObjectManager* objMan = GetIEditor()->GetObjectManager(); - - if (!objMan) - { - return; - } - - CErrorReport errorReport; - errorReport.SetCurrentFile(""); - errorReport.SetImmediateMode(false); - - int objCount = objMan->GetObjectCount(); - AABB bbox1; - AABB bbox2; - int bugNo = 0; - QString statTxt(""); - - std::vector objects; - objMan->GetObjects(objects); - - std::vector foundObjects; - - std::vector objIDs; - - for (int i1 = 0; i1 < objCount; ++i1) - { - CBaseObject* pObj1 = objects[i1]; - - if (!pObj1) - { - continue; - } - - // Object must have geometry - if (!pObj1->GetGeometry()) - { - continue; - } - - pObj1->GetBoundBox(bbox1); - - // Check if object has other objects inside its bbox - foundObjects.clear(); - objMan->FindObjectsInAABB(bbox1, foundObjects); - - for (int i2 = 0; i2 < foundObjects.size(); ++i2) - { - CBaseObject* pObj2 = objects[i2]; - if (!pObj2) - { - continue; - } - - if (pObj2->GetId() == pObj1->GetId()) - { - continue; - } - - if (pObj2->GetParent()) - { - continue; - } - - if (stl::find(objIDs, pObj2->GetId())) - { - continue; - } - - if (!pObj2->GetGeometry()) - { - continue; - } - - pObj2->GetBoundBox(bbox2); - - if (!bbox1.IsContainPoint(bbox2.max)) - { - continue; - } - - if (!bbox1.IsContainPoint(bbox2.min)) - { - continue; - } - - objIDs.push_back(pObj2->GetId()); - - CErrorRecord error; - error.pObject = pObj2; - error.count = bugNo; - error.error = tr("%1 inside %2 object").arg(pObj2->GetName(), pObj1->GetName()); - error.description = "Object left inside other object"; - errorReport.ReportError(error); - ++bugNo; - } - - statTxt = tr("%1/%2 [Reported Objects: %3]").arg(i1).arg(objCount).arg(bugNo); - GetIEditor()->SetStatusText(statTxt); - } - - if (errorReport.GetErrorCount() == 0) - { - QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("No Errors Found")); - } - else - { - errorReport.Display(); - } -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsPreferences() { @@ -4143,12 +3969,6 @@ void CCryEditApp::OnOpenUICanvasEditor() QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnTimeOfDay() -{ - GetIEditor()->OpenView("Time Of Day"); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::SetGameSpecCheck(ESystemConfigSpec spec, ESystemConfigPlatform platform, int &nCheck, bool &enable) { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index 6faa167146..c0b26a9405 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -230,11 +230,9 @@ public: void OnFileEditEditorini(); void OnPreferences(); void OnReloadTextures(); - void OnReloadGeometry(); void OnRedo(); void OnUpdateRedo(QAction* action); void OnUpdateUndo(QAction* action); - void OnGenerateCgfThumbnails(); void OnSwitchPhysics(); void OnSwitchPhysicsUpdate(QAction* action); void OnSyncPlayer(); @@ -419,7 +417,6 @@ private: void OnFileSavelevelresources(); void OnClearRegistryData(); void OnValidatelevel(); - void OnValidateObjectPositions(); void OnToolsPreferences(); void OnGraphicsSettings(); void OnSwitchToDefaultCamera(); @@ -434,7 +431,6 @@ private: void OnOpenTrackView(); void OnOpenAudioControlsEditor(); void OnOpenUICanvasEditor(); - void OnTimeOfDay(); void OnChangeGameSpec(UINT nID); void SetGameSpecCheck(ESystemConfigSpec spec, ESystemConfigPlatform platform, int &nCheck, bool &enable); void OnUpdateGameSpec(QAction* action); diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 2138c5c79e..557341f28c 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -42,7 +42,6 @@ #include "Settings.h" #include "PluginManager.h" -#include "Mission.h" #include "ViewManager.h" #include "DisplaySettings.h" #include "GameEngine.h" @@ -57,7 +56,6 @@ #include "CheckOutDialog.h" #include "GameExporter.h" #include "MainWindow.h" -#include "ITimeOfDay.h" #include "LevelFileDialog.h" #include "StatObjBus.h" @@ -123,7 +121,6 @@ CCryEditDoc::CCryEditDoc() // The right way would require us to save to the level folder the export status of the // level. , m_boLevelExported(true) - , m_mission(NULL) , m_modified(false) , m_envProbeHeight(200.0f) , m_envProbeSliceRelativePath("EngineAssets/Slices/DefaultLevelSetup.slice") @@ -158,7 +155,6 @@ CCryEditDoc::CCryEditDoc() CCryEditDoc::~CCryEditDoc() { GetIEditor()->SetDocument(nullptr); - ClearMissions(); delete m_pLevelShaderCache; @@ -255,17 +251,6 @@ bool CCryEditDoc::Save() return OnSaveDocument(GetActivePathName()); } -void CCryEditDoc::ChangeMission() -{ - GetIEditor()->Notify(eNotify_OnMissionChange); - - // Notify listeners. - for (std::list::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnMissionChange(); - } -} - void CCryEditDoc::DeleteContents() { m_hasErrors = false; @@ -295,10 +280,6 @@ void CCryEditDoc::DeleteContents() // Delete all objects from Object Manager. GetIEditor()->GetObjectManager()->DeleteAllObjects(); - ClearMissions(); - - GetIEditor()->GetGameEngine()->ResetResources(); - // Load scripts data SetModifiedFlag(FALSE); SetModifiedModules(eModifiedNothing); @@ -341,7 +322,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) if (!isPrefabEnabled) { CAutoDocNotReady autoDocNotReady; - QString currentMissionName; if (arrXmlAr[DMAS_GENERAL] != NULL) { @@ -356,8 +336,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) // Fog settings /////////////////////////////////////////////////////// SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); - // Serialize Missions ////////////////////////////////////////////////// - SerializeMissions(arrXmlAr, currentMissionName, false); SerializeShaderCache((*arrXmlAr[DMAS_GENERAL_NAMED_DATA])); SerializeNameSelection((*arrXmlAr[DMAS_GENERAL])); @@ -404,7 +382,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) HEAP_CHECK CLogFile::FormatLine("Loading from %s...", szFilename.toUtf8().data()); - QString currentMissionName; QString szLevelPath = Path::GetPath(szFilename); { @@ -482,29 +459,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); } - HEAP_CHECK - - if (!isPrefabEnabled) - { - // multiple missions are no longer supported, only load the current mission (last used) - SerializeMissions(arrXmlAr, currentMissionName, false); - } - - HEAP_CHECK - - if (GetIEditor()->Get3DEngine()) - { - if (!isPrefabEnabled) - { - GetIEditor()->Get3DEngine()->LoadCompiledOctreeForEditor(); - } - } - - { - CAutoLogTime logtime("Game Engine level load"); - GetIEditor()->GetGameEngine()->LoadLevel(currentMissionName, true, true); - } - if (!isPrefabEnabled) { ////////////////////////////////////////////////////////////////////////// @@ -523,27 +477,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); } - { - QByteArray str; - str = tr("Activating Mission %1").arg(currentMissionName).toUtf8(); - - CAutoLogTime logtime(str.data()); - - // Select current mission. - m_mission = FindMission(currentMissionName); - - if (m_mission) - { - SyncCurrentMissionContent(true); - } - else - { - GetCurrentMission(); - } - } - - ForceSkyUpdate(); - if (!isPrefabEnabled) { // Serialize Shader Cache. @@ -730,94 +663,6 @@ void CCryEditDoc::SerializeFogSettings(CXmlArchive& xmlAr) } } -void CCryEditDoc::SerializeMissions(TDocMultiArchive& arrXmlAr, QString& currentMissionName, bool bPartsInXml) -{ - bool bLoading = IsLoadingXmlArArray(arrXmlAr); - - if (bLoading) - { - // Loading - CLogFile::WriteLine("Loading missions..."); - // Clear old layers - ClearMissions(); - // Load shared objects and layers. - XmlNodeRef objectsNode = arrXmlAr[DMAS_GENERAL]->root->findChild("Objects"); - XmlNodeRef objectLayersNode = arrXmlAr[DMAS_GENERAL]->root->findChild("ObjectLayers"); - // Load the layer count - XmlNodeRef node = arrXmlAr[DMAS_GENERAL]->root->findChild("Missions"); - - if (!node) - { - return; - } - - QString current; - node->getAttr("Current", current); - currentMissionName = current; - - // Read all node - for (int i = 0; i < node->getChildCount(); i++) - { - CXmlArchive ar(*arrXmlAr[DMAS_GENERAL]); - ar.root = node->getChild(i); - CMission* mission = new CMission(this); - mission->Serialize(ar); - if (bPartsInXml) - { - mission->SerializeTimeOfDay(*arrXmlAr[DMAS_TIME_OF_DAY]); - mission->SerializeEnvironment(*arrXmlAr[DMAS_ENVIRONMENT]); - } - else - { - mission->LoadParts(); - } - - // Timur[9/11/2002] For backward compatibility with shared objects - if (objectsNode) - { - mission->AddObjectsNode(objectsNode); - } - if (objectLayersNode) - { - mission->SetLayersNode(objectLayersNode); - } - - AddMission(mission); - } - } - else - { - // Storing - CLogFile::WriteLine("Storing missions..."); - // Save contents of current mission. - SyncCurrentMissionContent(false); - - XmlNodeRef node = arrXmlAr[DMAS_GENERAL]->root->newChild("Missions"); - - //! Store current mission name. - currentMissionName = GetCurrentMission()->GetName(); - node->setAttr("Current", currentMissionName.toUtf8().data()); - - // Write all surface types. - for (int i = 0; i < m_missions.size(); i++) - { - CXmlArchive ar(*arrXmlAr[DMAS_GENERAL]); - ar.root = node->newChild("Mission"); - m_missions[i]->Serialize(ar, false); - if (bPartsInXml) - { - m_missions[i]->SerializeTimeOfDay(*arrXmlAr[DMAS_TIME_OF_DAY]); - m_missions[i]->SerializeEnvironment(*arrXmlAr[DMAS_ENVIRONMENT]); - } - else - { - m_missions[i]->SaveParts(); - } - } - CLogFile::WriteString("Done"); - } -} - void CCryEditDoc::SerializeShaderCache(CXmlArchive& xmlAr) { if (xmlAr.bLoading) @@ -2089,58 +1934,6 @@ void CCryEditDoc::SaveAutoBackup(bool bForce) isInProgress = false; } - -CMission* CCryEditDoc::GetCurrentMission(bool bSkipLoadingAIWhenSyncingContent /* = false */) -{ - if (m_mission) - { - return m_mission; - } - - if (!m_missions.empty()) - { - // Choose first available mission. - SetCurrentMission(m_missions[0]); - return m_mission; - } - - // Create initial mission. - m_mission = new CMission(this); - m_mission->SetName("Mission0"); - AddMission(m_mission); - m_mission->SyncContent(true, false, bSkipLoadingAIWhenSyncingContent); - return m_mission; -} - -void CCryEditDoc::SetCurrentMission(CMission* mission) -{ - if (mission != m_mission) - { - QWaitCursor wait; - - if (m_mission) - { - m_mission->SyncContent(false, false); - } - - m_mission = mission; - m_mission->SyncContent(true, false); - - GetIEditor()->GetGameEngine()->LoadMission(m_mission->GetName()); - } -} - -void CCryEditDoc::ClearMissions() -{ - for (int i = 0; i < m_missions.size(); i++) - { - delete m_missions[i]; - } - - m_missions.clear(); - m_mission = 0; -} - bool CCryEditDoc::IsLevelExported() const { return m_boLevelExported; @@ -2151,37 +1944,6 @@ void CCryEditDoc::SetLevelExported(bool boExported) m_boLevelExported = boExported; } -CMission* CCryEditDoc::FindMission(const QString& name) const -{ - for (int i = 0; i < m_missions.size(); i++) - { - if (QString::compare(name, m_missions[i]->GetName(), Qt::CaseInsensitive) == 0) - { - return m_missions[i]; - } - } - return 0; -} - -void CCryEditDoc::AddMission(CMission* mission) -{ - assert(std::find(m_missions.begin(), m_missions.end(), mission) == m_missions.end()); - m_missions.push_back(mission); - GetIEditor()->Notify(eNotify_OnInvalidateControls); -} - -void CCryEditDoc::RemoveMission(CMission* mission) -{ - // if deleting current mission. - if (mission == m_mission) - { - m_mission = 0; - } - - m_missions.erase(std::find(m_missions.begin(), m_missions.end(), mission)); - GetIEditor()->Notify(eNotify_OnInvalidateControls); -} - void CCryEditDoc::RegisterListener(IDocListener* listener) { if (listener == nullptr) @@ -2287,19 +2049,6 @@ void CCryEditDoc::OnStartLevelResourceList() gEnv->pCryPak->GetResourceList(AZ::IO::IArchive::RFOM_Level)->Clear(); } -void CCryEditDoc::ForceSkyUpdate() -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine ? gEnv->p3DEngine->GetTimeOfDay() : nullptr; - CMission* pCurMission = GetIEditor()->GetDocument()->GetCurrentMission(); - - if (pTimeOfDay && pCurMission) - { - pTimeOfDay->SetTime(pCurMission->GetTime(), gSettings.bForceSkyUpdate); - pCurMission->SetTime(pCurMission->GetTime()); - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } -} - BOOL CCryEditDoc::DoFileSave() { if (GetEditMode() == CCryEditDoc::DocumentEditingMode::LevelEdit) @@ -2361,27 +2110,11 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU ////////////////////////////////////////////////////////////////////////// if (!GetIEditor()->IsInPreviewMode()) { - // Make new mission. GetIEditor()->ReloadTemplates(); m_environmentTemplate = GetIEditor()->FindTemplate("Environment"); - GetCurrentMission(true); // true = skip loading the AI in case the content needs to get synchronized (otherwise it would attempt to load AI stuff from the previously loaded level (!) which might give confusing warnings) - GetIEditor()->GetGameEngine()->SetMissionName(GetCurrentMission()->GetName()); GetIEditor()->GetGameEngine()->SetLevelCreated(true); - GetIEditor()->GetGameEngine()->ReloadEnvironment(); GetIEditor()->GetGameEngine()->SetLevelCreated(false); - - // Default time of day. - auto defaultTimeOfDayPath = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / "Assets" / "Editor" / "default_time_of_day.xml"; - XmlNodeRef root = GetISystem()->LoadXmlFromFile(defaultTimeOfDayPath.c_str()); - if (root) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine ? gEnv->p3DEngine->GetTimeOfDay() : nullptr; - if (pTimeOfDay) - { - pTimeOfDay->Serialize(root, true); - } - } } { @@ -2469,8 +2202,6 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) pVar->Get(value); childNode->setAttr("value", value.toUtf8().data()); } - - GetIEditor()->GetGameEngine()->ReloadEnvironment(); } QString CCryEditDoc::GetCryIndexPath(const LPCTSTR levelFilePath) @@ -2523,12 +2254,6 @@ void CCryEditDoc::ReleaseXmlArchiveArray(TDocMultiArchive& arrXmlAr) SAFE_DELETE(arrXmlAr[0]); } - -void CCryEditDoc::SyncCurrentMissionContent(bool bRetrieve) -{ - GetCurrentMission()->SyncContent(bRetrieve, false); -} - ////////////////////////////////////////////////////////////////////////// // AzToolsFramework::EditorEntityContextNotificationBus interface implementation void CCryEditDoc::OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, AZ::SliceComponent::SliceInstanceAddress& sliceAddress, const AzFramework::SliceInstantiationTicket& /*ticket*/) diff --git a/Code/Sandbox/Editor/CryEditDoc.h b/Code/Sandbox/Editor/CryEditDoc.h index 481e9fa046..be8a5fcec7 100644 --- a/Code/Sandbox/Editor/CryEditDoc.h +++ b/Code/Sandbox/Editor/CryEditDoc.h @@ -22,7 +22,6 @@ #include #endif -class CMission; class CLevelShaderCache; class CClouds; struct LightingSettings; @@ -124,18 +123,6 @@ public: // Create from serialization only const char* GetTemporaryLevelName() const; void DeleteTemporaryLevel(); - void ChangeMission(); - //! Return currently active Mission. - CMission* GetCurrentMission(bool bSkipLoadingAIWhenSyncingContent = false); - //! Get number of missions on Map. - int GetMissionCount() const { return m_missions.size(); } - //! Get Mission by index. - CMission* GetMission(int index) const { return m_missions[index]; } - //! Find Mission by name. - CMission* FindMission(const QString& name) const; - //! Makes specified mission current. - void SetCurrentMission(CMission* mission); - CLevelShaderCache* GetShaderCache() { return m_pLevelShaderCache; } CClouds* GetClouds() { return m_pClouds; } void SetWaterColor(const QColor& col) { m_waterColor = col; } @@ -167,7 +154,6 @@ protected: virtual void Load(TDocMultiArchive& arrXmlAr, const QString& szFilename); virtual void StartStreamingLoad(){} - virtual void SyncCurrentMissionContent(bool bRetrieve); void Save(CXmlArchive& xmlAr); void Load(CXmlArchive& xmlAr, const QString& szFilename); @@ -179,14 +165,8 @@ protected: bool LoadEntitiesFromSlice(const QString& sliceFile); void SerializeFogSettings(CXmlArchive& xmlAr); virtual void SerializeViewSettings(CXmlArchive& xmlAr); - void SerializeMissions(TDocMultiArchive& arrXmlAr, QString& currentMission, bool bPartsInXml); void SerializeShaderCache(CXmlArchive& xmlAr); void SerializeNameSelection(CXmlArchive& xmlAr); - void ForceSkyUpdate(); - //! Add new mission to map. - void AddMission(CMission* mission); - //! Remove existing mission from map. - void RemoveMission(CMission* mission); void LogLoadTime(int time); struct TSaveDocContext @@ -200,10 +180,8 @@ protected: virtual bool OnSaveDocument(const QString& lpszPathName); virtual void OnFileSaveAs(); - void LoadTemplates(); //! called immediately after saving the level. void AfterSave(); - void ClearMissions(); void RegisterConsoleVariables(); void OnStartLevelResourceList(); static void OnValidateSurfaceTypesChanged(ICVar*); @@ -220,9 +198,7 @@ protected: QColor m_waterColor; XmlNodeRef m_fogTemplate; XmlNodeRef m_environmentTemplate; - CMission* m_mission; CClouds* m_pClouds; - std::vector m_missions; std::list m_listeners; bool m_bDocumentReady; CLevelShaderCache* m_pLevelShaderCache; diff --git a/Code/Sandbox/Editor/DisplaySettings.cpp b/Code/Sandbox/Editor/DisplaySettings.cpp index 75e5c54ae9..6454471a80 100644 --- a/Code/Sandbox/Editor/DisplaySettings.cpp +++ b/Code/Sandbox/Editor/DisplaySettings.cpp @@ -86,11 +86,6 @@ void CDisplaySettings::PostInitApply() void CDisplaySettings::SetRenderFlags(int flags) { m_renderFlags = flags; - - if (!GetIEditor()->Get3DEngine()) - { - return; - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/EditorDefs.h b/Code/Sandbox/Editor/EditorDefs.h index dd86bdf07a..8c78e9644f 100644 --- a/Code/Sandbox/Editor/EditorDefs.h +++ b/Code/Sandbox/Editor/EditorDefs.h @@ -132,7 +132,6 @@ #include #include #include -#include #include #include #include diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 05986d6561..61cfea0894 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -54,7 +54,6 @@ #include // CryCommon -#include #include // AzFramework @@ -97,6 +96,10 @@ #include +#include +#include +#include + AZ_CVAR( bool, ed_visibility_logTiming, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Output the timing of the new IVisibilitySystem query"); @@ -250,11 +253,6 @@ void EditorViewportWidget::resizeEvent(QResizeEvent* event) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - if (gEnv->pRenderer) - { - gEnv->pRenderer->EF_DisableTemporalEffects(); - } - // We queue the window resize event because the render overlay may be hidden. // If the render overlay is not visible, the native window that is backing it will // also be hidden, and it will not resize until it becomes visible. @@ -520,9 +518,6 @@ void EditorViewportWidget::Update() // Render { // TODO: Move out this logic to a controller and refactor to work with Atom - // m_renderer->SetClearColor(Vec3(0.4f, 0.4f, 0.4f)); - // 3D engine stats - GetIEditor()->GetSystem()->RenderBegin(); OnRender(); @@ -547,8 +542,6 @@ void EditorViewportWidget::Update() } } - GetIEditor()->GetSystem()->RenderEnd(m_bRenderStats); - gEnv->pSystem->SetViewCamera(CurCamera); } @@ -1556,7 +1549,6 @@ void EditorViewportWidget::ToggleCameraObject() { if (m_viewSourceType == ViewSourceType::SequenceCamera) { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); ResetToViewSourceType(ViewSourceType::LegacyCamera); } else @@ -2136,17 +2128,23 @@ bool EditorViewportWidget::AdjustObjectPosition(const ray_hit& hit, Vec3& outNor ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const { - SRayHitInfo hitInfo; + AZ_UNUSED(pRenderMesh); + AZ_UNUSED(vInPos); + AZ_UNUSED(vInDir); + AZ_UNUSED(vOutPos); + AZ_UNUSED(vOutNormal); + return false; + /*SRayHitInfo hitInfo; hitInfo.bUseCache = false; hitInfo.bInFirstHit = false; hitInfo.inRay.origin = vInPos; hitInfo.inRay.direction = vInDir.GetNormalized(); hitInfo.inReferencePoint = vInPos; hitInfo.fMaxHitDistance = 0; - bool bRes = GetIEditor()->Get3DEngine()->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); + bool bRes = ???->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); vOutPos = hitInfo.vHitPos; vOutNormal = hitInfo.vHitNormal; - return bRes; + return bRes;*/ } void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const @@ -2417,10 +2415,6 @@ void EditorViewportWidget::SetDefaultCamera() return; } ResetToViewSourceType(ViewSourceType::None); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); - } GetViewManager()->SetCameraObjectId(m_cameraObjectId); SetName(m_defaultViewName); SetViewTM(m_defaultViewTM); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.h b/Code/Sandbox/Editor/EditorViewportWidget.h index 8673d258cc..09474200f1 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.h +++ b/Code/Sandbox/Editor/EditorViewportWidget.h @@ -481,10 +481,6 @@ protected: OBB m_GroundOBB; Vec3 m_GroundOBBPos; - //------------------------------------------- - // Render options. - bool m_bRenderStats = true; - // Index of camera objects. mutable GUID m_cameraObjectId; mutable AZ::EntityId m_viewEntityId; diff --git a/Code/Sandbox/Editor/EnvironmentPanel.cpp b/Code/Sandbox/Editor/EnvironmentPanel.cpp deleted file mode 100644 index f71babbff6..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "EnvironmentPanel.h" - -// Editor -#include "GameEngine.h" -#include "CryEditDoc.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -///////////////////////////////////////////////////////////////////////////// -// CEnvironmentPanel dialog - -CEnvironmentPanel::CEnvironmentPanel(QWidget* pParent /*=nullptr*/) - : QWidget(pParent) - , ui(new Ui::CEnvironmentPanel) -{ - XmlNodeRef node = GetIEditor()->GetDocument()->GetEnvironmentTemplate(); - - m_onSetCallback = AZStd::bind(&CCryEditDoc::OnEnvironmentPropertyChanged, GetIEditor()->GetDocument(), AZStd::placeholders::_1); - - ui->setupUi(this); - ui->m_wndProps->Setup(); - ui->m_wndProps->CreateItems(node, m_varBlock, &m_onSetCallback, true); - ui->m_wndProps->RebuildCtrl(false); - ui->m_wndProps->ExpandAll(); - connect(ui->APPLYBTN, &QPushButton::clicked, this, &CEnvironmentPanel::OnBnClickedApply); -} - -CEnvironmentPanel::~CEnvironmentPanel() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CEnvironmentPanel::OnBnClickedApply() -{ - GetIEditor()->GetGameEngine()->ReloadEnvironment(); -} diff --git a/Code/Sandbox/Editor/EnvironmentPanel.h b/Code/Sandbox/Editor/EnvironmentPanel.h deleted file mode 100644 index ff4594a502..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H -#define CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H - -#pragma once -// EnvironmentPanel.h : header file -// - -#include "Util/Variable.h" - -#include -#include - -///////////////////////////////////////////////////////////////////////////// -// CEnvironmentPanel dialog -namespace Ui { - class CEnvironmentPanel; -} - -class CEnvironmentPanel - : public QWidget -{ - // Construction -public: - CEnvironmentPanel(QWidget* pParent = nullptr); // standard constructor - ~CEnvironmentPanel(); - - // Implementation -protected: - CVarBlockPtr m_varBlock; - -public: - void OnBnClickedApply(); - -private: - QScopedPointer ui; - - IVariable::OnSetCallback m_onSetCallback; -}; - -#endif // CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H diff --git a/Code/Sandbox/Editor/EnvironmentPanel.ui b/Code/Sandbox/Editor/EnvironmentPanel.ui deleted file mode 100644 index b808fc93fc..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.ui +++ /dev/null @@ -1,56 +0,0 @@ - - - CEnvironmentPanel - - - - 0 - 0 - 264 - 259 - - - - - - - - 0 - 200 - - - - - - - - Apply - - - - - - - Qt::Horizontal - - - - 162 - 20 - - - - - - - - - ReflectedPropertyControl - QWidget -
Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h
- 1 -
-
- - -
diff --git a/Code/Sandbox/Editor/Export/ExportManager.cpp b/Code/Sandbox/Editor/Export/ExportManager.cpp index ddb8a38870..2d0f784647 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.cpp +++ b/Code/Sandbox/Editor/Export/ExportManager.cpp @@ -22,7 +22,6 @@ #include // Editor -#include "Geometry/EdGeometry.h" #include "ViewManager.h" #include "OBJExporter.h" #include "OCMExporter.h" @@ -41,6 +40,9 @@ #include "Resource.h" #include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h" +#include +#include + namespace { void SetTexture(Export::TPath& outName, IRenderShaderResources* pRes, int nSlot) @@ -494,53 +496,6 @@ bool CExportManager::AddStatObj(Export::CObject* pObj, IStatObj* pStatObj, Matri bool CExportManager::AddMeshes(Export::CObject* pObj) { - CEdGeometry* pEdGeom = m_pBaseObj->GetGeometry(); - IIndexedMesh* pIndMesh = 0; - - if (pEdGeom) - { - size_t idx = 0; - size_t nextIdx = 0; - do - { - pIndMesh = 0; - if (m_isOccluder) - { - if (pEdGeom->GetIStatObj() && pEdGeom->GetIStatObj()->GetLodObject(2)) - { - pIndMesh = pEdGeom->GetIStatObj()->GetLodObject(2)->GetIndexedMesh(true); - } - if (!pIndMesh && pEdGeom->GetIStatObj() && pEdGeom->GetIStatObj()->GetLodObject(1)) - { - pIndMesh = pEdGeom->GetIStatObj()->GetLodObject(1)->GetIndexedMesh(true); - } - } - - if (!pIndMesh) - { - pIndMesh = pEdGeom->GetIndexedMesh(idx); - nextIdx++; - } - - if (!pIndMesh) - { - break; - } - - Matrix34 tm; - pEdGeom->GetTM(&tm, idx); - Matrix34A objTM = tm; - AddMesh(pObj, pIndMesh, &objTM); - idx = nextIdx; - } - while (pIndMesh && idx); - - if (idx > 0) - { - return true; - } - } - if (m_pBaseObj->GetType() == OBJTYPE_AZENTITY) { CEntityObject* pEntityObject = (CEntityObject*)m_pBaseObj; @@ -548,11 +503,7 @@ bool CExportManager::AddMeshes(Export::CObject* pObj) if (pEngineNode) { - if (m_isPrecaching) - { - GetIEditor()->Get3DEngine()->PrecacheRenderNode(pEngineNode, 0); - } - else + if (!m_isPrecaching) { for (int i = 0; i < pEngineNode->GetSlotCount(); ++i) { @@ -1115,8 +1066,6 @@ bool CExportManager::AddSelectedRegionObjects() AddObject(objects[i]); } - GetIEditor()->Get3DEngine()->ProposeContentPrecache(); - // Repeat pipeline to collect geometry m_isPrecaching = false; for (size_t i = 0; i < numObjects; ++i) diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index d5aec9e7d4..6c1bef7a68 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -34,15 +34,11 @@ // Editor #include "IEditorImpl.h" #include "CryEditDoc.h" -#include "Geometry/EdMesh.h" -#include "Mission.h" #include "Settings.h" // CryCommon -#include #include #include -#include #include #include @@ -283,7 +279,6 @@ AZ_POP_DISABLE_WARNING AZ::Interface::Unregister(this); GetIEditor()->UnregisterNotifyListener(this); m_pISystem->GetIMovieSystem()->SetCallback(NULL); - CEdMesh::ReleaseAll(); if (m_gameDll) { @@ -493,13 +488,6 @@ AZ::Outcome CGameEngine::Init( SetEditorCoreEnvironment(gEnv); - if (gEnv - && gEnv->p3DEngine - && gEnv->p3DEngine->GetTimeOfDay()) - { - gEnv->p3DEngine->GetTimeOfDay()->BeginEditMode(); - } - if (gEnv && gEnv->pMovieSystem) { gEnv->pMovieSystem->EnablePhysicsEvents(m_bSimulationMode); @@ -549,11 +537,6 @@ void CGameEngine::SetLevelPath(const QString& path) { m_levelExtension = defaultExtension; } - - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->SetLevelPath(m_levelPath.toUtf8().data()); - } } void CGameEngine::SetMissionName(const QString& mission) @@ -607,24 +590,11 @@ bool CGameEngine::LoadLevel( } - // Load level in 3d engine. - if (gEnv->p3DEngine && !gEnv->p3DEngine->InitLevelForEditor(m_levelPath.toUtf8().data(), m_missionName.toUtf8().data())) - { - CLogFile::WriteLine("ERROR: Can't load level !"); - QMessageBox::critical(QApplication::activeWindow(), QString(), QObject::tr("ERROR: Can't load level !")); - return false; - } - // Audio: notify audio of level loading start? GetIEditor()->GetObjectManager()->SendEvent(EVENT_REFRESH); m_bLevelLoaded = true; - if (!bReleaseResources) - { - ReloadEnvironment(); - } - return true; } @@ -638,61 +608,8 @@ bool CGameEngine::ReloadLevel() return true; } -bool CGameEngine::LoadMission(const QString& mission) -{ - if (!IsLevelLoaded()) - { - return false; - } - - if (mission != m_missionName) - { - m_missionName = mission; - gEnv->p3DEngine->LoadMissionDataFromXMLNode(m_missionName.toUtf8().data()); - } - - return true; -} - -bool CGameEngine::ReloadEnvironment() -{ - if (!gEnv->p3DEngine) - { - return false; - } - - if (!IsLevelLoaded() && !m_bJustCreated) - { - return false; - } - - if (!GetIEditor()->GetDocument()) - { - return false; - } - - XmlNodeRef env = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(GetIEditor()->GetDocument()->GetEnvironmentTemplate(), env); - - // Notify mission that environment may be changed. - GetIEditor()->GetDocument()->GetCurrentMission()->OnEnvironmentChange(); - - QString xmlStr = QString::fromLatin1(env->getXML()); - - // Reload level data in engine. - gEnv->p3DEngine->LoadEnvironmentSettingsFromXML(env); - - return true; -} - void CGameEngine::SwitchToInGame() { - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->DisablePostEffects(); - gEnv->p3DEngine->ResetPostEffects(); - } - auto streamer = AZ::Interface::Get(); if (streamer) { @@ -707,11 +624,6 @@ void CGameEngine::SwitchToInGame() m_pISystem->SetThreadState(ESubsys_Physics, false); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->ResetParticlesAndDecals(); - } - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; @@ -721,10 +633,6 @@ void CGameEngine::SwitchToInGame() pRuler->SetActive(false); } - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetTimeOfDay()->EndEditMode(); - } gEnv->pSystem->GetViewCamera().SetMatrix(m_playerViewTM); // Disable accelerators. @@ -760,24 +668,9 @@ void CGameEngine::SwitchToInEditor() m_pISystem->SetThreadState(ESubsys_Physics, false); - if (gEnv->p3DEngine) - { - // Reset 3d engine effects - gEnv->p3DEngine->DisablePostEffects(); - gEnv->p3DEngine->ResetPostEffects(); - gEnv->p3DEngine->ResetParticlesAndDecals(); - } - CViewport* pGameViewport = GetIEditor()->GetViewManager()->GetGameViewport(); m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(m_bSimulationMode); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetTimeOfDay()->BeginEditMode(); - - // this has to be done before the RemoveSink() call, or else some entities may not be removed - gEnv->p3DEngine->GetDeferredPhysicsEventManager()->ClearDeferredEvents(); - } // Enable accelerators. GetIEditor()->EnableAcceleratos(true); @@ -865,7 +758,6 @@ void CGameEngine::SetGameMode(bool bInGame) // Ignore updates while changing in and out of game mode m_bIgnoreUpdates = true; - LockResources(); // Switching modes will destroy the current AzFramework::EntityConext which may contain // data the queued events hold on to, so execute all queued events before switching. @@ -891,7 +783,6 @@ void CGameEngine::SetGameMode(bool bInGame) GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_GAME_MODE_CHANGED, bInGame, 0); - UnlockResources(); m_bIgnoreUpdates = false; GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_GAME_MODE_SWITCH_END, bInGame, 0); @@ -906,11 +797,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(enabled); - if (!bOnlyPhysics) - { - LockResources(); - } - if (enabled) { CRuler* pRuler = GetIEditor()->GetRuler(); @@ -935,35 +821,12 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) if (m_bSimulationMode) { - if (!bOnlyPhysics) - { - if (m_pISystem->GetI3DEngine()) - { - m_pISystem->GetI3DEngine()->ResetPostEffects(); - } - - GetIEditor()->SetConsoleVar("ai_ignoreplayer", 1); - //GetIEditor()->SetConsoleVar( "ai_soundperception",0 ); - } - // [Anton] the order of the next 3 calls changed, since, EVENT_INGAME loads physics state (if any), // and Reset should be called before it GetIEditor()->GetObjectManager()->SendEvent(EVENT_INGAME); } else { - if (!bOnlyPhysics) - { - GetIEditor()->SetConsoleVar("ai_ignoreplayer", 0); - //GetIEditor()->SetConsoleVar( "ai_soundperception",1 ); - - if (m_pISystem->GetI3DEngine()) - { - m_pISystem->GetI3DEngine()->ResetPostEffects(); - } - } - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_OUTOFGAME); } @@ -983,23 +846,9 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) AzToolsFramework::EditorEntityContextRequestBus::Broadcast(&AzToolsFramework::EditorEntityContextRequestBus::Events::StartPlayInEditor); } - if (!bOnlyPhysics) - { - UnlockResources(); - } - AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState); } -void CGameEngine::ResetResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->UnloadLevel(); - } - -} - void CGameEngine::SetPlayerViewMatrix(const Matrix34& tm, [[maybe_unused]] bool bEyePos) { m_playerViewTM = tm; @@ -1107,24 +956,6 @@ void CGameEngine::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { - case eNotify_OnBeginNewScene: - case eNotify_OnBeginSceneOpen: - { - ResetResources(); - } - break; - case eNotify_OnEndSceneOpen: - case eNotify_OnEndTerrainRebuild: - { - } - case eNotify_OnEndNewScene: // intentional fall-through? - { - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - } - break; case eNotify_OnSplashScreenDestroyed: { if (m_pSystemUserCallback != NULL) @@ -1136,22 +967,6 @@ void CGameEngine::OnEditorNotifyEvent(EEditorNotifyEvent event) } } -void CGameEngine::LockResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LockCGFResources(); - } -} - -void CGameEngine::UnlockResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->UnlockCGFResources(); - } -} - void CGameEngine::OnTerrainModified(const Vec2& modPosition, float modAreaRadius, bool fullTerrain) { INavigationSystem* pNavigationSystem = nullptr; // INavigationSystem will be converted to an AZInterface (LY-111343) diff --git a/Code/Sandbox/Editor/GameEngine.h b/Code/Sandbox/Editor/GameEngine.h index 366ec42f72..c660f971f2 100644 --- a/Code/Sandbox/Editor/GameEngine.h +++ b/Code/Sandbox/Editor/GameEngine.h @@ -94,10 +94,6 @@ public: bool bReleaseResources); //!* Reload level if it was already loaded. bool ReloadLevel(); - //! Load new mission. - bool LoadMission(const QString& mission); - //! Reload environment settings in currently loaded level. - bool ReloadEnvironment(); //! Request to switch In/Out of game mode on next update. //! The switch will happen when no sub systems are currently being updated. //! @param inGame When true editor switch to game mode. @@ -142,9 +138,6 @@ public: //! Called every frame. void Update(); virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - void LockResources(); - void UnlockResources(); - void ResetResources(); void OnTerrainModified(const Vec2& modPosition, float modAreaRadius, bool fullTerrain); void OnAreaModified(const AABB& modifiedArea); diff --git a/Code/Sandbox/Editor/GameExporter.cpp b/Code/Sandbox/Editor/GameExporter.cpp index 64e1fc6514..31f3fafe84 100644 --- a/Code/Sandbox/Editor/GameExporter.cpp +++ b/Code/Sandbox/Editor/GameExporter.cpp @@ -24,7 +24,6 @@ #include "GameExporter.h" #include "GameEngine.h" #include "CryEditDoc.h" -#include "Mission.h" #include "ShaderCache.h" #include "UsedResources.h" #include "WaitProgress.h" @@ -131,13 +130,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE m_levelPath = Path::RemoveBackslash(sLevelPath); QString rootLevelPath = Path::AddSlash(pGameEngine->GetLevelPath()); - // Make sure we unload any unused CGFs before exporting so that they don't end up in - // the level data. - if (pEditor->Get3DEngine()) - { - pEditor->Get3DEngine()->FreeUnusedCGFResources(); - } - CCryEditDoc* pDocument = pEditor->GetDocument(); if (flags & eExp_Fast) @@ -191,8 +183,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE //////////////////////////////////////////////////////////////////////// if (exportSuccessful) { - ExportVisAreas(sLevelPath.toUtf8().data(), eExportEndian); - //////////////////////////////////////////////////////////////////////// // Exporting map setttings //////////////////////////////////////////////////////////////////////// @@ -254,47 +244,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE return exportSuccessful; } - -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportVisAreas(const char* pszGamePath, EEndian eExportEndian) -{ - char szFileOutputPath[_MAX_PATH]; - - // export visareas - IEditor* pEditor = GetIEditor(); - - // remove old files - sprintf_s(szFileOutputPath, "%s%s", pszGamePath, COMPILED_VISAREA_MAP_FILE_NAME); - m_levelPak.m_pakFile.RemoveFile(szFileOutputPath); - - SHotUpdateInfo exportInfo; - I3DEngine* p3DEngine = pEditor->Get3DEngine(); - - if (p3DEngine && (eExportEndian == GetPlatformEndian())) // skip second export, this data is common for PC and consoles - { - std::vector* pTempBrushTable = NULL; - std::vector<_smart_ptr>* pTempMatsTable = NULL; - std::vector* pTempVegGroupTable = NULL; - - // export visareas - CLogFile::WriteLine("Exporting indoors..."); - pEditor->SetStatusText("Exporting indoors..."); - if (IVisAreaManager* pVisAreaManager = p3DEngine->GetIVisAreaManager()) - { - if (int nSize = pVisAreaManager->GetCompiledDataSize()) - { // get visareas data from 3dengine and save it into file - uint8* pData = new uint8[nSize]; - pVisAreaManager->GetCompiledData(pData, nSize, &pTempBrushTable, &pTempMatsTable, &pTempVegGroupTable, eExportEndian); - sprintf_s(szFileOutputPath, "%s%s", pszGamePath, COMPILED_VISAREA_MAP_FILE_NAME); - CCryMemFile visareasCompiledFile; - visareasCompiledFile.Write(pData, nSize); - m_levelPak.m_pakFile.UpdateFile(szFileOutputPath, visareasCompiledFile); - delete[] pData; - } - } - } -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportOcclusionMesh(const char* pszGamePath) { @@ -319,7 +268,7 @@ void CGameExporter::ExportOcclusionMesh(const char* pszGamePath) } ////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) +void CGameExporter::ExportLevelData(const QString& path, bool /*bExportMission*/) { IEditor* pEditor = GetIEditor(); pEditor->SetStatusText(QObject::tr("Exporting LevelData.xml...")); @@ -332,49 +281,6 @@ void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) XmlNodeRef rootAction = XmlHelpers::CreateXmlNode("LevelDataAction"); rootAction->setAttr("SandboxVersion", versionString); - ExportMapInfo(root); - - CCryEditDoc* pDocument = pEditor->GetDocument(); - CMission* pCurrentMission = 0; - - if (bExportMission) - { - pCurrentMission = pDocument->GetCurrentMission(); - // Save contents of current mission. - } - - ////////////////////////////////////////////////////////////////////////// - // Export missions tag. - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef missionsNode = rootAction->newChild("Missions"); - QString missionFileName; - QString currentMissionFileName; - I3DEngine* p3DEngine = pEditor->Get3DEngine(); - if (p3DEngine) - { - for (int i = 0; i < pDocument->GetMissionCount(); i++) - { - CMission* pMission = pDocument->GetMission(i); - - QString name = pMission->GetName(); - name.replace(' ', '_'); - missionFileName = QStringLiteral("Mission_%1.xml").arg(name); - - XmlNodeRef missionDescNode = missionsNode->newChild("Mission"); - missionDescNode->setAttr("Name", pMission->GetName().toUtf8().data()); - missionDescNode->setAttr("File", missionFileName.toUtf8().data()); - missionDescNode->setAttr("CGFCount", p3DEngine->GetLoadedObjectCount()); - - int nProgressBarRange = m_numExportedMaterials / 10 + p3DEngine->GetLoadedObjectCount(); - missionDescNode->setAttr("ProgressBarRange", nProgressBarRange); - - if (pMission == pCurrentMission) - { - currentMissionFileName = missionFileName; - } - } - } - ////////////////////////////////////////////////////////////////////////// // Save Level Data XML ////////////////////////////////////////////////////////////////////////// @@ -389,41 +295,6 @@ void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) CCryMemFile fileAction; fileAction.Write(xmlDataAction.c_str(), xmlDataAction.length()); m_levelPak.m_pakFile.UpdateFile(levelDataActionFile.toUtf8().data(), fileAction); - - if (bExportMission) - { - XmlNodeRef objectsNode = NULL; - ////////////////////////////////////////////////////////////////////////// - // Export current mission file. - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef missionNode = rootAction->createNode("Mission"); - pCurrentMission->Export(missionNode, objectsNode); - - if (p3DEngine) - { - missionNode->setAttr("CGFCount", p3DEngine->GetLoadedObjectCount()); - } - - //if (!CFileUtil::OverwriteFile( path+currentMissionFileName )) - // return; - - AZStd::vector entitySaveBuffer; - AZ::IO::ByteContainerStream > entitySaveStream(&entitySaveBuffer); - bool savedEntities = false; - EBUS_EVENT_RESULT(savedEntities, AzToolsFramework::EditorEntityContextRequestBus, SaveToStreamForGame, entitySaveStream, AZ::DataStream::ST_BINARY); - if (savedEntities) - { - QString entitiesFile; - entitiesFile = QStringLiteral("%1%2.entities_xml").arg(path, pCurrentMission ? pCurrentMission->GetName() : ""); - m_levelPak.m_pakFile.UpdateFile(entitiesFile.toUtf8().data(), entitySaveBuffer.begin(), entitySaveBuffer.size()); - } - - _smart_ptr pXmlStrData = missionNode->getXMLData(5000000); - - CCryMemFile fileMission; - fileMission.Write(pXmlStrData->GetString(), pXmlStrData->GetStringLength()); - m_levelPak.m_pakFile.UpdateFile((path + currentMissionFileName).toUtf8().data(), fileMission); - } } ////////////////////////////////////////////////////////////////////////// @@ -446,18 +317,6 @@ void CGameExporter::ExportLevelInfo(const QString& path) const int compiledHeightmapSize = static_cast(terrainAabb.GetXExtent() / terrainGridResolution.GetX()); root->setAttr("HeightmapSize", compiledHeightmapSize); - // Save all missions in this level. - XmlNodeRef missionsNode = root->newChild("Missions"); - int numMissions = pEditor->GetDocument()->GetMissionCount(); - for (int i = 0; i < numMissions; i++) - { - CMission* pMission = pEditor->GetDocument()->GetMission(i); - XmlNodeRef missionNode = missionsNode->newChild("Mission"); - missionNode->setAttr("Name", pMission->GetName().toUtf8().data()); - missionNode->setAttr("Description", pMission->GetDescription().toUtf8().data()); - } - - ////////////////////////////////////////////////////////////////////////// // Save LevelInfo file. ////////////////////////////////////////////////////////////////////////// @@ -469,38 +328,6 @@ void CGameExporter::ExportLevelInfo(const QString& path) m_levelPak.m_pakFile.UpdateFile(filename.toUtf8().data(), file); } -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportMapInfo(XmlNodeRef& node) -{ - if (!GetIEditor()->Get3DEngine()) - { - return; - } - - XmlNodeRef info = node->newChild("LevelInfo"); - - IEditor* pEditor = GetIEditor(); - info->setAttr("Name", QFileInfo(pEditor->GetDocument()->GetTitle()).completeBaseName()); - - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero()); - const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainGridResolution() : AZ::Vector2::CreateOne(); - - const int terrainSizeInMeters = static_cast(terrainAabb.GetXExtent()); - const int terrainUnitSizeInMeters = static_cast(terrainGridResolution.GetX()); - info->setAttr("HeightmapSize", terrainSizeInMeters / terrainUnitSizeInMeters); - info->setAttr("HeightmapUnitSize", terrainUnitSizeInMeters); - //! Default Max Height value. - constexpr int HEIGHTMAP_MAX_HEIGHT = 150; //This is the default max height in CHeightmap - info->setAttr("HeightmapMaxHeight", HEIGHTMAP_MAX_HEIGHT); - info->setAttr("WaterLevel", pEditor->Get3DEngine()->GetWaterLevel()); - - // Serialize surface types. - CXmlArchive xmlAr; - xmlAr.bLoading = false; - xmlAr.root = node; -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportLevelResourceList(const QString& path) { diff --git a/Code/Sandbox/Editor/GameExporter.h b/Code/Sandbox/Editor/GameExporter.h index a428046f0a..18ec79189a 100644 --- a/Code/Sandbox/Editor/GameExporter.h +++ b/Code/Sandbox/Editor/GameExporter.h @@ -91,9 +91,7 @@ private: void ExportLevelData(const QString& path, bool bExportMission = true); void ExportLevelInfo(const QString& path); - void ExportVisAreas(const char* pszGamePath, EEndian eExportEndian); void ExportOcclusionMesh(const char* pszGamePath); - void ExportMapInfo(XmlNodeRef& node); void ExportLevelResourceList(const QString& path); void ExportLevelUsedResourceList(const QString& path); diff --git a/Code/Sandbox/Editor/Geometry/EdGeometry.cpp b/Code/Sandbox/Editor/Geometry/EdGeometry.cpp deleted file mode 100644 index 13e8dd96ba..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdGeometry.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "EdGeometry.h" diff --git a/Code/Sandbox/Editor/Geometry/EdGeometry.h b/Code/Sandbox/Editor/Geometry/EdGeometry.h deleted file mode 100644 index 3def344a35..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdGeometry.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H -#define CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H -#pragma once - -struct IIndexedMesh; -struct DisplayContext; -struct HitContext; -struct SSubObjSelectionModifyContext; -class CObjectArchive; - -// Basic supported geometry types. -enum EEdGeometryType -{ - GEOM_TYPE_MESH = 0, // Mesh geometry. - GEOM_TYPE_BRUSH, // Solid brush geometry. - GEOM_TYPE_PATCH, // Bezier patch surface geometry. - GEOM_TYPE_NURB, // Nurbs surface geometry. -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// CEdGeometry is a base class for all supported editable geometries. -////////////////////////////////////////////////////////////////////////// -class CRYEDIT_API CEdGeometry - : public CRefCountBase -{ -public: - CEdGeometry() {}; - - // Query the type of the geometry mesh. - virtual EEdGeometryType GetType() const = 0; - - // Serialize geometry. - virtual void Serialize(CObjectArchive& ar) = 0; - - // Return geometry axis aligned bounding box. - virtual void GetBounds(AABB& box) = 0; - - // Clones Geometry, returns exact copy of the original geometry. - virtual CEdGeometry* Clone() = 0; - - // Access to the indexed mesh. - // Return false if geometry can not be represented by an indexed mesh. - virtual IIndexedMesh* GetIndexedMesh(size_t idx = 0) = 0; - virtual IStatObj* GetIStatObj() const = 0; - virtual void GetTM(Matrix34* pTM, size_t idx = 0) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Advanced geometry interface for SubObject selection and modification. - ////////////////////////////////////////////////////////////////////////// - virtual void SetModified(bool bModified = true) = 0; - virtual bool IsModified() const = 0; - virtual bool StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, int nFlags) = 0; - virtual void EndSubObjSelection() = 0; - - // Display geometry for sub object selection. - virtual void Display(DisplayContext& dc) = 0; - - // Sub geometry hit testing and selection. - virtual bool HitTest(HitContext& hit) = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void ModifySelection(SSubObjSelectionModifyContext& modCtx, bool isUndo = true) = 0; - // Called when selection modification is accepted. - virtual void AcceptModifySelection() = 0; - -protected: - ~CEdGeometry() {}; -}; - -#endif // CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H diff --git a/Code/Sandbox/Editor/Geometry/EdMesh.cpp b/Code/Sandbox/Editor/Geometry/EdMesh.cpp deleted file mode 100644 index 466c07ece7..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdMesh.cpp +++ /dev/null @@ -1,1548 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of CEdMesh class. - - -#include "EditorDefs.h" - -// CryCommon -#include - -// Editor -#include "EdMesh.h" -#include "Viewport.h" -#include "ViewManager.h" -#include "Util/PakFile.h" -#include "Include/HitContext.h" -#include "Include/ITransformManipulator.h" -#include "Objects/ObjectLoader.h" -#include "Undo/IUndoObject.h" -#include "Util/fastlib.h" - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -//! Undo object for Editable Mesh. -class CUndoEdMesh - : public IUndoObject -{ -public: - CUndoEdMesh(CEdMesh* pEdMesh, int nCopyFlags, const char* undoDescription) - { - // Stores the current state of this object. - assert(pEdMesh != 0); - m_nCopyFlags = nCopyFlags; - m_undoDescription = undoDescription; - m_pEdMesh = pEdMesh; - pEdMesh->CopyToMesh(undoMesh, nCopyFlags); - } -protected: - virtual int GetSize() - { - // sizeof(undoMesh) + sizeof(redoMesh); - return sizeof(*this); - } - virtual QString GetDescription() { return m_undoDescription; }; - - virtual void Undo(bool bUndo) - { - if (bUndo) - { - m_pEdMesh->CopyToMesh(redoMesh, m_nCopyFlags); - } - // Undo object state. - m_pEdMesh->CopyFromMesh(undoMesh, m_nCopyFlags, bUndo); - } - virtual void Redo() - { - m_pEdMesh->CopyFromMesh(redoMesh, m_nCopyFlags, true); - } - -private: - QString m_undoDescription; - int m_nCopyFlags; - _smart_ptr m_pEdMesh; - CTriMesh undoMesh; - CTriMesh redoMesh; -}; - -////////////////////////////////////////////////////////////////////////// -// Static member of CEdMesh. -////////////////////////////////////////////////////////////////////////// -CEdMesh::MeshMap CEdMesh::m_meshMap; - -////////////////////////////////////////////////////////////////////////// -CEdMesh::CEdMesh() -{ - m_pStatObj = 0; - m_pSubObjCache = 0; - m_nUserCount = 0; - m_bModified = false; -} - - -////////////////////////////////////////////////////////////////////////// -CEdMesh::CEdMesh(IStatObj* pGeom) -{ - assert(pGeom); - if (pGeom) - { - m_pStatObj = pGeom; - m_pStatObj->AddRef(); - } - m_pSubObjCache = 0; - m_nUserCount = 0; - m_bModified = false; -} - -////////////////////////////////////////////////////////////////////////// -CEdMesh::~CEdMesh() -{ - for (auto ppIndexedMeshes = m_tempIndexedMeshes.begin(); ppIndexedMeshes != m_tempIndexedMeshes.end(); ++ppIndexedMeshes) - { - SAFE_RELEASE(*ppIndexedMeshes); - } - - SAFE_RELEASE(m_pStatObj); - // Remove this object from map. - m_meshMap.erase(m_filename); - if (m_pSubObjCache) - { - if (m_pSubObjCache->pTriMesh) - { - delete m_pSubObjCache->pTriMesh; - } - delete m_pSubObjCache; - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Serialize(CObjectArchive& ar) -{ - if (ar.bUndo) - { - return; - } - if (ar.bLoading) - { - } - else - { - if (m_bModified) - { - CBaseObject* pObj = ar.GetCurrentObject(); - if (pObj) - { - QString levelPath = Path::AddPathSlash(GetIEditor()->GetLevelFolder()); - CPakFile* pPakFile = ar.GetGeometryPak((levelPath + "\\Geometry.pak").toUtf8().data()); - if (pPakFile) - { - SaveToCGF(m_filename.toUtf8().data(), pPakFile); - } - } - SetModified(false); - } - } -} - -////////////////////////////////////////////////////////////////////////// -// CEdMesh implementation. -////////////////////////////////////////////////////////////////////////// -CEdMesh* CEdMesh::LoadMesh(const char* filename) -{ - if (strlen(filename) == 0) - { - return 0; - } - - // If object created see if its not yet registered. - CEdMesh* pMesh = stl::find_in_map(m_meshMap, filename, (CEdMesh*)0); - if (pMesh) - { - // Found, return it. - return pMesh; - } - - // Make new. - IStatObj* pGeom = GetIEditor()->Get3DEngine()->LoadStatObjUnsafeManualRef(filename); - if (!pGeom) - { - return 0; - } - - // Not found, Make new. - pMesh = new CEdMesh(pGeom); - pMesh->m_filename = filename; - m_meshMap[filename] = pMesh; - return pMesh; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::AddUser() -{ - m_nUserCount++; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::RemoveUser() -{ - m_nUserCount--; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ReloadAllGeometries() -{ - for (MeshMap::iterator it = m_meshMap.begin(); it != m_meshMap.end(); ++it) - { - CEdMesh* pMesh = it->second; - if (pMesh) - { - pMesh->ReloadGeometry(); - } - } -} - -void CEdMesh::ReleaseAll() -{ - m_meshMap.clear(); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ReloadGeometry() -{ - // Reload mesh. - if (m_pStatObj) - { - m_pStatObj->Refresh(FRO_GEOMETRY); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsSameObject(const char* filename) -{ - return QString::compare(m_filename, filename, Qt::CaseInsensitive) == 0; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::GetBounds(AABB& box) -{ - assert(m_pStatObj); - - if (m_pStatObj) - { - box.min = m_pStatObj->GetBoxMin(); - box.max = m_pStatObj->GetBoxMax(); - } -} - -////////////////////////////////////////////////////////////////////////// -CEdGeometry* CEdMesh::Clone() -{ - if (m_pStatObj) - { - // Clone StatObj. - IStatObj* pStatObj = m_pStatObj->Clone(true, true, false); - pStatObj->AddRef(); - CEdMesh* pNewMesh = new CEdMesh(pStatObj); - return pNewMesh; - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetFilename(const QString& filename) -{ - if (!m_filename.isEmpty()) - { - m_meshMap.erase(m_filename); - } - m_filename = Path::MakeGamePath(filename); - m_meshMap[m_filename] = this; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Render(SRendParams& rp, const SRenderingPassInfo& passInfo) -{ - if (m_pStatObj) - { - m_pStatObj->Render(rp, passInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsDefaultObject() -{ - if (m_pStatObj) - { - return m_pStatObj->IsDefaultObject(); - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -IIndexedMesh* CEdMesh::GetIndexedMesh(size_t idx) -{ - if (m_tempIndexedMeshes.size() == 0 && m_pStatObj) - { - if (m_pStatObj->GetIndexedMesh()) - { - if (idx == 0) - { - return m_pStatObj->GetIndexedMesh(); - } - - return nullptr; - } - else - { - // Load from CGF. - QString sFilename = m_pStatObj->GetFilePath(); - CContentCGF cgf(sFilename.toUtf8().data()); - if (gEnv->p3DEngine->LoadChunkFileContent(&cgf, sFilename.toUtf8().data())) - { - for (int i = 0; i < cgf.GetNodeCount(); ++i) - { - CNodeCGF* pNode = cgf.GetNode(i); - if (pNode->type == CNodeCGF::NODE_MESH) - { - CMesh* pMesh = pNode->pMesh; - if (pMesh) - { - IIndexedMesh* pTempIndexedMesh = GetIEditor()->Get3DEngine()->CreateIndexedMesh(); - pTempIndexedMesh->SetMesh(*pMesh); - m_tempIndexedMeshes.push_back(pTempIndexedMesh); - - Matrix34 tm = pNode->localTM; - CNodeCGF* pParent = pNode->pParent; - while (pParent) - { - tm = pParent->localTM * tm; - pParent = pParent->pParent; - } - m_tempMatrices.push_back(tm); - } - } - } - } - } - } - - if (idx < m_tempIndexedMeshes.size()) - { - return m_tempIndexedMeshes[idx]; - } - - return nullptr; -} - -void CEdMesh::GetTM(Matrix34* pTM, size_t idx) -{ - if (idx < m_tempMatrices.size()) - { - *pTM = m_tempMatrices[idx]; - } - else - { - pTM->SetIdentity(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::AcceptModifySelection() -{ - // Implement - UpdateIndexedMeshFromCache(true); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::UpdateIndexedMeshFromCache(bool bFast) -{ - // Implement - if (m_pSubObjCache) - { - if (bFast) - { - if (g_SubObjSelOptions.displayType == SO_DISPLAY_GEOMETRY) - { - m_pSubObjCache->pTriMesh->UpdateIndexedMesh(GetIndexedMesh()); - if (m_pStatObj) - { - m_pStatObj->Invalidate(); - } - } - } - else - { - m_pSubObjCache->pTriMesh->UpdateIndexedMesh(GetIndexedMesh()); - if (m_pStatObj) - { - m_pStatObj->Invalidate(); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, [[maybe_unused]] int nFlags) -{ - IIndexedMesh* pIndexedMesh = GetIndexedMesh(); - if (!pIndexedMesh) - { - return false; - } - CMesh& mesh = *pIndexedMesh->GetMesh(); - - if (!m_pSubObjCache) - { - m_pSubObjCache = new SubObjCache; - } - m_pSubObjCache->worldTM = nodeWorldTM; - m_pSubObjCache->invWorldTM = nodeWorldTM.GetInverted(); - - if (!m_pSubObjCache->pTriMesh) - { - m_pSubObjCache->pTriMesh = new CTriMesh; - m_pSubObjCache->pTriMesh->SetFromMesh(mesh); - } - UpdateSubObjCache(); - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - triMesh.selectionType = elemType; - - m_pSubObjCache->bNoDisplay = false; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetModified(bool bModified) -{ - if (m_pSubObjCache && bModified) - { - // Update xformed vertices. - UpdateSubObjCache(); - } - m_bModified = bModified; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::UpdateSubObjCache() -{ - Matrix34& wtm = m_pSubObjCache->worldTM; - - SetWorldTM(wtm); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::EndSubObjSelection() -{ - if (!m_pSubObjCache) - { - return; - } - - UpdateIndexedMeshFromCache(false); - - if (m_pSubObjCache->pTriMesh) - { - delete m_pSubObjCache->pTriMesh; - } - delete m_pSubObjCache; - m_pSubObjCache = 0; - - if (m_pStatObj) - { - if (m_bModified) - { - m_pStatObj->Invalidate(true); - } - // Clear hidden flag from geometry. - m_pStatObj->SetFlags(m_pStatObj->GetFlags() & (~STATIC_OBJECT_HIDDEN)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Display(DisplayContext& dc) -{ - if (!m_pSubObjCache || m_pSubObjCache->bNoDisplay) - { - return; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - if (!triMesh.pWSVertices) - { - return; - } - - if (m_pStatObj) - { - int nStatObjFlags = m_pStatObj->GetFlags(); - if (g_SubObjSelOptions.displayType == SO_DISPLAY_GEOMETRY) - { - nStatObjFlags &= ~STATIC_OBJECT_HIDDEN; - } - else - { - nStatObjFlags |= STATIC_OBJECT_HIDDEN; - } - m_pStatObj->SetFlags(nStatObjFlags); - } - - const Matrix34& worldTM = m_pSubObjCache->worldTM; - Vec3 vWSCameraVector = m_pSubObjCache->worldTM.GetTranslation() - dc.view->GetViewTM().GetTranslation(); - Vec3 vOSCameraVector = m_pSubObjCache->invWorldTM.TransformVector(vWSCameraVector).GetNormalized(); // Object space camera vector. - - // Render geometry vertices. - uint32 nPrevState = dc.GetState(); - - ////////////////////////////////////////////////////////////////////////// - // Calculate front facing vertices. - ////////////////////////////////////////////////////////////////////////// - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - triMesh.frontFacingVerts.clear(); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (vOSCameraVector.Dot(face.normal) < 0) - { - triMesh.frontFacingVerts[face.v[0]] = true; - triMesh.frontFacingVerts[face.v[1]] = true; - triMesh.frontFacingVerts[face.v[2]] = true; - } - } - - ////////////////////////////////////////////////////////////////////////// - // Display flat shaded object. - ////////////////////////////////////////////////////////////////////////// - if (g_SubObjSelOptions.displayType == SO_DISPLAY_FLAT) - { - ColorB faceColor(0, 250, 250, 255); - ColorB col = faceColor; - dc.SetDrawInFrontMode(false); - dc.SetFillMode(e_FillModeSolid); - dc.CullOn(); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (triMesh.selectionType != SO_ELEM_FACE || !triMesh.faceSel[i]) - { - ColorB col2 = faceColor; - float dt = -face.normal.Dot(vOSCameraVector); - dt = max(0.4f, dt); - dt = min(1.0f, dt); - col2.r = ftoi(faceColor.r * dt); - col2.g = ftoi(faceColor.g * dt); - col2.b = ftoi(faceColor.b * dt); - col2.a = faceColor.a; - dc.pRenderAuxGeom->DrawTriangle( - triMesh.pWSVertices[face.v[0]], col2, - triMesh.pWSVertices[face.v[1]], col2, - triMesh.pWSVertices[face.v[2]], col2 - ); - } - } - } - - // Draw selected triangles. - ColorB edgeColor(255, 255, 255, 155); - if (triMesh.StreamHaveSelection(CTriMesh::FACES)) - { - if (g_SubObjSelOptions.bDisplayBackfacing) - { - dc.CullOff(); - } - else - { - dc.CullOn(); - } - dc.SetDrawInFrontMode(true); - dc.SetFillMode(e_FillModeWireframe); - // Draw triangles. - //dc.pRenderAuxGeom->DrawTriangles( triMesh.pVertices,triMesh.GetVertexCount(), mesh.m_pIndices,mesh.GetIndexCount(),edgeColor ); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (!triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle( - triMesh.pWSVertices[face.v[0]], edgeColor, - triMesh.pWSVertices[face.v[1]], edgeColor, - triMesh.pWSVertices[face.v[2]], edgeColor - ); - } - } - } - - if (g_SubObjSelOptions.bDisplayNormals) - { - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - Vec3 p1 = triMesh.pWSVertices[face.v[0]]; - Vec3 p2 = triMesh.pWSVertices[face.v[1]]; - Vec3 p3 = triMesh.pWSVertices[face.v[2]]; - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - dc.pRenderAuxGeom->DrawLine(midp, edgeColor, midp + worldTM.TransformVector(face.normal) * g_SubObjSelOptions.fNormalsLength, edgeColor); - } - } - - if (triMesh.selectionType == SO_ELEM_VERTEX || triMesh.StreamHaveSelection(CTriMesh::VERTICES)) - { - ColorB pointColor(0, 255, 255, 255); - - float fClrAdd = (g_SubObjSelOptions.bSoftSelection) ? 0 : 1; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - bool bSelected = triMesh.vertSel[i] || triMesh.pWeights[i] != 0; - if (bSelected) - { - int clr = (triMesh.pWeights[i] + fClrAdd) * 255; - dc.pRenderAuxGeom->DrawPoint(triMesh.pWSVertices[i], ColorB(clr, 255 - clr, 255 - clr, 255), 8); - } - else if (!g_SubObjSelOptions.bDisplayBackfacing || triMesh.frontFacingVerts[i]) - { - dc.pRenderAuxGeom->DrawPoint(triMesh.pWSVertices[i], pointColor, 5); - } - } - } - - // Draw edges. - if (triMesh.selectionType == SO_ELEM_EDGE || triMesh.StreamHaveSelection(CTriMesh::EDGES)) - { - ColorB edgeColor2(200, 255, 200, 255); - ColorB selEdgeColor(255, 0, 0, 255); - - // Draw selected edges. - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - CTriEdge& edge = triMesh.pEdges[i]; - if (triMesh.edgeSel[i]) - { - const Vec3& p1 = triMesh.pWSVertices[edge.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[edge.v[1]]; - dc.pRenderAuxGeom->DrawLine(p1, selEdgeColor, p2, selEdgeColor, 6); - } - else if (!g_SubObjSelOptions.bDisplayBackfacing || ( - triMesh.frontFacingVerts[edge.v[0]] && triMesh.frontFacingVerts[edge.v[1]])) - { - const Vec3& p1 = triMesh.pWSVertices[edge.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[edge.v[1]]; - dc.pRenderAuxGeom->DrawLine(p1, edgeColor2, p2, edgeColor2); - } - } - } - - if (triMesh.selectionType == SO_ELEM_FACE) - { - ColorB pointColor(0, 255, 255, 255); - ColorB selFaceColor(255, 0, 0, 180); - - // Draw selected faces and face points. - dc.CullOff(); - dc.SetFillMode(e_FillModeSolid); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - const Vec3& p1 = triMesh.pWSVertices[face.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[face.v[1]]; - const Vec3& p3 = triMesh.pWSVertices[face.v[2]]; - if (triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle(p1, selFaceColor, p2, selFaceColor, p3, selFaceColor); - } - - if (!g_SubObjSelOptions.bDisplayBackfacing && vOSCameraVector.Dot(face.normal) > 0) - { - continue; // Backfacing. - } - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - dc.pRenderAuxGeom->DrawPoint(midp, pointColor, 4); - } - } - else if (triMesh.StreamHaveSelection(CTriMesh::FACES)) - { - ColorB pointColor(0, 255, 255, 255); - ColorB selFaceColor(255, 0, 0, 180); - - // Draw selected faces and face points. - dc.CullOff(); - dc.SetFillMode(e_FillModeSolid); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - const Vec3& p1 = triMesh.pWSVertices[face.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[face.v[1]]; - const Vec3& p3 = triMesh.pWSVertices[face.v[2]]; - if (triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle(p1, selFaceColor, p2, selFaceColor, p3, selFaceColor); - } - } - } - - dc.SetState(nPrevState); // Restore render state. -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestVertex(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - // This make sure that bit array size matches num vertices, front facing should be calculated in Display method. - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - - float minDist = FLT_MAX; - int closestElem = -1; - - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (env.bIgnoreBackfacing && !triMesh.frontFacingVerts[i]) - { - continue; - } - QPoint p = hit.view->WorldToView(triMesh.pWSVertices[i]); - if (p.x() >= hit.rect.left() && p.x() <= hit.rect.right() && - p.y() >= hit.rect.top() && p.y() <= hit.rect.bottom()) - { - if (env.bHitTestNearest) - { - float dist = env.vWSCameraPos.GetDistance(triMesh.pWSVertices[i]); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - else - { - result.elems.push_back(i); - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = minDist; - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestEdge(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - // This make sure that bit array size matches num vertices, front facing should be calculated in Display method. - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - - float minDist = FLT_MAX; - int closestElem = -1; - - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - CTriEdge& edge = triMesh.pEdges[i]; - if (!env.bIgnoreBackfacing || - (triMesh.frontFacingVerts[edge.v[0]] && triMesh.frontFacingVerts[edge.v[1]])) - { - if (hit.view->HitTestLine(triMesh.pWSVertices[edge.v[0]], triMesh.pWSVertices[edge.v[1]], hit.point2d, 5)) - { - if (env.bHitTestNearest) - { - float dist = env.vWSCameraPos.GetDistance(triMesh.pWSVertices[edge.v[0]]); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - else - { - result.elems.push_back(i); - } - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = minDist; - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestFace(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - float minDist = FLT_MAX; - int closestElem = -1; - - Vec3 vOut(0, 0, 0); - Ray hitRay(hit.raySrc, hit.rayDir); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - - if (env.bIgnoreBackfacing && env.vOSCameraVector.Dot(face.normal) > 0) - { - continue; // Back facing. - } - Vec3 p1 = triMesh.pWSVertices[face.v[0]]; - Vec3 p2 = triMesh.pWSVertices[face.v[1]]; - Vec3 p3 = triMesh.pWSVertices[face.v[2]]; - - if (!env.bHitTestNearest) - { - // Hit test face middle point in rectangle. - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - - QPoint p = hit.view->WorldToView(midp); - if (p.x() >= hit.rect.left() && p.x() <= hit.rect.right() && - p.y() >= hit.rect.top() && p.y() <= hit.rect.bottom()) - { - result.elems.push_back(i); - } - } - else - { - // Hit test ray/triangle. - if (Intersect::Ray_Triangle(hitRay, p1, p3, p2, vOut)) - { - float dist = hitRay.origin.GetSquaredDistance(vOut); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = (float)sqrt(minDist); - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::SelectSubObjElements(SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - bool bSelChanged = false; - if (env.bSelectOnHit && !result.elems.empty()) - { - CBitArray* streamSel = triMesh.GetStreamSelection(result.stream); - if (streamSel) - { - // Select on hit. - for (int i = 0, num = result.elems.size(); i < num; i++) - { - int elem = result.elems[i]; - if ((*streamSel)[elem] != env.bSelectValue) - { - bSelChanged = true; - (*streamSel)[elem] = env.bSelectValue; - } - } - if (bSelChanged) - { - if (env.bSelectValue) - { - triMesh.streamSelMask |= (1 << result.stream); - } - else if (!env.bSelectValue && streamSel->is_zero()) - { - triMesh.streamSelMask &= ~(1 << result.stream); - } - } - } - } - return bSelChanged; -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsHitTestResultSelected(SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - if (!result.elems.empty()) - { - CBitArray* streamSel = triMesh.GetStreamSelection(result.stream); - if (streamSel) - { - // check if first result element is selected. - if ((*streamSel)[ result.elems[0] ]) - { - return true; - } - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTest(HitContext& hit) -{ - if (hit.nSubObjFlags & SO_HIT_NO_EDIT) - // This is for a 'move-by-face-normal'. Prepare the mesh and set the 'bNoDisplay'to true - // so that the normal rendering happens instead of the edit-mode rendering. - { - StartSubObjSelection(hit.object->GetWorldTM(), SO_ELEM_FACE, 0); - m_pSubObjCache->bNoDisplay = true; - } - - if (!m_pSubObjCache) - { - return false; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - SSubObjHitTestEnvironment env; - env.vWSCameraPos = hit.view->GetViewTM().GetTranslation(); - env.vWSCameraVector = m_pSubObjCache->worldTM.GetTranslation() - hit.view->GetViewTM().GetTranslation(); - env.vOSCameraVector = m_pSubObjCache->invWorldTM.TransformVector(env.vWSCameraVector).GetNormalized(); // Object space camera vector. - - env.bHitTestNearest = hit.nSubObjFlags & SO_HIT_POINT; - env.bHitTestSelected = hit.nSubObjFlags & SO_HIT_TEST_SELECTED; - env.bSelectOnHit = hit.nSubObjFlags & SO_HIT_SELECT; - env.bAdd = hit.nSubObjFlags & SO_HIT_SELECT_ADD; - env.bRemove = hit.nSubObjFlags & SO_HIT_SELECT_REMOVE; - env.bSelectValue = !env.bRemove; - env.bHighlightOnly = hit.nSubObjFlags & SO_HIT_HIGHLIGHT_ONLY; - env.bIgnoreBackfacing = g_SubObjSelOptions.bIgnoreBackfacing && !env.bHitTestNearest; - - int nHitTestWhat = (hit.nSubObjFlags & SO_HIT_ELEM_ALL); - if (nHitTestWhat == 0) - { - if (g_SubObjSelOptions.bSelectByVertex) - { - nHitTestWhat |= SO_HIT_ELEM_VERTEX; - } - switch (triMesh.selectionType) - { - case SO_ELEM_VERTEX: - nHitTestWhat |= SO_HIT_ELEM_VERTEX; - break; - case SO_ELEM_EDGE: - nHitTestWhat |= SO_HIT_ELEM_EDGE; - break; - case SO_ELEM_FACE: - nHitTestWhat |= SO_HIT_ELEM_FACE; - break; - case SO_ELEM_POLYGON: - nHitTestWhat |= SO_HIT_ELEM_POLYGON; - break; - } - } - - IUndoObject* pUndoObj = NULL; - if (env.bSelectOnHit) - { - if (CUndo::IsRecording() && !(hit.nSubObjFlags & SO_HIT_NO_EDIT)) - { - switch (triMesh.selectionType) - { - case SO_ELEM_VERTEX: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_VERT_SEL | CTriMesh::COPY_WEIGHTS, "Select Vertex(s)"); - break; - case SO_ELEM_EDGE: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_EDGE_SEL | CTriMesh::COPY_WEIGHTS, "Select Edge(s)"); - break; - case SO_ELEM_FACE: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_FACE_SEL | CTriMesh::COPY_WEIGHTS, "Select Face(s)"); - break; - } - } - } - - bool bSelChanged = false; - bool bAnyHit = false; - ////////////////////////////////////////////////////////////////////////// - if (env.bSelectOnHit && !env.bAdd && !env.bRemove) - { - bSelChanged = triMesh.ClearSelection(); - } - ////////////////////////////////////////////////////////////////////////// - - SSubObjHitTestResult result[4]; - result[0].stream = CTriMesh::VERTICES; - result[1].stream = CTriMesh::EDGES; - result[2].stream = CTriMesh::FACES; - - if (nHitTestWhat & SO_HIT_ELEM_VERTEX) - { - if (HitTestVertex(hit, env, result[0])) - { - bAnyHit = true; - } - } - - if (nHitTestWhat & SO_HIT_ELEM_EDGE) - { - if (HitTestEdge(hit, env, result[1])) - { - bAnyHit = true; - } - } - - if (nHitTestWhat & SO_HIT_ELEM_FACE) - { - if (HitTestFace(hit, env, result[2])) - { - bAnyHit = true; - } - } - - if (bAnyHit && !env.bSelectOnHit && !env.bHitTestSelected) - { - // Return distance to the first hit element. - hit.dist = min(min(result[0].minDistance, result[1].minDistance), result[2].minDistance); - return true; - } - if (bAnyHit && !env.bSelectOnHit && env.bHitTestSelected) - { - // check if we hit selected item. - if (IsHitTestResultSelected(result[0]) || - IsHitTestResultSelected(result[1]) || - IsHitTestResultSelected(result[2])) - { - hit.dist = min(min(result[0].minDistance, result[1].minDistance), result[2].minDistance); - return true; - } - // If not hit selected. - return false; - } - if (bAnyHit) - { - // Find closest hit. - int n = 0; - if (!result[0].elems.empty()) - { - n = 0; - } - else if (!result[1].elems.empty()) - { - n = 1; - } - else if (!result[2].elems.empty()) - { - n = 2; - } - - hit.dist = result[n].minDistance; - - if (env.bSelectOnHit && - g_SubObjSelOptions.bSelectByVertex && - !result[0].elems.empty() && - !env.bHighlightOnly && - triMesh.selectionType != SO_HIT_ELEM_VERTEX) - { - // When selecting elements by vertex. - switch (triMesh.selectionType) - { - case SO_ELEM_EDGE: - n = 1; - triMesh.GetEdgesByVertex(result[0].elems, result[1].elems); - break; - case SO_ELEM_FACE: - n = 2; - triMesh.GetFacesByVertex(result[0].elems, result[2].elems); - break; - case SO_ELEM_POLYGON: - n = 2; - triMesh.GetFacesByVertex(result[0].elems, result[2].elems); - break; - } - } - if (env.bSelectOnHit && SelectSubObjElements(env, result[n])) - { - bSelChanged = true; - } - } - if (bSelChanged) - { - hit.nSubObjFlags |= SO_HIT_SELECTION_CHANGED; - } - else - { - hit.nSubObjFlags &= ~SO_HIT_SELECTION_CHANGED; - } - - bool bSelectionNotEmpty = false; - if (env.bSelectOnHit && bSelChanged && !env.bHighlightOnly) - { - if (CUndo::IsRecording() && pUndoObj) - { - CUndo::Record(pUndoObj); - } - - bSelectionNotEmpty = triMesh.UpdateSelection(); - if (g_SubObjSelOptions.bSoftSelection) - { - triMesh.SoftSelection(g_SubObjSelOptions); - } - - OnSelectionChange(); - } - else - { - if (pUndoObj) - { - pUndoObj->Release(); - } - } - - return bSelectionNotEmpty; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::OnSelectionChange() -{ - Matrix34 localRefFrame; - if (!GetSelectionReferenceFrame(localRefFrame)) - { - GetIEditor()->ShowTransformManipulator(false); - } - else - { - ITransformManipulator* pManipulator = GetIEditor()->ShowTransformManipulator(true); - - // In local space orient axis gizmo by first object. - localRefFrame = m_pSubObjCache->worldTM * localRefFrame; - - Matrix34 parentTM = m_pSubObjCache->worldTM; - Matrix34 userTM = GetIEditor()->GetViewManager()->GetGrid()->GetMatrix(); - parentTM.SetTranslation(localRefFrame.GetTranslation()); - userTM.SetTranslation(localRefFrame.GetTranslation()); - //tm.SetTranslation( m_selectionCenter ); - pManipulator->SetTransformation(COORDS_LOCAL, localRefFrame); - pManipulator->SetTransformation(COORDS_PARENT, parentTM); - pManipulator->SetTransformation(COORDS_USERDEFINED, userTM); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::GetSelectionReferenceFrame(Matrix34& refFrame) -{ - if (!m_pSubObjCache) - { - return false; - } - - bool bAnySelected = false; - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - Vec3 normal(0, 0, 0); - - refFrame.SetIdentity(); - - if (triMesh.selectionType == SO_ELEM_VERTEX) - { - // Average all selected vertex normals. - int numNormals = 0; - int nFaces = triMesh.GetFacesCount(); - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (triMesh.vertSel[i]) - { - bAnySelected = true; - int nVertexIndex = i; - for (int j = 0; j < nFaces; j++) - { - CTriFace& face = triMesh.pFaces[j]; - for (int k = 0; k < 3; k++) - { - if (face.v[k] == nVertexIndex) - { - normal += face.n[k]; - numNormals++; - } - } - } - } - } - if (numNormals > 0) - { - normal = normal / numNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - else if (triMesh.selectionType == SO_ELEM_EDGE) - { - int nNormals = 0; - // Average face normals of a the selected edges. - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - if (triMesh.edgeSel[i]) - { - bAnySelected = true; - CTriEdge& edge = triMesh.pEdges[i]; - for (int j = 0; j < 2; j++) - { - if (edge.face[j] >= 0) - { - normal = normal + triMesh.pFaces[edge.face[j]].normal; - nNormals++; - } - } - } - } - if (nNormals > 0) - { - normal = normal / nNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - else if (triMesh.selectionType == SO_ELEM_FACE) - { - // Average all face normals. - int nNormals = 0; - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - if (triMesh.faceSel[i]) - { - bAnySelected = true; - CTriFace& face = triMesh.pFaces[i]; - normal = normal + face.normal; - nNormals++; - } - } - if (nNormals > 0) - { - normal = normal / nNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - - if (bAnySelected) - { - Vec3 pos(0, 0, 0); - int numSel = 0; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (triMesh.pWeights[i] == 1.0f) - { - pos = pos + triMesh.pVertices[i].pos; - numSel++; - } - } - if (numSel > 0) - { - pos = pos / numSel; // Average position. - } - refFrame.SetTranslation(pos); - - if (!normal.IsZero()) - { - Vec3 xAxis(1, 0, 0), yAxis(0, 1, 0), zAxis(0, 0, 1); - if (normal.IsEquivalent(zAxis) || normal.IsEquivalent(-zAxis)) - { - zAxis = xAxis; - } - xAxis = normal.Cross(zAxis).GetNormalized(); - yAxis = xAxis.Cross(normal).GetNormalized(); - refFrame.SetFromVectors(xAxis, yAxis, normal, pos); - } - } - - return bAnySelected; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ModifySelection(SSubObjSelectionModifyContext& modCtx, [[maybe_unused]] bool isUndo) -{ - if (!m_pSubObjCache) - { - return; - } - - IIndexedMesh* pIndexedMesh = GetIndexedMesh(); - if (!pIndexedMesh) - { - return; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - if (modCtx.type == SO_MODIFY_UNSELECT) - { - IUndoObject* pUndoObj = NULL; - if (CUndo::IsRecording()) - { - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_VERT_SEL | CTriMesh::COPY_WEIGHTS, "Move Vertices"); - } - bool bChanged = triMesh.ClearSelection(); - if (bChanged) - { - OnSelectionChange(); - } - if (CUndo::IsRecording() && bChanged) - { - CUndo::Record(pUndoObj); - } - else if (pUndoObj) - { - pUndoObj->Release(); - } - return; - } - - Matrix34 worldTM = m_pSubObjCache->worldTM; - Matrix34 invTM = worldTM.GetInverted(); - - // Change modify reference frame to object space. - Matrix34 modRefFrame = invTM * modCtx.worldRefFrame; - Matrix34 modRefFrameInverse = modCtx.worldRefFrame.GetInverted() * worldTM; - - if (modCtx.type == SO_MODIFY_MOVE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Move Vertices")); - } - - Vec3 vOffset = modCtx.vValue; - vOffset = modCtx.worldRefFrame.GetInverted().TransformVector(vOffset); // Offset in local space. - - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Matrix34 tm = modRefFrame * Matrix34::CreateTranslationMat(vOffset * triMesh.pWeights[i]) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - OnSelectionChange(); - } - else if (modCtx.type == SO_MODIFY_ROTATE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Rotate Vertices")); - } - - Ang3 angles = Ang3(modCtx.vValue); - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Matrix34 tm = modRefFrame * Matrix33::CreateRotationXYZ(angles * triMesh.pWeights[i]) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - } - else if (modCtx.type == SO_MODIFY_SCALE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Scale Vertices")); - } - - Vec3 vScale = modCtx.vValue; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Vec3 scl = Vec3(1.0f, 1.0f, 1.0f) * (1.0f - triMesh.pWeights[i]) + vScale * triMesh.pWeights[i]; - Matrix34 tm = modRefFrame * Matrix33::CreateScale(scl) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - } - - SetModified(); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::CopyToMesh(CTriMesh& toMesh, int nCopyFlags) -{ - if (!m_pSubObjCache) - { - return; - } - - toMesh.Copy(*m_pSubObjCache->pTriMesh, nCopyFlags); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::CopyFromMesh(CTriMesh& fromMesh, int nCopyFlags, bool bUndo) -{ - if (m_pSubObjCache) - { - m_pSubObjCache->pTriMesh->Copy(fromMesh, nCopyFlags); - } - else - { - /* - CMesh mesh; - CTriMesh triMesh; - triMesh.Copy( fromMesh ); - trimesh.void CopyToMeshFast( CMesh &mesh ); - */ - } - if (bUndo) - { - UpdateIndexedMeshFromCache(true); - OnSelectionChange(); - } - - if (m_pSubObjCache) - { - UpdateSubObjCache(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SaveToCGF(const char* sFilename, CPakFile* pPakFile, _smart_ptr pMaterial) -{ - if (m_pStatObj) - { - // Save this EdMesh to CGF file. - m_filename = Path::MakeGamePath(sFilename); - - _smart_ptr pOriginalMaterial = m_pStatObj->GetMaterial(); - if (pMaterial) - { - m_pStatObj->SetMaterial(pMaterial); - } - - if (!pPakFile) - { - m_pStatObj->SaveToCGF(sFilename); - } - else - { - IChunkFile* pChunkFile = NULL; - if (m_pStatObj->SaveToCGF(sFilename, &pChunkFile)) - { - void* pMemFile = NULL; - int nFileSize = 0; - - pChunkFile->WriteToMemoryBuffer(&pMemFile, &nFileSize); - pPakFile->UpdateFile(sFilename, pMemFile, nFileSize, true, AZ::IO::INestedArchive::LEVEL_FASTER); - pChunkFile->Release(); - } - } - - // Restore original material. - if (pMaterial) - { - m_pStatObj->SetMaterial(pOriginalMaterial); - } - } -} - -////////////////////////////////////////////////////////////////////////// -CTriMesh* CEdMesh::GetMesh() -{ - if (m_pSubObjCache) - { - return m_pSubObjCache->pTriMesh; - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -CEdMesh* CEdMesh::CreateMesh(const char* name) -{ - IStatObj* pStatObj = gEnv->p3DEngine->CreateStatObj(); - if (pStatObj) - { - CEdMesh* pEdMesh = new CEdMesh; - pEdMesh->m_pStatObj = pStatObj; - pEdMesh->m_pStatObj->AddRef(); - - // Force create of indexed mesh. - pEdMesh->m_pStatObj->GetIndexedMesh(true); - - // Not found, Make new. - pEdMesh->m_filename = name; - - if (!pEdMesh->m_pSubObjCache) - { - pEdMesh->m_pSubObjCache = new SubObjCache; - pEdMesh->m_pSubObjCache->pTriMesh = new CTriMesh; - pEdMesh->m_pSubObjCache->worldTM.SetIdentity(); - pEdMesh->m_pSubObjCache->invWorldTM.SetIdentity(); - } - return pEdMesh; - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::InvalidateMesh() -{ - if (m_pSubObjCache) - { - UpdateIndexedMeshFromCache(false); - } - if (m_pStatObj) - { - m_pStatObj->Invalidate(true); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetWorldTM(const Matrix34& worldTM) -{ - if (!m_pSubObjCache) - { - return; - } - - m_pSubObjCache->worldTM = worldTM; - m_pSubObjCache->invWorldTM = worldTM.GetInverted(); - - ////////////////////////////////////////////////////////////////////////// - // Transform vertices and normals to world space and store in cached mesh. - ////////////////////////////////////////////////////////////////////////// - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - int nVerts = triMesh.GetVertexCount(); - triMesh.ReallocStream(CTriMesh::WS_POSITIONS, nVerts); - for (int i = 0; i < nVerts; i++) - { - triMesh.pWSVertices[i] = worldTM.TransformPoint(triMesh.pVertices[i].pos); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::DebugDraw(const SGeometryDebugDrawInfo& info, float fExtrdueScale) -{ - if (m_pStatObj) - { - m_pStatObj->DebugDraw(info, fExtrdueScale); - } -} diff --git a/Code/Sandbox/Editor/Geometry/EdMesh.h b/Code/Sandbox/Editor/Geometry/EdMesh.h deleted file mode 100644 index 52dc1fc25d..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdMesh.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Editor structure that wraps access to IStatObj - - -#ifndef CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H -#define CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H -#pragma once - -#include "EdGeometry.h" -#include "Objects/SubObjSelection.h" -#include "TriMesh.h" - -// Flags that can be set on CEdMesh. -enum CEdMeshFlags -{ -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// CEdMesh is a Geometry kind representing simple mesh. -// Holds IStatObj interface from the 3D Engine. -////////////////////////////////////////////////////////////////////////// -class CRYEDIT_API CEdMesh - : public CEdGeometry -{ -public: - ////////////////////////////////////////////////////////////////////////// - // CEdGeometry implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EEdGeometryType GetType() const { return GEOM_TYPE_MESH; }; - virtual void Serialize(CObjectArchive& ar); - - virtual void GetBounds(AABB& box); - virtual CEdGeometry* Clone(); - virtual IIndexedMesh* GetIndexedMesh(size_t idx = 0); - virtual void GetTM(Matrix34* pTM, size_t idx = 0); - virtual void SetModified(bool bModified = true); - virtual bool IsModified() const { return m_bModified; }; - virtual bool StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, int nFlags); - virtual void EndSubObjSelection(); - virtual void Display(DisplayContext& dc); - virtual bool HitTest(HitContext& hit); - bool GetSelectionReferenceFrame(Matrix34& refFrame); - virtual void ModifySelection(SSubObjSelectionModifyContext& modCtx, bool isUndo = true); - virtual void AcceptModifySelection(); - ////////////////////////////////////////////////////////////////////////// - - ~CEdMesh(); - - // Return filename of mesh. - const QString& GetFilename() const { return m_filename; }; - void SetFilename(const QString& filename); - - //! Reload geometry of mesh. - void ReloadGeometry(); - void AddUser(); - void RemoveUser(); - int GetUserCount() const { return m_nUserCount; }; - - ////////////////////////////////////////////////////////////////////////// - void SetFlags(int nFlags) { m_nFlags = nFlags; }; - int GetFlags() { return m_nFlags; } - ////////////////////////////////////////////////////////////////////////// - - //! Access stored IStatObj. - IStatObj* GetIStatObj() const { return m_pStatObj; } - - //! Returns true if filename and geomname refer to the same object as this one. - bool IsSameObject(const char* filename); - - //! RenderMesh. - void Render(SRendParams& rp, const SRenderingPassInfo& passInfo); - - //! Make new CEdMesh, if same IStatObj loaded, and CEdMesh for this IStatObj is allocated. - //! This instance of CEdMesh will be returned. - static CEdMesh* LoadMesh(const char* filename); - - // Creates a new mesh not from a file. - // Create a new StatObj and IndexedMesh. - static CEdMesh* CreateMesh(const char* name); - - //! Reload all geometries. - static void ReloadAllGeometries(); - static void ReleaseAll(); - - //! Check if default object was loaded. - bool IsDefaultObject(); - - ////////////////////////////////////////////////////////////////////////// - // Copy EdMesh data to the specified mesh. - void CopyToMesh(CTriMesh& toMesh, int nCopyFlags); - // Copy EdMesh data from the specified mesh. - void CopyFromMesh(CTriMesh& fromMesh, int nCopyFlags, bool bUndo); - - // Retrieve mesh class. - CTriMesh* GetMesh(); - - ////////////////////////////////////////////////////////////////////////// - void InvalidateMesh(); - void SetWorldTM(const Matrix34& worldTM); - - // Save mesh into the file. - // Optionally can provide pointer to the pak file where to save files into. - void SaveToCGF(const char* sFilename, CPakFile* pPakFile = NULL, _smart_ptr pMaterial = NULL); - - // Draw debug representation of this mesh. - void DebugDraw(const SGeometryDebugDrawInfo& info, float fExtrdueScale = 0.01f); - -private: - ////////////////////////////////////////////////////////////////////////// - CEdMesh(IStatObj* pGeom); - CEdMesh(); - void UpdateSubObjCache(); - void UpdateIndexedMeshFromCache(bool bFast); - void OnSelectionChange(); - - ////////////////////////////////////////////////////////////////////////// - struct SSubObjHitTestEnvironment - { - Vec3 vWSCameraPos; - Vec3 vWSCameraVector; - Vec3 vOSCameraVector; - - bool bHitTestNearest; - bool bHitTestSelected; - bool bSelectOnHit; - bool bAdd; - bool bRemove; - bool bSelectValue; - bool bHighlightOnly; - bool bIgnoreBackfacing; - }; - struct SSubObjHitTestResult - { - CTriMesh::EStream stream; // To What stream of the TriMesh this result apply. - MeshElementsArray elems; // List of hit elements. - float minDistance; // Minimal distance to the hit. - SSubObjHitTestResult() { minDistance = FLT_MAX; } - }; - bool HitTestVertex(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool HitTestEdge(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool HitTestFace(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - - // Return`s true if selection changed. - bool SelectSubObjElements(SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool IsHitTestResultSelected(SSubObjHitTestResult& result); - - ////////////////////////////////////////////////////////////////////////// - //! CGF filename. - QString m_filename; - IStatObj* m_pStatObj; - int m_nUserCount; - int m_nFlags; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - typedef std::map > MeshMap; - static MeshMap m_meshMap; - - // This cache is created when sub object selection is needed. - struct SubObjCache - { - // Cache of data in geometry. - // World space mesh. - CTriMesh* pTriMesh; - Matrix34 worldTM; - Matrix34 invWorldTM; - CBitArray m_tempBitArray; - bool bNoDisplay; - - SubObjCache() - : pTriMesh(0) - , bNoDisplay(false) {}; - }; - SubObjCache* m_pSubObjCache; - bool m_bModified; - - std::vector m_tempIndexedMeshes; - std::vector m_tempMatrices; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index c03b99e128..f11beacf10 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -85,7 +85,6 @@ namespace WinWidget } struct ISystem; -struct I3DEngine; struct IRenderer; struct AABB; struct IEventLoopHook; @@ -137,7 +136,6 @@ enum EEditorNotifyEvent eNotify_OnEndLayerExport, // Sent after a layer have been exported. eNotify_OnCloseScene, // Send when the document is about to close. eNotify_OnSceneClosed, // Send when the document is closed. - eNotify_OnMissionChange, // Send when the current mission changes. eNotify_OnBeginLoad, // Sent when the document is start to load. eNotify_OnEndLoad, // Sent when the document loading is finished @@ -180,8 +178,6 @@ enum EEditorNotifyEvent eNotify_OnDisplayRenderUpdate, // Sent when editor finish terrain texture generation. - eNotify_OnTimeOfDayChange, // Time of day parameters where modified. - eNotify_OnDataBaseUpdate, // DataBase Library was modified. eNotify_OnLayerImportBegin, //layer import was started @@ -241,8 +237,6 @@ struct IDocListener virtual void OnLoadDocument() = 0; //! Called when document is being closed. virtual void OnCloseDocument() = 0; - //! Called when mission changes. - virtual void OnMissionChange() = 0; }; //! Derive from this class if you want to register for getting global editor notifications. @@ -431,7 +425,6 @@ struct IEditor virtual void DeleteThis() = 0; //! Access to Editor ISystem interface. virtual ISystem* GetSystem() = 0; - virtual I3DEngine* Get3DEngine() = 0; virtual IRenderer* GetRenderer() = 0; //! Access to class factory. virtual IEditorClassFactory* GetClassFactory() = 0; @@ -739,8 +732,6 @@ struct IEditor typedef AZStd::function TContextMenuExtensionFunc; virtual void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) = 0; - virtual void SetCurrentMissionTime(float time) = 0; - virtual SSystemGlobalEnvironment* GetEnv() = 0; virtual IImageUtil* GetImageUtil() = 0; // Vladimir@conffx virtual SEditorSettings* GetEditorSettings() = 0; diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index ff9ece339a..53a2c120c4 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -71,7 +71,6 @@ AZ_POP_DISABLE_WARNING #include "BackgroundTaskManager.h" #include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" -#include "Mission.h" #include "MainStatusBar.h" #include "SettingsBlock.h" @@ -441,15 +440,6 @@ ISystem* CEditorImpl::GetSystem() return m_pSystem; } -I3DEngine* CEditorImpl::Get3DEngine() -{ - if (gEnv) - { - return gEnv->p3DEngine; - } - return nullptr; -} - IRenderer* CEditorImpl::GetRenderer() { if (gEnv) @@ -1716,13 +1706,6 @@ void CEditorImpl::RegisterObjectContextMenuExtension(TContextMenuExtensionFunc f m_objectContextMenuExtensions.push_back(func); } -void CEditorImpl::SetCurrentMissionTime(float time) -{ - if (CMission* pMission = GetIEditor()->GetDocument()->GetCurrentMission()) - { - pMission->SetTime(time); - } -} // Vladimir@Conffx SSystemGlobalEnvironment* CEditorImpl::GetEnv() { diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index d17a94807f..bbef338cb2 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -116,7 +116,6 @@ public: bool IsInitialized() const{ return m_bInitialized; } bool SaveDocument(); ISystem* GetSystem(); - I3DEngine* Get3DEngine(); IRenderer* GetRenderer(); void WriteToConsole(const char* string) { CLogFile::WriteLine(string); }; void WriteToConsole(const QString& string) { CLogFile::WriteLine(string); }; @@ -321,7 +320,6 @@ public: void OnObjectContextMenuOpened(QMenu* pMenu, const CBaseObject* pObject); virtual void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) override; - virtual void SetCurrentMissionTime(float time); virtual SSystemGlobalEnvironment* GetEnv() override; virtual IBaseLibraryManager* GetMaterialManagerLibrary() override; // Vladimir@Conffx virtual IEditorMaterialManager* GetIEditorMaterialManager() override; // Vladimir@Conffx diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 828a7cdfcc..e06b89b38e 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -25,6 +25,7 @@ #include "Util/Image.h" #include "Util/ImageUtil.h" +#include #define HELPER_MATERIAL "Objects/Helper" @@ -76,12 +77,11 @@ void CIconManager::Done() ////////////////////////////////////////////////////////////////////////// void CIconManager::Reset() { - I3DEngine* pEngine = GetIEditor()->Get3DEngine(); // Do not unload objects. but clears them. int i; for (i = 0; i < sizeof(m_objects) / sizeof(m_objects[0]); i++) { - if (m_objects[i] && pEngine) + if (m_objects[i]) { m_objects[i]->Release(); } @@ -130,39 +130,10 @@ int CIconManager::GetIconTexture(EIcon icon) return m_icons[icon]; } - ////////////////////////////////////////////////////////////////////////// -_smart_ptr CIconManager::GetHelperMaterial() +IStatObj* CIconManager::GetObject(EStatObject) { - if (!m_pHelperMtl) - { - m_pHelperMtl = GetIEditor()->Get3DEngine()->GetMaterialManager()->LoadMaterial(HELPER_MATERIAL); - } - return m_pHelperMtl; -}; - -////////////////////////////////////////////////////////////////////////// -IStatObj* CIconManager::GetObject(EStatObject object) -{ - assert(object >= 0 && object < eStatObject_COUNT); - - if (m_objects[object]) - { - return m_objects[object]; - } - - // Try to load this object. - m_objects[object] = GetIEditor()->Get3DEngine()->LoadStatObjUnsafeManualRef(g_ObjectNames[object], NULL, NULL, false); - if (!m_objects[object]) - { - CLogFile::FormatLine("Error: Load Failed: %s", g_ObjectNames[object]); - } - m_objects[object]->AddRef(); - if (GetHelperMaterial()) - { - m_objects[object]->SetMaterial(GetHelperMaterial()); - } - return m_objects[object]; + return nullptr; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/IconManager.h b/Code/Sandbox/Editor/IconManager.h index 641e3f70a7..6c86627f3a 100644 --- a/Code/Sandbox/Editor/IconManager.h +++ b/Code/Sandbox/Editor/IconManager.h @@ -51,7 +51,6 @@ public: virtual IStatObj* GetObject(EStatObject object); virtual int GetIconTexture(const char* iconName); - virtual _smart_ptr GetHelperMaterial(); ////////////////////////////////////////////////////////////////////////// // Icon bitmaps. @@ -64,14 +63,11 @@ public: virtual void OnNewDocument() { Reset(); }; virtual void OnLoadDocument() { Reset(); }; virtual void OnCloseDocument() { Reset(); }; - virtual void OnMissionChange() { Reset(); }; ////////////////////////////////////////////////////////////////////////// private: StdMap m_textures; - _smart_ptr m_pHelperMtl; - IStatObj* m_objects[eStatObject_COUNT]; int m_icons[eIcon_COUNT]; diff --git a/Code/Sandbox/Editor/Include/IIconManager.h b/Code/Sandbox/Editor/Include/IIconManager.h index 115d998be3..15ef37e23b 100644 --- a/Code/Sandbox/Editor/Include/IIconManager.h +++ b/Code/Sandbox/Editor/Include/IIconManager.h @@ -61,7 +61,6 @@ struct IIconManager virtual IStatObj* GetObject(EStatObject object) = 0; virtual int GetIconTexture(EIcon icon) = 0; virtual int GetIconTexture(const char* iconName) = 0; - virtual _smart_ptr GetHelperMaterial() = 0; virtual QImage* GetIconBitmap(const char* filename, bool& haveAlpha, uint32 effects = 0) = 0; // Register an Icon for the specific command virtual void RegisterCommandIcon([[maybe_unused]] const char* filename, [[maybe_unused]] int nCommandId) {} diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 6659e41122..4a20bd6b60 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -32,7 +32,6 @@ public: public: MOCK_METHOD0(DeleteThis, void()); MOCK_METHOD0(GetSystem, ISystem*()); - MOCK_METHOD0(Get3DEngine, I3DEngine* ()); MOCK_METHOD0(GetRenderer, IRenderer* ()); MOCK_METHOD0(GetClassFactory, IEditorClassFactory* ()); MOCK_METHOD0(GetCommandManager, CEditorCommandManager*()); @@ -191,7 +190,6 @@ public: MOCK_METHOD0(GetBackgroundScheduleManager, struct IBackgroundScheduleManager* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); - MOCK_METHOD1(SetCurrentMissionTime, void(float )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); MOCK_METHOD0(GetImageUtil, IImageUtil* ()); MOCK_METHOD0(GetEditorSettings, SEditorSettings* ()); diff --git a/Code/Sandbox/Editor/LyViewPaneNames.h b/Code/Sandbox/Editor/LyViewPaneNames.h index fdbf8bf90c..e95191ce06 100644 --- a/Code/Sandbox/Editor/LyViewPaneNames.h +++ b/Code/Sandbox/Editor/LyViewPaneNames.h @@ -44,7 +44,6 @@ namespace LyViewPane static const char* const TerrainTool = "Terrain Tool"; static const char* const TerrainTextureLayers = "Terrain Texture Layers"; static const char* const ParticleEditor = "Particle Editor"; - static const char* const TimeOfDayEditor = "Time Of Day"; static const char* const AudioControlsEditor = "Audio Controls Editor"; static const char* const SubstanceEditor = "Substance Editor"; static const char* const VegetationEditor = "Vegetation Editor"; diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c54c31c5d5..895df4214f 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -90,7 +90,6 @@ AZ_POP_DISABLE_WARNING #include "TrackView/TrackViewDialog.h" #include "ErrorReportDialog.h" -#include "TimeOfDayDialog.h" #include "Dialogs/PythonScriptsDialog.h" #include "EngineSettingsManager.h" @@ -1078,8 +1077,6 @@ void MainWindow::InitActions() // Tools actions am->AddAction(ID_RELOAD_TEXTURES, tr("Reload Textures/Shaders")) .SetStatusTip(tr("Reload all textures.")); - am->AddAction(ID_RELOAD_GEOMETRY, tr("Reload Geometry")) - .SetStatusTip(tr("Reload all geometries.")); am->AddAction(ID_TOOLS_ENABLEFILECHANGEMONITORING, tr("Enable File Change Monitoring")); am->AddAction(ID_CLEAR_REGISTRY, tr("Clear Registry Data")) .SetStatusTip(tr("Clear Registry Data")); @@ -1352,12 +1349,6 @@ void MainWindow::InitEnvironmentModeMenu(CVarMenu* environmentModeMenu) environmentModeMenu->AddCVarToggleItem({ "r_ssdo", tr("Hide Screen Space Directional Occlusion"), 0, 1 }); environmentModeMenu->AddCVarToggleItem({ "e_DynamicLights", tr("Hide All Dynamic Lights"), 0, 1 }); environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarValuesItem("e_TimeOfDay", tr("Time of Day"), - { - {tr("Day (1:00 pm)"), 13}, - {tr("Night (9:00 pm)"), 21} - }, 9); - environmentModeMenu->AddSeparator(); environmentModeMenu->AddCVarToggleItem({ "e_Entities", tr("Hide Entities"), 0, 1 }); environmentModeMenu->AddSeparator(); environmentModeMenu->AddCVarToggleItem({ "e_Vegetation", tr("Hide Vegetation"), 0, 1 }); diff --git a/Code/Sandbox/Editor/Mission.cpp b/Code/Sandbox/Editor/Mission.cpp deleted file mode 100644 index b9668f1c80..0000000000 --- a/Code/Sandbox/Editor/Mission.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : CMission class implementation. - -#include "EditorDefs.h" - -#include "Mission.h" - -// cryCommon -#include -#include - -// Editor -#include "CryEditDoc.h" -#include "GameEngine.h" -#include "Include/IObjectManager.h" - - -namespace -{ - const char* kTimeOfDayFile = "TimeOfDay.xml"; - const char* kTimeOfDayRoot = "TimeOfDay"; - const char* kEnvironmentFile = "Environment.xml"; - const char* kEnvironmentRoot = "Environment"; -}; - - -////////////////////////////////////////////////////////////////////////// -CMission::CMission(CCryEditDoc* doc) -{ - m_doc = doc; - m_objects = XmlHelpers::CreateXmlNode("Objects"); - m_layers = XmlHelpers::CreateXmlNode("ObjectLayers"); - //m_exportData = XmlNodeRef( "ExportData" ); - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - m_environment = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(m_doc->GetEnvironmentTemplate(), m_environment); - - m_time = 12; // 12 PM by default. - - m_numCGFObjects = 0; - - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -CMission::~CMission() -{ -} - -////////////////////////////////////////////////////////////////////////// -CMission* CMission::Clone() -{ - CMission* m = new CMission(m_doc); - m->SetName(m_name); - m->SetDescription(m_description); - m->m_objects = m_objects->clone(); - m->m_layers = m_layers->clone(); - m->m_environment = m_environment->clone(); - m->m_time = m_time; - return m; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::Serialize(CXmlArchive& ar, bool bParts) -{ - if (ar.bLoading) - { - // Load. - ar.root->getAttr("Name", m_name); - ar.root->getAttr("Description", m_description); - - XmlNodeRef objects = ar.root->findChild("Objects"); - if (objects) - { - m_objects = objects; - } - - XmlNodeRef layers = ar.root->findChild("ObjectLayers"); - if (layers) - { - m_layers = layers; - } - - SerializeTimeOfDay(ar); - - m_Animations = ar.root->findChild("MovieData"); - - SerializeEnvironment(ar); - } - else - { - ar.root->setAttr("Name", m_name.toUtf8().data()); - ar.root->setAttr("Description", m_description.toUtf8().data()); - - QString timeStr; - int nHour = floor(m_time); - int nMins = (m_time - floor(m_time)) * 60.0f; - timeStr = QStringLiteral("%1:%2").arg(nHour, 2, 10, QLatin1Char('0')).arg(nMins, 2, 10, QLatin1Char('0')); - ar.root->setAttr("MissionTime", timeStr.toUtf8().data()); - - // Saving. - XmlNodeRef layers = m_layers->clone(); - layers->setTag("ObjectLayers"); - ar.root->addChild(layers); - - ///XmlNodeRef objects = m_objects->clone(); - m_objects->setTag("Objects"); - ar.root->addChild(m_objects); - - if (bParts) - { - SerializeTimeOfDay(ar); - SerializeEnvironment(ar); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::Export(XmlNodeRef& root, XmlNodeRef& objectsNode) -{ - // Also save exported objects data. - root->setAttr("Name", m_name.toUtf8().data()); - root->setAttr("Description", m_description.toUtf8().data()); - - QString timeStr; - int nHour = floor(m_time); - int nMins = (m_time - floor(m_time)) * 60.0f; - timeStr = QStringLiteral("%1:%2").arg(nHour, 2, 10, QLatin1Char('0')).arg(nMins, 2, 10, QLatin1Char('0')); - root->setAttr("Time", timeStr.toUtf8().data()); - - // Saving. - //XmlNodeRef objects = m_exportData->clone(); - //objects->setTag( "Objects" ); - //root->addChild( objects ); - - XmlNodeRef envNode = m_environment->clone(); - root->addChild(envNode); - - m_timeOfDay->setAttr("Time", m_time); - root->addChild(m_timeOfDay); - - IObjectManager* pObjMan = GetIEditor()->GetObjectManager(); - - ////////////////////////////////////////////////////////////////////////// - // Serialize objects. - ////////////////////////////////////////////////////////////////////////// - QString path = QDir::toNativeSeparators(QFileInfo(m_doc->GetLevelPathName()).absolutePath()); - if (!path.endsWith(QDir::separator())) - path += QDir::separator(); - - objectsNode = root->newChild("Objects"); - pObjMan->Export(path, objectsNode, true); // Export shared. - pObjMan->Export(path, objectsNode, false); // Export not shared. -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SyncContent(bool bRetrieve, bool bIgnoreObjects, [[maybe_unused]] bool bSkipLoadingAI /* = false */) -{ - // The function may take a longer time when executing objMan->Serialize, which uses CWaitProgress internally - // Adding a sync flag to prevent the function from being re-entered after the data is modified by OnEnvironmentChange - if (m_reentrancyProtector) - { - return; - } - m_reentrancyProtector = true; - - // Save data from current Document to Mission. - IObjectManager* objMan = GetIEditor()->GetObjectManager(); - if (bRetrieve) - { - // Activating this mission. - CGameEngine* gameEngine = GetIEditor()->GetGameEngine(); - - if (!bIgnoreObjects) - { - // Retrieve data from Mission and put to document. - XmlNodeRef root = XmlHelpers::CreateXmlNode("Root"); - root->addChild(m_objects); - root->addChild(m_layers); - objMan->Serialize(root, true, SERIALIZE_ONLY_NOTSHARED); - } - - m_doc->GetFogTemplate() = m_environment; - - CXmlTemplate::GetValues(m_doc->GetEnvironmentTemplate(), m_environment); - - gameEngine->ReloadEnvironment(); - - objMan->SendEvent(EVENT_MISSION_CHANGE); - m_doc->ChangeMission(); - - if (GetIEditor()->Get3DEngine()) - { - m_numCGFObjects = GetIEditor()->Get3DEngine()->GetLoadedObjectCount(); - - // Load time of day. - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_timeOfDay, true); - } - } - else - { - // Save time of day. - if (GetIEditor()->Get3DEngine()) - { - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_timeOfDay, false); - } - - if (!bIgnoreObjects) - { - XmlNodeRef root = XmlHelpers::CreateXmlNode("Root"); - objMan->Serialize(root, false, SERIALIZE_ONLY_NOTSHARED); - m_objects = root->findChild("Objects"); - XmlNodeRef layers = root->findChild("ObjectLayers"); - if (layers) - { - m_layers = layers; - } - } - } - - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::OnEnvironmentChange() -{ - // Only execute the reload function if there is no ongoing SyncContent. - if (m_reentrancyProtector) - { - return; - } - m_reentrancyProtector = true; - m_environment = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(m_doc->GetEnvironmentTemplate(), m_environment); - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::AddObjectsNode(XmlNodeRef& node) -{ - for (int i = 0; i < node->getChildCount(); i++) - { - m_objects->addChild(node->getChild(i)->clone()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SetLayersNode(XmlNodeRef& node) -{ - m_layers = node->clone(); -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SaveParts() -{ - // Save Time of Day - { - CTempFileHelper helper((GetIEditor()->GetLevelDataFolder() + kTimeOfDayFile).toUtf8().data()); - - m_timeOfDay->saveToFile(helper.GetTempFilePath().toUtf8().data()); - - if (!helper.UpdateFile(false)) - { - return; - } - } - - - // Save Environment - { - CTempFileHelper helper((GetIEditor()->GetLevelDataFolder() + kEnvironmentFile).toUtf8().data()); - - XmlNodeRef root = m_environment->clone(); - root->setTag(kEnvironmentRoot); - root->saveToFile(helper.GetTempFilePath().toUtf8().data()); - - if (!helper.UpdateFile(false)) - { - return; - } - } -} - - -////////////////////////////////////////////////////////////////////////// -void CMission::LoadParts() -{ - // Load Time of Day - { - QString filename = GetIEditor()->GetLevelDataFolder() + kTimeOfDayFile; - XmlNodeRef root = XmlHelpers::LoadXmlFromFile(filename.toUtf8().data()); - if (root && !_stricmp(root->getTag(), kTimeOfDayRoot)) - { - m_timeOfDay = root; - m_timeOfDay->getAttr("Time", m_time); - } - } - - // Load Environment - { - QString filename = GetIEditor()->GetLevelDataFolder() + kEnvironmentFile; - XmlNodeRef root = XmlHelpers::LoadXmlFromFile(filename.toUtf8().data()); - if (root && !_stricmp(root->getTag(), kEnvironmentRoot)) - { - m_environment = root; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SerializeTimeOfDay(CXmlArchive& ar) -{ - if (ar.bLoading) - { - XmlNodeRef todNode = ar.root->findChild("TimeOfDay"); - if (todNode) - { - m_timeOfDay = todNode; - todNode->getAttr("Time", m_time); - } - else - { - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - } - } - else - { - m_timeOfDay->setAttr("Time", m_time); - ar.root->addChild(m_timeOfDay); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SerializeEnvironment(CXmlArchive& ar) -{ - if (ar.bLoading) - { - XmlNodeRef env = ar.root->findChild("Environment"); - if (env) - { - m_environment = env; - } - } - else - { - XmlNodeRef env = m_environment->clone(); - env->setTag("Environment"); - ar.root->addChild(env); - } -} - diff --git a/Code/Sandbox/Editor/Mission.h b/Code/Sandbox/Editor/Mission.h deleted file mode 100644 index f0773a0be7..0000000000 --- a/Code/Sandbox/Editor/Mission.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Mission class definition. - -#pragma once - - -/*! - CMission represent single Game Mission on same map. - Multiple Missions share same map, and stored in one .cry or .ly file. - - */ -class CMission -{ -public: - //! Ctor of mission. - CMission(CCryEditDoc* doc); - //! Dtor of mission. - virtual ~CMission(); - - void SetName(const QString& name) { m_name = name; } - const QString& GetName() const { return m_name; } - - void SetDescription(const QString& dsc) { m_description = dsc; } - const QString& GetDescription() const { return m_description; } - - XmlNodeRef GetEnvironment() { return m_environment; }; - - void SetTime(float time) { m_time = time; }; - float GetTime() const { return m_time; }; - - //! Called when this mission must be synchonized with current data in Document. - //! if bRetrieve is true, data is retrieved from Mission to global structures. - void SyncContent(bool bRetrieve, bool bIgnoreObjects, bool bSkipLoadingAI = false); - - //! Create clone of this mission. - CMission* Clone(); - - //! Serialize mission. - void Serialize(CXmlArchive& ar, bool bParts = true); - - //! Serialize time of day - void SerializeTimeOfDay(CXmlArchive& ar); - - //! Serialize environment - void SerializeEnvironment(CXmlArchive& ar); - - //! Save some elements of mission to separate files - void SaveParts(); - - //! Load some elements of mission from separate files - void LoadParts(); - - //! Export mission to game. - void Export(XmlNodeRef& root, XmlNodeRef& objectsNode); - - //! Add shared objects to mission objects. - void AddObjectsNode(XmlNodeRef& node); - void SetLayersNode(XmlNodeRef& node); - - void OnEnvironmentChange(); - int GetNumCGFObjects() const { return m_numCGFObjects; }; - -private: - //! Document owner of this mission. - CCryEditDoc* m_doc; - - QString m_name; - QString m_description; - - //! Mission time; - float m_time; - - //! Root node of objects defined only in this mission. - XmlNodeRef m_objects; - - //! Object layers. - XmlNodeRef m_layers; - - //! Exported data of this mission. - XmlNodeRef m_exportData; - - //! Environment settings of this mission. - XmlNodeRef m_environment; - - XmlNodeRef m_Animations; // backward compatibility. - - XmlNodeRef m_timeOfDay; - - int m_numCGFObjects; - - bool m_reentrancyProtector; -}; - diff --git a/Code/Sandbox/Editor/ModelViewport.cpp b/Code/Sandbox/Editor/ModelViewport.cpp deleted file mode 100644 index 2e00adb4fc..0000000000 --- a/Code/Sandbox/Editor/ModelViewport.cpp +++ /dev/null @@ -1,961 +0,0 @@ - -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "ModelViewport.h" - -// Qt -#include -#include - -// CryCommon -#include - -#include "CryPhysicsDeprecation.h" - - -// Editor -#include "ThumbnailGenerator.h" // for CThumbnailGenerator -#include "FileTypeUtils.h" // for IsPreviewableFileType -#include "ErrorRecorder.h" - - - - - -uint32 g_ypos = 0; - -#define SKYBOX_NAME "InfoRedGal" - -///////////////////////////////////////////////////////////////////////////// -// CModelViewport - -CModelViewport::CModelViewport(const char* settingsPath, QWidget* parent) - : CRenderViewport(tr("Model View"), parent) -{ - m_settingsPath = QString::fromLatin1(settingsPath); - - m_bPaused = false; - - m_Camera.SetFrustum(800, 600, 3.14f / 4.0f, 0.02f, 10000); - - m_bInRotateMode = false; - m_bInMoveMode = false; - - m_object = 0; - - - m_weaponModel = 0; - - m_camRadius = 10; - - m_moveSpeed = 0.1f; - m_LightRotationRadian = 0.0f; - - m_weaponIK = false; - - m_pRESky = 0; - m_pSkyboxName = 0; - m_pSkyBoxShader = NULL; - - m_attachBone = QStringLiteral("weapon_bone"); - - // Init variable. - mv_objectAmbientColor = Vec3(0.25f, 0.25f, 0.25f); - mv_backgroundColor = Vec3(0.25f, 0.25f, 0.25f); - - mv_lightDiffuseColor = Vec3(0.70f, 0.70f, 0.70f); - mv_lightMultiplier = 3.0f; - mv_lightOrbit = 15.0f; - mv_lightRadius = 400.0f; - mv_lightSpecMultiplier = 1.0f; - - mv_showPhysics = false; - - m_GridOrigin = Vec3(ZERO); - m_arrAnimatedCharacterPath.resize(0x200, ZERO); - m_arrSmoothEntityPath.resize(0x200, ZERO); - - m_arrRunStrafeSmoothing.resize(0x100); - SetPlayerPos(); - - // cache all the variable callbacks, must match order of enum defined in header - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnCharPhysics, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnLightColor, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnLightMultiplier, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnShowShaders, this, AZStd::placeholders::_1)); - - //-------------------------------------------------- - // Register variables. - //-------------------------------------------------- - m_vars.AddVariable(mv_showPhysics, "Display Physics"); - m_vars.AddVariable(mv_useCharPhysics, "Use Character Physics", &m_onSetCallbacksCache[VariableCallbackIndex::OnCharPhysics]); - mv_useCharPhysics = true; - m_vars.AddVariable(mv_showGrid, "ShowGrid"); - mv_showGrid = true; - m_vars.AddVariable(mv_showBase, "ShowBase"); - mv_showBase = false; - m_vars.AddVariable(mv_showLocator, "ShowLocator"); - mv_showLocator = 0; - m_vars.AddVariable(mv_InPlaceMovement, "InPlaceMovement"); - mv_InPlaceMovement = false; - m_vars.AddVariable(mv_StrafingControl, "StrafingControl"); - mv_StrafingControl = false; - - m_vars.AddVariable(mv_lighting, "Lighting"); - mv_lighting = true; - m_vars.AddVariable(mv_animateLights, "AnimLights"); - - m_vars.AddVariable(mv_backgroundColor, "BackgroundColor", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - m_vars.AddVariable(mv_objectAmbientColor, "ObjectAmbient", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - - m_vars.AddVariable(mv_lightDiffuseColor, "LightDiffuse", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - m_vars.AddVariable(mv_lightMultiplier, "Light Multiplier", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightSpecMultiplier, "Light Specular Multiplier", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightRadius, "Light Radius", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightOrbit, "Light Orbit", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - - m_vars.AddVariable(mv_showWireframe1, "ShowWireframe1"); - m_vars.AddVariable(mv_showWireframe2, "ShowWireframe2"); - m_vars.AddVariable(mv_showTangents, "ShowTangents"); - m_vars.AddVariable(mv_showBinormals, "ShowBinormals"); - m_vars.AddVariable(mv_showNormals, "ShowNormals"); - - m_vars.AddVariable(mv_showSkeleton, "ShowSkeleton"); - m_vars.AddVariable(mv_showJointNames, "ShowJointNames"); - m_vars.AddVariable(mv_showJointsValues, "ShowJointsValues"); - m_vars.AddVariable(mv_showStartLocation, "ShowInvStartLocation"); - m_vars.AddVariable(mv_showMotionParam, "ShowMotionParam"); - m_vars.AddVariable(mv_printDebugText, "PrintDebugText"); - - m_vars.AddVariable(mv_UniformScaling, "UniformScaling"); - mv_UniformScaling = 1.0f; - mv_UniformScaling.SetLimits(0.01f, 2.0f); - m_vars.AddVariable(mv_forceLODNum, "ForceLODNum"); - mv_forceLODNum = 0; - mv_forceLODNum.SetLimits(0, 10); - m_vars.AddVariable(mv_showShaders, "ShowShaders", &m_onSetCallbacksCache[VariableCallbackIndex::OnShowShaders]); - m_vars.AddVariable(mv_AttachCamera, "AttachCamera"); - - m_vars.AddVariable(mv_fov, "FOV"); - mv_fov = 60; - mv_fov.SetLimits(1, 120); - - RestoreDebugOptions(); - - m_camRadius = 10; - - //YPR_Angle = Ang3(0,-1.0f,0); - //SetViewTM( Matrix34(CCamera::CreateOrientationYPR(YPR_Angle), Vec3(0,-m_camRadius,0)) ); - Vec3 camPos = Vec3(10, 10, 10); - Matrix34 tm = Matrix33::CreateRotationVDir((Vec3(0, 0, 0) - camPos).GetNormalized()); - tm.SetTranslation(camPos); - SetViewTM(tm); - - - m_AABB.Reset(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SaveDebugOptions() const -{ - QSettings settings; - for (auto g : m_settingsPath.split('\\')) - settings.beginGroup(g); - - CVarBlock* vb = GetVarObject()->GetVarBlock(); - int32 vbCount = vb->GetNumVariables(); - - settings.setValue("iDebugOptionCount", vbCount); - - char keyType[64], keyValue[64]; - for (int32 i = 0; i < vbCount; ++i) - { - IVariable* var = vb->GetVariable(i); - IVariable::EType vType = var->GetType(); - sprintf_s(keyType, "DebugOption_%s_type", var->GetName().toUtf8().data()); - sprintf_s(keyValue, "DebugOption_%s_value", var->GetName().toUtf8().data()); - switch (vType) - { - case IVariable::UNKNOWN: - { - break; - } - case IVariable::INT: - { - int32 value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::INT); - settings.setValue(keyValue, value); - - break; - } - case IVariable::BOOL: - { - bool value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::BOOL); - settings.setValue(keyValue, value); - break; - } - case IVariable::FLOAT: - { - f32 value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::FLOAT); - settings.setValue(keyValue, value); - break; - } - case IVariable::VECTOR: - { - Vec3 value; - var->Get(value); - f32 valueArray[3]; - valueArray[0] = value.x; - valueArray[1] = value.y; - valueArray[2] = value.z; - settings.setValue(keyType, IVariable::VECTOR); - settings.setValue(keyValue, QByteArray(reinterpret_cast(&value), 3 * sizeof(f32))); - - break; - } - case IVariable::QUAT: - { - Quat value; - var->Get(value); - f32 valueArray[4]; - valueArray[0] = value.w; - valueArray[1] = value.v.x; - valueArray[2] = value.v.y; - valueArray[3] = value.v.z; - - settings.setValue(keyType, IVariable::QUAT); - settings.setValue(keyValue, QByteArray(reinterpret_cast(&value), 4 * sizeof(f32))); - - break; - } - case IVariable::STRING: - { - QString value; - var->Get(value); - settings.setValue(keyType, IVariable::STRING); - settings.setValue(keyValue, value); - - break; - } - case IVariable::ARRAY: - { - break; - } - default: - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::RestoreDebugOptions() -{ - QSettings settings; - for (auto g : m_settingsPath.split('\\')) - settings.beginGroup(g); - - QString strRead = ""; - int32 iRead = 0; - BOOL bRead = FALSE; - f32 fRead = .0f; - QByteArray pbtData; - - CVarBlock* vb = m_vars.GetVarBlock(); - int32 vbCount = vb->GetNumVariables(); - - char keyType[64], keyValue[64]; - for (int32 i = 0; i < vbCount; ++i) - { - IVariable* var = vb->GetVariable(i); - sprintf_s(keyType, "DebugOption_%s_type", var->GetName().toUtf8().data()); - - int32 iType = settings.value(keyType, 0).toInt(); - - sprintf_s(keyValue, "DebugOption_%s_value", var->GetName().toUtf8().data()); - switch (iType) - { - case IVariable::UNKNOWN: - { - break; - } - case IVariable::INT: - { - iRead = settings.value(keyValue, 0).toInt(); - var->Set(iRead); - break; - } - case IVariable::BOOL: - { - bRead = settings.value(keyValue, FALSE).toBool(); - var->Set(bRead); - break; - } - case IVariable::FLOAT: - { - fRead = settings.value(keyValue).toDouble(); - var->Set(fRead); - break; - } - case IVariable::VECTOR: - { - pbtData = settings.value(keyValue).toByteArray(); - assert(pbtData.count() == 3 * sizeof(f32)); - f32* pfRead = reinterpret_cast(pbtData.data()); - - Vec3 vecRead(pfRead[0], pfRead[1], pfRead[2]); - var->Set(vecRead); - break; - } - case IVariable::QUAT: - { - pbtData = settings.value(keyValue).toByteArray(); - assert(pbtData.count() == 4 * sizeof(f32)); - f32* pfRead = reinterpret_cast(pbtData.data()); - - Quat valueRead(pfRead[0], pfRead[1], pfRead[2], pfRead[3]); - var->Set(valueRead); - break; - } - case IVariable::STRING: - { - strRead = settings.value(keyValue, "").toString(); - var->Set(strRead); - break; - } - case IVariable::ARRAY: - { - break; - } - default: - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -CModelViewport::~CModelViewport() -{ - OnDestroy(); - ReleaseObject(); - - GetIEditor()->FlushUndo(); - - SaveDebugOptions(); - - // helper offset?? - CRY_PHYSICS_REPLACEMENT_ASSERT(); - GetIEditor()->SetConsoleVar("ca_UsePhysics", 1); -} - -///////////////////////////////////////////////////////////////////////////// -// CModelViewport message handlers -///////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CModelViewport::ReleaseObject() -{ - if (m_object) - { - m_object->Release(); - m_object = NULL; - } - - if (m_weaponModel) - { - m_weaponModel->Release(); - m_weaponModel = NULL; - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::LoadObject(const QString& fileName, [[maybe_unused]] float scale) -{ - m_bPaused = false; - - // Load object. - QString file = Path::MakeGamePath(fileName); - - bool reload = false; - if (m_loadedFile == file) - { - reload = true; - } - m_loadedFile = file; - - SetName(tr("Model View - %1").arg(file)); - - ReleaseObject(); - - // Enables display of warning after model have been loaded. - CErrorsRecorder errRecorder; - - if (IsPreviewableFileType(file.toUtf8().data())) - { - const QString fileExt = QFileInfo(file).completeSuffix(); - // Try Load character. - const bool isSKEL = (0 == fileExt.compare(CRY_SKEL_FILE_EXT, Qt::CaseInsensitive)); - const bool isSKIN = (0 == fileExt.compare(CRY_SKIN_FILE_EXT, Qt::CaseInsensitive)); - const bool isCGA = (0 == fileExt.compare(CRY_ANIM_GEOMETRY_FILE_EXT, Qt::CaseInsensitive)); - const bool isCDF = (0 == fileExt.compare(CRY_CHARACTER_DEFINITION_FILE_EXT, Qt::CaseInsensitive)); - if (isSKEL || isSKIN || isCGA || isCDF) - { - } - else - { - LoadStaticObject(file); - } - } - else - { - QMessageBox::warning(this, tr("Preview Error"), tr("Preview of this file type not supported.")); - return; - } - - //-------------------------------------------------------------------------------- - - if (!reload) - { - Vec3 v = m_AABB.max - m_AABB.min; - float radius = v.GetLength() / 2.0f; - m_camRadius = radius * 2; - } - - if (GetIEditor()->IsInPreviewMode()) - { - Physicalize(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::LoadStaticObject(const QString& file) -{ - if (m_object) - { - m_object->Release(); - } - - // Load Static object. - m_object = m_engine->LoadStatObjUnsafeManualRef(file.toUtf8().data(), 0, 0, false); - - if (!m_object) - { - CLogFile::WriteLine("Loading of object failed."); - return; - } - m_object->AddRef(); - - // Generate thumbnail for this cgf. - CThumbnailGenerator thumbGen; - thumbGen.GenerateForFile(file); - - m_AABB.min = m_object->GetBoxMin(); - m_AABB.max = m_object->GetBoxMax(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnRender() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - const QRect rc = contentsRect(); - ProcessKeys(); - if (m_renderer) - { - PreWidgetRendering(); - - m_Camera.SetFrustum(m_Camera.GetViewSurfaceX(), m_Camera.GetViewSurfaceZ(), m_Camera.GetFov(), 0.02f, 10000, m_Camera.GetPixelAspectRatio()); - const int w = rc.width(); - const int h = rc.height(); - m_Camera.SetFrustum(w, h, DEG2RAD(mv_fov), 0.0101f, 10000.0f); - - if (GetIEditor()->IsInPreviewMode()) - { - GetISystem()->SetViewCamera(m_Camera); - } - - Vec3 clearColor = mv_backgroundColor; - m_renderer->SetClearColor(clearColor); - m_renderer->SetCamera(m_Camera); - - auto colorf = ColorF(clearColor, 1.0f); - m_renderer->ClearTargetsImmediately(FRT_CLEAR | FRT_CLEAR_IMMEDIATE, colorf); - m_renderer->ResetToDefault(); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - - { - CScopedWireFrameMode scopedWireFrame(m_renderer, mv_showWireframe1 ? R_WIREFRAME_MODE : R_SOLID_MODE); - DrawModel(passInfo); - } - - PostWidgetRendering(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawSkyBox(const SRenderingPassInfo& passInfo) -{ - CRenderObject* pObj = m_renderer->EF_GetObject_Temp(passInfo.ThreadID()); - pObj->m_II.m_Matrix.SetTranslationMat(GetViewTM().GetTranslation()); - - if (m_pSkyboxName) - { - SShaderItem skyBoxShaderItem(m_pSkyBoxShader); - m_renderer->EF_AddEf(m_pRESky, skyBoxShaderItem, pObj, passInfo, EFSLIST_GENERAL, 1, SRendItemSorter::CreateRendItemSorter(passInfo)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimBack() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFastBack() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFastForward() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFront() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimPlay() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::mouseDoubleClickEvent(QMouseEvent* event) -{ - // TODO: Add your message handler code here and/or call default - - CRenderViewport::mouseDoubleClickEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - Matrix34 tm; - tm.SetIdentity(); - SetViewTM(tm); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnLightColor([[maybe_unused]] IVariable* var) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowNormals([[maybe_unused]] IVariable* var) -{ - bool enable = mv_showNormals; - GetIEditor()->SetConsoleVar("r_ShowNormals", (enable) ? 1 : 0); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowTangents([[maybe_unused]] IVariable* var) -{ - bool enable = mv_showTangents; - GetIEditor()->SetConsoleVar("r_ShowTangents", (enable) ? 1 : 0); -} - - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnCharPhysics([[maybe_unused]] IVariable* var) -{ - bool enable = mv_useCharPhysics; - GetIEditor()->SetConsoleVar("ca_UsePhysics", enable); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowShaders([[maybe_unused]] IVariable* var) -{ - bool bEnable = mv_showShaders; - GetIEditor()->SetConsoleVar("r_ProfileShaders", bEnable); -} - -void CModelViewport::OnDestroy() -{ - ReleaseObject(); - if (m_pRESky) - { - m_pRESky->Release(false); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnActivate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnDeactivate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Update() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - CRenderViewport::Update(); - - DrawInfo(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawInfo() const -{ - if (GetIEditor()->Get3DEngine()) - { - ICVar* pDisplayInfo = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (pDisplayInfo && pDisplayInfo->GetIVal() != 0) - { - const float fps = gEnv->pTimer->GetFrameRate(); - const float x = (float)gEnv->pRenderer->GetWidth() - 5.0f; - - gEnv->p3DEngine->DrawTextRightAligned(x, 1, "FPS: %.2f", fps); - - int nPolygons, nShadowVolPolys; - gEnv->pRenderer->GetPolyCount(nPolygons, nShadowVolPolys); - int nDrawCalls = gEnv->pRenderer->GetCurrentNumberOfDrawCalls(); - gEnv->p3DEngine->DrawTextRightAligned(x, 20, "Tris:%2d,%03d - DP:%d", nPolygons / 1000, nPolygons % 1000, nDrawCalls); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CModelViewport::CanDrop([[maybe_unused]] const QPoint& point, IDataBaseItem* pItem) -{ - if (!pItem) - { - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Drop([[maybe_unused]] const QPoint& point, [[maybe_unused]] IDataBaseItem* pItem) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Physicalize() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::RePhysicalize() -{ - Physicalize(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SetPaused(bool bPaused) -{ - //return; - if (m_bPaused != bPaused) - { - m_bPaused = bPaused; - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawModel(const SRenderingPassInfo& passInfo) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - m_vCamPos = GetCamera().GetPosition(); - const QRect rc = contentsRect(); - //GetISystem()->SetViewCamera( m_Camera ); - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - m_renderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->EF_ClearSkinningDataPool(); - m_renderer->EF_StartEf(passInfo); - - ////////////////////////////////////////////////////////////////////////// - // Draw lights. - ////////////////////////////////////////////////////////////////////////// - if (mv_lighting == true) - { - pAuxGeom->DrawSphere(m_VPLight.m_Origin, 0.2f, ColorB(255, 255, 0, 255)); - } - - gEnv->pConsole->GetCVar("ca_DrawWireframe")->Set(mv_showWireframe2); - gEnv->pConsole->GetCVar("ca_DrawTangents")->Set(mv_showTangents); - gEnv->pConsole->GetCVar("ca_DrawBinormals")->Set(mv_showBinormals); - gEnv->pConsole->GetCVar("ca_DrawNormals")->Set(mv_showNormals); - - DrawLights(passInfo); - - - //----------------------------------------------------------------------------- - //----- Render Static Object (handled by 3DEngine) ---- - //----------------------------------------------------------------------------- - // calculate LOD - - f32 fDistance = GetViewTM().GetTranslation().GetLength(); - SRendParams rp; - rp.fDistance = fDistance; - - Matrix34 tm; - tm.SetIdentity(); - rp.pMatrix = &tm; - rp.pPrevMatrix = &tm; - - Vec3 vAmbient; - mv_objectAmbientColor.Get(vAmbient); - - rp.AmbientColor.r = vAmbient.x * mv_lightMultiplier; - rp.AmbientColor.g = vAmbient.y * mv_lightMultiplier; - rp.AmbientColor.b = vAmbient.z * mv_lightMultiplier; - rp.AmbientColor.a = 1; - - rp.nDLightMask = 7; - if (mv_lighting == false) - { - rp.nDLightMask = 0; - } - - rp.dwFObjFlags = 0; - - //----------------------------------------------------------------------------- - //----- Render Static Object (handled by 3DEngine) ---- - //----------------------------------------------------------------------------- - if (m_object) - { - m_object->Render(rp, passInfo); - if (mv_showGrid) - { - DrawFloorGrid(Quat(IDENTITY), Vec3(ZERO), Matrix33(IDENTITY)); - } - - if (mv_showBase) - { - DrawCoordSystem(IDENTITY, 10.0f); - } - } - - m_renderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); -} - - -void CModelViewport::DrawLights(const SRenderingPassInfo& passInfo) -{ - if (mv_animateLights) - { - m_LightRotationRadian += m_AverageFrameTime; - } - - if (m_LightRotationRadian > gf_PI) - { - m_LightRotationRadian = -gf_PI; - } - - Matrix33 LightRot33 = Matrix33::CreateRotationZ(m_LightRotationRadian); - - Vec3 LPos0 = Vec3(-mv_lightOrbit, mv_lightOrbit, mv_lightOrbit); - m_VPLight.SetPosition(LightRot33 * LPos0 + m_PhysicalLocation.t); - Vec3 d = mv_lightDiffuseColor; - m_VPLight.SetLightColor(ColorF(d.x * mv_lightMultiplier, d.y * mv_lightMultiplier, d.z * mv_lightMultiplier, 0)); - m_VPLight.SetSpecularMult(mv_lightSpecMultiplier); - m_VPLight.m_fRadius = mv_lightRadius; - m_VPLight.m_Flags = DLF_SUN | DLF_DIRECTIONAL; - - if (mv_lighting == true) - { - m_renderer->EF_ADDDlight(&m_VPLight, passInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::PlayAnimation([[maybe_unused]] const char* szName) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawFloorGrid(const Quat& m33, const Vec3& vPhysicalLocation, const Matrix33& rGridRot) -{ - if (!m_renderer) - { - return; - } - - float XR = 45; - float YR = 45; - - - - - - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - pAuxGeom->SetRenderFlags(e_Def3DPublicRenderflags); - - Vec3 axis = m33.GetColumn0(); - - Matrix33 SlopeMat33 = rGridRot; - uint32 GroundAlign = 1; - if (GroundAlign == 0) - { - SlopeMat33 = Matrix33::CreateRotationAA(m_absCurrentSlope, axis); - } - - - m_GridOrigin = Vec3(floorf(vPhysicalLocation.x), floorf(vPhysicalLocation.y), vPhysicalLocation.z); - - - Matrix33 ScaleMat33 = IDENTITY; - Vec3 rh = Matrix33::CreateRotationY(m_absCurrentSlope) * Vec3(1.0f, 0.0f, 0.0f); - if (rh.x) - { - Vec3 xback = SlopeMat33.GetRow(0); - Vec3 yback = SlopeMat33.GetRow(1); - f32 ratiox = 1.0f / Vec3(xback.x, xback.y, 0.0f).GetLength(); - f32 ratioy = 1.0f / Vec3(yback.x, yback.y, 0.0f).GetLength(); - - f32 ratio = 1.0f / rh.x; - // Vec3 h=Vec3((m_GridOrigin.x-vPhysicalLocation.x)*ratiox,(m_GridOrigin.y-vPhysicalLocation.y)*ratioy,0.0f); - Vec3 h = Vec3(m_GridOrigin.x - vPhysicalLocation.x, m_GridOrigin.y - vPhysicalLocation.y, 0.0f); - Vec3 nh = SlopeMat33 * h; - m_GridOrigin.z += nh.z * ratio; - - ScaleMat33 = Matrix33::CreateScale(Vec3(ratiox, ratioy, 0.0f)); - - // float color1[4] = {0,1,0,1}; - // m_renderer->Draw2dLabel(12,g_ypos,1.6f,color1,false,"h: %f %f %f h.z: %f ratio: %f ratiox: %f ratioy: %f",h.x,h.y,h.z, nh.z,ratio,ratiox,ratioy); - // g_ypos+=18; - } - - Matrix33 _m33; - _m33.SetIdentity(); - AABB aabb1 = AABB(Vec3(-0.03f, -YR, -0.001f), Vec3(0.03f, YR, 0.001f)); - OBB _obb1 = OBB::CreateOBBfromAABB(SlopeMat33, aabb1); - AABB aabb2 = AABB(Vec3(-XR, -0.03f, -0.001f), Vec3(XR, 0.03f, 0.001f)); - OBB _obb2 = OBB::CreateOBBfromAABB(SlopeMat33, aabb2); - - SlopeMat33 = SlopeMat33 * ScaleMat33; - // Draw grid. - float step = 0.25f; - for (float x = -XR; x < XR; x += step) - { - Vec3 p0 = Vec3(x, -YR, 0); - Vec3 p1 = Vec3(x, YR, 0); - //pAuxGeom->DrawLine( SlopeMat33*p0,RGBA8(0x7f,0x7f,0x7f,0x00), SlopeMat33*p1,RGBA8(0x7f,0x7f,0x7f,0x00) ); - int32 intx = int32(x); - if (fabsf(intx - x) < 0.001f) - { - pAuxGeom->DrawOBB(_obb1, SlopeMat33 * Vec3(x, 0.0f, 0.0f) + m_GridOrigin, 1, RGBA8(0x9f, 0x9f, 0x9f, 0x00), eBBD_Faceted); - } - else - { - pAuxGeom->DrawLine(SlopeMat33 * p0 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00), SlopeMat33 * p1 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00)); - } - } - - for (float y = -YR; y < YR; y += step) - { - Vec3 p0 = Vec3(-XR, y, 0); - Vec3 p1 = Vec3(XR, y, 0); - // pAuxGeom->DrawLine( SlopeMat33*p0,RGBA8(0x7f,0x7f,0x7f,0x00), SlopeMat33*p1,RGBA8(0x7f,0x7f,0x7f,0x00) ); - int32 inty = int32(y); - if (fabsf(inty - y) < 0.001f) - { - pAuxGeom->DrawOBB(_obb2, SlopeMat33 * Vec3(0.0f, y, 0.0f) + m_GridOrigin, 1, RGBA8(0x9f, 0x9f, 0x9f, 0x00), eBBD_Faceted); - } - else - { - pAuxGeom->DrawLine(SlopeMat33 * p0 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00), SlopeMat33 * p1 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00)); - } - } - - // TODO - the grid should probably be an IRenderNode at some point - // flushing grid geometry now so it will not override transparent - // objects later in the render pipeline. - pAuxGeom->Commit(); -} - - -//-------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------- -void CModelViewport::DrawCoordSystem(const QuatT& location, f32 length) -{ - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags renderFlags(e_Def3DPublicRenderflags); - pAuxGeom->SetRenderFlags(renderFlags); - - Vec3 absAxisX = location.q.GetColumn0(); - Vec3 absAxisY = location.q.GetColumn1(); - Vec3 absAxisZ = location.q.GetColumn2(); - - const f32 scale = 3.0f; - const f32 size = 0.009f; - AABB xaabb = AABB(Vec3(-length * scale, -size * scale, -size * scale), Vec3(length * scale, size * scale, size * scale)); - AABB yaabb = AABB(Vec3(-size * scale, -length * scale, -size * scale), Vec3(size * scale, length * scale, size * scale)); - AABB zaabb = AABB(Vec3(-size * scale, -size * scale, -length * scale), Vec3(size * scale, size * scale, length * scale)); - - OBB obb; - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), xaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0xff, 0x00, 0x00, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisX * length * scale, absAxisX, 0.03f * scale, 0.15f * scale, RGBA8(0xff, 0x00, 0x00, 0xff)); - - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), yaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0x00, 0xff, 0x00, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisY * length * scale, absAxisY, 0.03f * scale, 0.15f * scale, RGBA8(0x00, 0xff, 0x00, 0xff)); - - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), zaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0x00, 0x00, 0xff, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisZ * length * scale, absAxisZ, 0.03f * scale, 0.15f * scale, RGBA8(0x00, 0x00, 0xff, 0xff)); -} - - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnLightMultiplier([[maybe_unused]] IVariable* var) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SetSelected(bool const bSelect) -{ - // If a modelviewport gets activated, and listeners will be activated, disable the main viewport listener and re-enable when you lose focus. - if (gEnv->pSystem) - { - IViewSystem* const pIViewSystem = gEnv->pSystem->GetIViewSystem(); - - if (pIViewSystem) - { - pIViewSystem->SetControlAudioListeners(!bSelect); - } - } -} - -#include diff --git a/Code/Sandbox/Editor/ModelViewport.h b/Code/Sandbox/Editor/ModelViewport.h deleted file mode 100644 index a5d1ac2a26..0000000000 --- a/Code/Sandbox/Editor/ModelViewport.h +++ /dev/null @@ -1,258 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -//////////////////////////////////////////////////////////////////////////// -// -// Crytek Engine Source File. -// Copyright (C), Crytek Studios, 2001. -// ------------------------------------------------------------------------- -// File name: ModelViewport.h -// Version: v1.00 -// Created: 8/10/2001 by Timur. -// Compilers: Visual C++ 6.0 -// Description: -// ------------------------------------------------------------------------- -// History: -// -//////////////////////////////////////////////////////////////////////////// -#ifndef CRYINCLUDE_EDITOR_MODELVIEWPORT_H -#define CRYINCLUDE_EDITOR_MODELVIEWPORT_H - -#if !defined(Q_MOC_RUN) -#include "RenderViewport.h" -#include "Util/Variable.h" -#endif - -struct IPhysicalEntity; - -///////////////////////////////////////////////////////////////////////////// -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -// CModelViewport window -class SANDBOX_API CModelViewport - : public CRenderViewport -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT - // Construction -public: - CModelViewport(const char* settingsPath = "Settings\\CharacterEditorUserOptions", QWidget* parent = nullptr); - virtual ~CModelViewport(); - - virtual EViewportType GetType() const { return ET_ViewportModel; } - virtual void SetType([[maybe_unused]] EViewportType type) { assert(type == ET_ViewportModel); }; - - virtual void LoadObject(const QString& obj, float scale); - - virtual void OnActivate(); - virtual void OnDeactivate(); - - virtual bool CanDrop(const QPoint& point, IDataBaseItem* pItem); - virtual void Drop(const QPoint& point, IDataBaseItem* pItem); - - virtual void SetSelected(bool const bSelect); - - // Callbacks. - void OnShowShaders(IVariable* var); - void OnShowNormals(IVariable* var); - void OnShowTangents(IVariable* var); - - void OnShowPortals(IVariable* var); - void OnShowShadowVolumes(IVariable* var); - void OnShowTextureUsage(IVariable* var); - void OnCharPhysics(IVariable* var); - void OnShowOcclusion(IVariable* var); - - void OnLightColor(IVariable* var); - void OnLightMultiplier(IVariable* var); - void OnDisableVisibility(IVariable* var); - - IStatObj* GetStaticObject(){ return m_object; } - - void GetOnDisableVisibility(IVariable* var); - - const CVarObject* GetVarObject() const { return &m_vars; } - CVarObject* GetVarObject() { return &m_vars; } - - virtual void Update(); - - - void UseWeaponIK([[maybe_unused]] bool val) { m_weaponIK = true; } - - void ReleaseObject(); - void RePhysicalize(); - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Vec3 m_GridOrigin; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - void SetPaused(bool bPaused); - bool GetPaused() {return m_bPaused; } - - bool IsCameraAttached() const{ return mv_AttachCamera; } - - virtual void PlayAnimation(const char* szName); - - const QString& GetLoadedFileName() const { return m_loadedFile; } - - void Physicalize(); - -protected: - - void LoadStaticObject(const QString& file); - - // Called to render stuff. - virtual void OnRender(); - - virtual void DrawFloorGrid(const Quat& tmRotation, const Vec3& MotionTranslation, const Matrix33& rGridRot); - void DrawCoordSystem(const QuatT& q, f32 length); - - void SaveDebugOptions() const; - void RestoreDebugOptions(); - - virtual void DrawModel(const SRenderingPassInfo& passInfo); - virtual void DrawLights(const SRenderingPassInfo& passInfo); - virtual void DrawSkyBox(const SRenderingPassInfo& passInfo); - - void DrawInfo() const; - - void SetConsoleVar(const char* var, int value); - - void OnEditorNotifyEvent(EEditorNotifyEvent event) - { - if (event != eNotify_OnBeginGameMode) - { - // the base class responds to this by forcing itself to be the current context. - // we don't want that to be the case for previewer viewports. - CRenderViewport::OnEditorNotifyEvent(event); - } - } - - IStatObj* m_object; - IStatObj* m_weaponModel; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - - QString m_attachBone; - AABB m_AABB; - - struct BBox - { - OBB obb; - Vec3 pos; - ColorB col; - }; - std::vector m_arrBBoxes; - - // Camera control. - float m_camRadius; - - // True to show grid. - bool m_bGrid; - bool m_bBase; - - QString m_settingsPath; - - bool m_weaponIK; - - QString m_loadedFile; - CDLight m_VPLight; - - f32 m_LightRotationRadian; - - class CRESky* m_pRESky; - struct ICVar* m_pSkyboxName; - IShader* m_pSkyBoxShader; - - //--------------------------------------------------- - //--- debug options --- - //--------------------------------------------------- - CVariable mv_showGrid; - CVariable mv_showBase; - CVariable mv_showLocator; - CVariable mv_InPlaceMovement; - CVariable mv_StrafingControl; - - CVariable mv_showWireframe1; //draw wireframe instead of solid-geometry. - CVariable mv_showWireframe2; //this one is software-wireframe rendered on top of the solid geometry - CVariable mv_showTangents; - CVariable mv_showBinormals; - CVariable mv_showNormals; - - CVariable mv_showSkeleton; - CVariable mv_showJointNames; - CVariable mv_showJointsValues; - CVariable mv_showStartLocation; - CVariable mv_showMotionParam; - CVariable mv_UniformScaling; - - CVariable mv_printDebugText; - CVariable mv_AttachCamera; - - CVariable mv_showShaders; - - CVariable mv_lighting; - CVariable mv_animateLights; - - CVariable mv_backgroundColor; - CVariable mv_objectAmbientColor; - - CVariable mv_lightDiffuseColor; - CVariable mv_lightMultiplier; - CVariable mv_lightSpecMultiplier; - CVariable mv_lightRadius; - CVariable mv_lightOrbit; - - CVariable mv_fov; - CVariable mv_showPhysics; - CVariable mv_useCharPhysics; - CVariable mv_showPhysicsTetriders; - CVariable mv_forceLODNum; - - CVariableArray mv_advancedTable; - - CVarObject m_vars; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -public slots: - virtual void OnAnimPlay(); - virtual void OnAnimBack(); - virtual void OnAnimFastBack(); - virtual void OnAnimFastForward(); - virtual void OnAnimFront(); -protected: - bool m_bPaused; - - void OnDestroy(); - void mouseDoubleClickEvent(QMouseEvent* event) override; - -private: - struct VariableCallbackIndex - { - enum : unsigned char - { - OnCharPhysics = 0, - OnLightColor, - OnLightMultiplier, - OnShowShaders, - - // must be at the end - Count, - }; - }; -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - AZStd::fixed_vector< IVariable::OnSetCallback, VariableCallbackIndex::Count > m_onSetCallbacksCache; -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_MODELVIEWPORT_H diff --git a/Code/Sandbox/Editor/ModelViewportDC.cpp b/Code/Sandbox/Editor/ModelViewportDC.cpp deleted file mode 100644 index 9424a12c0c..0000000000 --- a/Code/Sandbox/Editor/ModelViewportDC.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - - - - - - - - - - diff --git a/Code/Sandbox/Editor/Objects/BaseObject.cpp b/Code/Sandbox/Editor/Objects/BaseObject.cpp index 109b28798f..3ec505172e 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.cpp +++ b/Code/Sandbox/Editor/Objects/BaseObject.cpp @@ -37,6 +37,8 @@ #include "ViewManager.h" #include "IEditorImpl.h" #include "GameEngine.h" +#include +#include // To use the Andrew's algorithm in order to make convex hull from the points, this header is needed. #include "Util/GeometryUtil.h" @@ -821,9 +823,8 @@ void CBaseObject::GetLocalBounds(AABB& box) } ////////////////////////////////////////////////////////////////////////// -void CBaseObject::SetModified(bool boModifiedTransformOnly) +void CBaseObject::SetModified(bool) { - ((CObjectManager*)GetObjectManager())->OnObjectModified(this, false, boModifiedTransformOnly); } void CBaseObject::DrawDefault(DisplayContext& dc, const QColor& labelColor) diff --git a/Code/Sandbox/Editor/Objects/BaseObject.h b/Code/Sandbox/Editor/Objects/BaseObject.h index 44df1e5757..5d6f800a58 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.h +++ b/Code/Sandbox/Editor/Objects/BaseObject.h @@ -35,7 +35,6 @@ class CUndoBaseObject; class CObjectManager; class CGizmo; class CObjectArchive; -class CEdGeometry; struct SSubObjSelectionModifyContext; struct SRayHitInfo; class ISubObjectSelectionReferenceFrameCalculator; @@ -580,10 +579,6 @@ public: virtual void ModifySubObjSelection([[maybe_unused]] SSubObjSelectionModifyContext& modCtx) {}; virtual void AcceptSubObjectModify() {}; - // Request a geometry pointer from the object. - // Return NULL if geometry can not be retrieved or object does not support geometries. - virtual CEdGeometry* GetGeometry() { return 0; }; - //! In This function variables of the object must be initialized. virtual void InitVariables() {}; diff --git a/Code/Sandbox/Editor/Objects/DisplayContext.h b/Code/Sandbox/Editor/Objects/DisplayContext.h index a8181e1d1b..13363a923e 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContext.h +++ b/Code/Sandbox/Editor/Objects/DisplayContext.h @@ -33,7 +33,6 @@ struct IDisplayViewport; struct IRenderer; struct IRenderAuxGeom; struct IIconManager; -struct I3DEngine; class CDisplaySettings; class CCamera; @@ -70,7 +69,6 @@ struct SANDBOX_API DisplayContext IRenderer* renderer; IRenderAuxGeom* pRenderAuxGeom; IIconManager* pIconManager; - I3DEngine* engine; CCamera* camera; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AABB box; // Bounding box of volume that need to be repainted. diff --git a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl index dd5c248357..4d284faea7 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl +++ b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl @@ -18,8 +18,6 @@ #include "Include/IIconManager.h" #include "Include/IDisplayViewport.h" -#include - #include #include @@ -32,7 +30,6 @@ DisplayContext::DisplayContext() { view = 0; renderer = 0; - engine = 0; flags = 0; settings = 0; pIconManager = 0; @@ -981,27 +978,8 @@ void DisplayContext::RenderObject(int objectType, const Vec3& pos, float scale) } ////////////////////////////////////////////////////////////////////////// -void DisplayContext::RenderObject(int objectType, const Matrix34& tm) +void DisplayContext::RenderObject(int, const Matrix34&) { - IStatObj* object = pIconManager ? pIconManager->GetObject((EStatObject)objectType) : 0; - if (object) - { - float color[4]; - color[0] = m_color4b.r * (1.0f / 255.0f); - color[1] = m_color4b.g * (1.0f / 255.0f); - color[2] = m_color4b.b * (1.0f / 255.0f); - color[3] = m_color4b.a * (1.0f / 255.0f); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(GetIEditor()->GetSystem()->GetViewCamera()); - - Matrix34 xform = m_matrixStack[m_currentMatrix] * tm; - SRendParams rp; - rp.pMatrix = &xform; - rp.AmbientColor = ColorF(color[0], color[1], color[2], 1); - rp.fAlpha = color[3]; - - object->Render(rp, passInfo); - } } ///////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Objects/EntityObject.cpp b/Code/Sandbox/Editor/Objects/EntityObject.cpp index 0b2627091c..17e9fdda5c 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.cpp +++ b/Code/Sandbox/Editor/Objects/EntityObject.cpp @@ -32,6 +32,8 @@ #include "HitContext.h" #include "Objects/SelectionGroup.h" +#include +#include ////////////////////////////////////////////////////////////////////////// //! Undo Entity Link @@ -1926,55 +1928,6 @@ void CEntityObject::OnContextMenu(QMenu* pMenu) CBaseObject::OnContextMenu(pMenu); } -////////////////////////////////////////////////////////////////////////// -IOpticsElementBasePtr CEntityObject::GetOpticsElement() -{ - CDLight* pLight = GetLightProperty(); - if (pLight == NULL) - { - return NULL; - } - return pLight->GetLensOpticsElement(); -} - -////////////////////////////////////////////////////////////////////////// -void CEntityObject::SetOpticsName(const QString& opticsFullName) -{ - if (opticsFullName.isEmpty()) - { - CDLight* pLight = GetLightProperty(); - if (pLight) - { - pLight->SetLensOpticsElement(NULL); - } - } -} - -////////////////////////////////////////////////////////////////////////// -CDLight* CEntityObject::GetLightProperty() const -{ - const PodArray* pLightEntities = GetIEditor()->Get3DEngine()->GetLightEntities(); - if (pLightEntities == NULL) - { - return NULL; - } - for (int i = 0, iLightSize(pLightEntities->Count()); i < iLightSize; ++i) - { - ILightSource* pLightSource = pLightEntities->GetAt(i); - if (pLightSource == NULL) - { - continue; - } - CDLight& lightProperty = pLightSource->GetLightProperties(); - if (GetName() != lightProperty.m_sName) - { - continue; - } - return &lightProperty; - } - return NULL; -} - ////////////////////////////////////////////////////////////////////////// void CEntityObject::PreInitLightProperty() { diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index a287cd8828..85368f7804 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -214,8 +214,6 @@ public: QString GetLightAnimation() const; IVariable* GetLightVariable(const char* name) const; - IOpticsElementBasePtr GetOpticsElement(); - void SetOpticsName(const QString& opticsFullName); void PreInitLightProperty(); void UpdateLightProperty(); @@ -230,8 +228,6 @@ public: void RegisterListener(IEntityObjectListener* pListener); void UnregisterListener(IEntityObjectListener* pListener); - CDLight* GetLightProperty() const; - protected: template void SetEntityProperty(const char* name, T value); diff --git a/Code/Sandbox/Editor/Objects/ObjectManager.cpp b/Code/Sandbox/Editor/Objects/ObjectManager.cpp index 39174774be..d383fb0e1b 100644 --- a/Code/Sandbox/Editor/Objects/ObjectManager.cpp +++ b/Code/Sandbox/Editor/Objects/ObjectManager.cpp @@ -400,8 +400,6 @@ void CObjectManager::DeleteObject(CBaseObject* obj) CUndo::Record(new CUndoBaseObjectDelete(obj)); } - OnObjectModified(obj, true, false); - AABB objAAB; obj->GetBoundBox(objAAB); GetIEditor()->GetGameEngine()->OnAreaModified(objAAB); @@ -2477,17 +2475,6 @@ IGizmoManager* CObjectManager::GetGizmoManager() return m_gizmoManager; } -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -void CObjectManager::OnObjectModified(CBaseObject* pObject, [[maybe_unused]] bool bDelete, [[maybe_unused]] bool boModifiedTransformOnly) -{ - if (IRenderNode* pRenderNode = pObject->GetEngineNode()) - { - GetIEditor()->Get3DEngine()->OnObjectModified(pRenderNode, pRenderNode->GetRndFlags()); - } -} - ////////////////////////////////////////////////////////////////////////// bool CObjectManager::IsLightClass(CBaseObject* pObject) { diff --git a/Code/Sandbox/Editor/Objects/ObjectManager.h b/Code/Sandbox/Editor/Objects/ObjectManager.h index 26905c47cd..4939fdeefc 100644 --- a/Code/Sandbox/Editor/Objects/ObjectManager.h +++ b/Code/Sandbox/Editor/Objects/ObjectManager.h @@ -326,9 +326,6 @@ public: // Gathers all resources used by all objects. void GatherUsedResources(CUsedResources& resources); - // Called when object gets modified. - void OnObjectModified(CBaseObject* pObject, bool bDelete, bool boModifiedTransformOnly); - virtual bool IsLightClass(CBaseObject* pObject); virtual void FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue); diff --git a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp index 08abf8f763..98e00645ee 100644 --- a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp +++ b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp @@ -22,6 +22,7 @@ #include "ViewManager.h" #include "Include/IObjectManager.h" +#include ////////////////////////////////////////////////////////////////////////// CSelectionGroup::CSelectionGroup() diff --git a/Code/Sandbox/Editor/PanelPreview.cpp b/Code/Sandbox/Editor/PanelPreview.cpp deleted file mode 100644 index fe5ea7be9b..0000000000 --- a/Code/Sandbox/Editor/PanelPreview.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "PanelPreview.h" - -// Qt -#include - -// CPanelPreview dialog - -CPanelPreview::CPanelPreview(QWidget* pParent /*=nullptr*/) - : QWidget(pParent) - , m_previewCtrl(new CPreviewModelCtrl(this)) -{ - QBoxLayout* layout = new QHBoxLayout; - layout->setMargin(0); - layout->addWidget(m_previewCtrl); - setLayout(layout); -} - -////////////////////////////////////////////////////////////////////////// -void CPanelPreview::LoadFile(const QString& filename) -{ - if (!filename.isEmpty()) - { - m_previewCtrl->EnableUpdate(false); - m_previewCtrl->LoadFile(filename, false); - } -} - diff --git a/Code/Sandbox/Editor/PanelPreview.h b/Code/Sandbox/Editor/PanelPreview.h deleted file mode 100644 index d2c951ba4e..0000000000 --- a/Code/Sandbox/Editor/PanelPreview.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_PANELPREVIEW_H -#define CRYINCLUDE_EDITOR_PANELPREVIEW_H -#pragma once - -// CPanelPreview dialog - -#include "Controls/PreviewModelCtrl.h" - - -class CPanelPreview - : public QWidget -{ -public: - CPanelPreview(QWidget* pParent = nullptr); // standard constructor - - void LoadFile(const QString& filename); - - QSize sizeHint() const override - { - return QSize(130, 240); - } - -protected: - CPreviewModelCtrl* m_previewCtrl; -}; - -#endif // CRYINCLUDE_EDITOR_PANELPREVIEW_H diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 325779a401..d24f569047 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -55,7 +55,6 @@ // CryCommon -#include #include // AzFramework @@ -89,6 +88,10 @@ #include +#include +#include +#include + AZ_CVAR( bool, ed_visibility_use, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable/disable using the new IVisibilitySystem for Entity visibility determination"); @@ -249,10 +252,6 @@ CRenderViewport::~CRenderViewport() ////////////////////////////////////////////////////////////////////////// int CRenderViewport::OnCreate() { - m_renderer = GetIEditor()->GetRenderer(); - m_engine = GetIEditor()->Get3DEngine(); - assert(m_engine); - CreateRenderContext(); return 0; @@ -1033,7 +1032,7 @@ void CRenderViewport::Update() return; } - if (!m_renderer || !m_engine || m_rcClient.isEmpty() || GetIEditor()->IsInMatEditMode()) + if (!m_renderer || m_rcClient.isEmpty() || GetIEditor()->IsInMatEditMode()) { return; } @@ -1156,9 +1155,6 @@ void CRenderViewport::Update() m_renderer->SetClearColor(Vec3(0.4f, 0.4f, 0.4f)); - // 3D engine stats - GetIEditor()->GetSystem()->RenderBegin(); - InitDisplayContext(); OnRender(); @@ -1184,8 +1180,6 @@ void CRenderViewport::Update() } } - GetIEditor()->GetSystem()->RenderEnd(m_bRenderStats); - gEnv->pSystem->SetViewCamera(CurCamera); } @@ -1421,8 +1415,6 @@ void CRenderViewport::OnRender() // This is necessary so that automated editor tests using the null renderer to test systems like dynamic vegetation // are still able to manipulate the current logical camera position, even if nothing is rendered. GetIEditor()->GetSystem()->SetViewCamera(m_Camera); - GetIEditor()->GetRenderer()->SetCamera(gEnv->pSystem->GetViewCamera()); - m_engine->RenderWorld(0, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera), __FUNCTION__); return; } @@ -1495,7 +1487,7 @@ void CRenderViewport::OnRender() } } - m_Camera.SetFrustum(w, h, fov, fNearZ, gEnv->p3DEngine->GetMaxViewDistance()); + m_Camera.SetFrustum(w, h, fov, fNearZ); } GetIEditor()->GetSystem()->SetViewCamera(m_Camera); @@ -1556,11 +1548,6 @@ void CRenderViewport::OnRender() m_renderer->ClearTargetsLater(FRT_CLEAR_COLOR, viewportBackgroundColor); DrawBackground(); } - - if (!m_renderer->IsStereoEnabled()) - { - GetIEditor()->GetSystem()->RenderStatistics(); - } } ////////////////////////////////////////////////////////////////////////// @@ -1590,7 +1577,6 @@ void CRenderViewport::InitDisplayContext() displayContext.settings = GetIEditor()->GetDisplaySettings(); displayContext.view = this; displayContext.renderer = m_renderer; - displayContext.engine = m_engine; displayContext.box.min = Vec3(-100000.0f, -100000.0f, -100000.0f); displayContext.box.max = Vec3(100000.0f, 100000.0f, 100000.0f); displayContext.camera = &m_Camera; @@ -2467,7 +2453,6 @@ void CRenderViewport::ToggleCameraObject() { if (m_viewSourceType == ViewSourceType::SequenceCamera) { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); ResetToViewSourceType(ViewSourceType::LegacyCamera); } else @@ -2789,11 +2774,6 @@ void CRenderViewport::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) ////////////////////////////////////////////////////////////////////////// void CRenderViewport::RenderSelectedRegion() { - if (!m_engine) - { - return; - } - AABB box; GetIEditor()->GetSelectedRegion(box); if (box.IsEmpty()) @@ -3385,19 +3365,9 @@ bool CRenderViewport::AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, } ////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const +bool CRenderViewport::RayRenderMeshIntersection(IRenderMesh*, const Vec3&, const Vec3&, Vec3&, Vec3&) const { - SRayHitInfo hitInfo; - hitInfo.bUseCache = false; - hitInfo.bInFirstHit = false; - hitInfo.inRay.origin = vInPos; - hitInfo.inRay.direction = vInDir.GetNormalized(); - hitInfo.inReferencePoint = vInPos; - hitInfo.fMaxHitDistance = 0; - bool bRes = GetIEditor()->Get3DEngine()->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); - vOutPos = hitInfo.vHitPos; - vOutNormal = hitInfo.vHitNormal; - return bRes; + return false; } ////////////////////////////////////////////////////////////////////////// @@ -3682,7 +3652,6 @@ void CRenderViewport::SetDefaultCamera() return; } ResetToViewSourceType(ViewSourceType::None); - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); GetViewManager()->SetCameraObjectId(m_cameraObjectId); SetName(m_defaultViewName); SetViewTM(m_defaultViewTM); @@ -3861,23 +3830,8 @@ void CRenderViewport::SetViewAndMovementLockFromEntityPerspective(const AZ::Enti bool CRenderViewport::GetActiveCameraPosition(AZ::Vector3& cameraPos) { - if (m_pPrimaryViewport == this) - { - if (GetIEditor()->IsInGameMode()) - { - const Vec3 camPos = m_engine->GetRenderingCamera().GetPosition(); - cameraPos = LYVec3ToAZVec3(camPos); - } - else - { - // Use viewTM, which is synced with the camera and guaranteed to be up-to-date - cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); - } - - return true; - } - - return false; + cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); + return true; } bool CRenderViewport::GetActiveCameraState(AzFramework::CameraState& cameraState) @@ -3886,9 +3840,7 @@ bool CRenderViewport::GetActiveCameraState(AzFramework::CameraState& cameraState { if (GetIEditor()->IsInGameMode()) { - const auto& renderingCamera = m_engine->GetRenderingCamera(); - cameraState = CameraStateFromCCamera( - renderingCamera, renderingCamera.GetFov(), m_rcClient.width(), m_rcClient.height()); + return false; } else { diff --git a/Code/Sandbox/Editor/RenderViewport.h b/Code/Sandbox/Editor/RenderViewport.h index 9985408d25..d70dd59b98 100644 --- a/Code/Sandbox/Editor/RenderViewport.h +++ b/Code/Sandbox/Editor/RenderViewport.h @@ -438,7 +438,6 @@ protected: //! Assigned renderer. IRenderer* m_renderer = nullptr; - I3DEngine* m_engine = nullptr; bool m_bRenderContextCreated = false; bool m_bInRotateMode = false; bool m_bInMoveMode = false; @@ -525,10 +524,6 @@ protected: OBB m_GroundOBB; Vec3 m_GroundOBBPos; - //------------------------------------------- - // Render options. - bool m_bRenderStats = true; - // Index of camera objects. mutable GUID m_cameraObjectId = GUID_NULL; mutable AZ::EntityId m_viewEntityId; diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index d9fdb42c0b..ea8ec828cf 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -75,7 +75,6 @@ #define IDC_PLATFORM_SALEM 2759 #define IDC_GROUPBOX_GLOBALTAGS 2916 #define IDC_GROUPBOX_FRAGMENTTAGS 2917 -#define ID_RESOURCES_GENERATECGFTHUMBNAILS 32894 #define ID_RESOURCES_REDUCEWORKINGSET 32896 #define ID_EDIT_HIDE 32898 #define ID_EDIT_UNHIDEALL 32899 @@ -133,7 +132,6 @@ #define ID_FILE_EDITEDITORINI 33543 #define ID_FILE_EDITLOGFILE 33544 #define ID_PREFERENCES 33546 -#define ID_RELOAD_GEOMETRY 33549 #define ID_REDO 33550 #define ID_SWITCH_PHYSICS 33555 #define ID_REF_COORDS_SYS 33556 diff --git a/Code/Sandbox/Editor/Settings.cpp b/Code/Sandbox/Editor/Settings.cpp index 99a801eedc..15d3e793a5 100644 --- a/Code/Sandbox/Editor/Settings.cpp +++ b/Code/Sandbox/Editor/Settings.cpp @@ -252,8 +252,6 @@ SEditorSettings::SEditorSettings() gui.hSystemFontBold = QFont("Ms Shell Dlg 2", lfHeight, QFont::Bold); gui.hSystemFontItalic = QFont("Ms Shell Dlg 2", lfHeight, QFont::Normal, true); - bForceSkyUpdate = true; - backgroundUpdatePeriod = 0; g_TemporaryLevelName = nullptr; @@ -647,8 +645,6 @@ void SEditorSettings::Save() SaveValue("Settings\\ObjectColors", "GeometryAlpha", objectColorSettings.fGeomAlpha); SaveValue("Settings\\ObjectColors", "ChildGeometryAlpha", objectColorSettings.fChildGeomAlpha); - SaveValue("Settings", "ForceSkyUpdate", gSettings.bForceSkyUpdate); - ////////////////////////////////////////////////////////////////////////// // Smart file open settings ////////////////////////////////////////////////////////////////////////// @@ -873,8 +869,6 @@ void SEditorSettings::Load() LoadValue("Settings\\ObjectColors", "GeometryAlpha", objectColorSettings.fGeomAlpha); LoadValue("Settings\\ObjectColors", "ChildGeometryAlpha", objectColorSettings.fChildGeomAlpha); - LoadValue("Settings", "ForceSkyUpdate", gSettings.bForceSkyUpdate); - ////////////////////////////////////////////////////////////////////////// // Smart file open settings ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Settings.h b/Code/Sandbox/Editor/Settings.h index 511bbb9bbe..93e61bc1ed 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -467,8 +467,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING bool bSettingsManagerMode; - bool bForceSkyUpdate; - bool bAutoSaveTagPoints; bool bNavigationContinuousUpdate; diff --git a/Code/Sandbox/Editor/ThumbnailGenerator.cpp b/Code/Sandbox/Editor/ThumbnailGenerator.cpp deleted file mode 100644 index c2f03a1944..0000000000 --- a/Code/Sandbox/Editor/ThumbnailGenerator.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "ThumbnailGenerator.h" - -// Editor -#include "Util/Image.h" -#include "Util/ImageUtil.h" // for CUmageUtil -#include "WaitProgress.h" // for CWaitProgress - -#if defined(AZ_PLATFORM_MAC) || defined(AZ_PLATFORM_LINUX) -#include -#include -#endif - - - -CThumbnailGenerator::CThumbnailGenerator(void) -{ -} - -CThumbnailGenerator::~CThumbnailGenerator(void) -{ -} - -// Get directory contents. -static bool scan_directory(const QString& root, const QString& path, const QString& file, QStringList& files, bool recursive) -{ - QString fullPath = root + path + file; - QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags; - if (recursive) - { - flags = QDirIterator::Subdirectories; - } - QDirIterator dirIterator(fullPath, {file}, QDir::Files, flags); - if (!dirIterator.hasNext()) - { - return false; - } - else - { - // Find the rest of the .c files. - while (dirIterator.hasNext()) - { - files.push_back(dirIterator.next()); - //FileInfo fi; - //fi.attrib = c_file.attrib; - //fi.name = path + c_file.name; - /* - // Add . after file name without extension. - if (fi.name.find('.') == CString::npos) { - fi.name.append( "." ); - } - */ - //fi.size = c_file.size; - //fi.time = c_file.time_write; - //files.push_back( fi ); - } - } - return true; -} - -#if defined(AZ_PLATFORM_WINDOWS) -#define FileTimeType FILETIME - -inline void GetThumbFileTime(const char* fileName, FILETIME& time) -{ - HANDLE hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (INVALID_HANDLE_VALUE != hFile) - { - GetFileTime(hFile, NULL, NULL, &time); - CloseHandle(hFile); - } -} - -inline void SetThumbFileTime(const char* fileName, FILETIME& time) -{ - HANDLE hFile = CreateFile(fileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (INVALID_HANDLE_VALUE != hFile) - { - SetFileTime(hFile, NULL, NULL, &time); - CloseHandle(hFile); - } -} - -inline bool ThumbFileTimeIsEqual(const FILETIME& ft1, const FILETIME& ft2) -{ - return ft1.dwHighDateTime == ft2.dwHighDateTime && ft1.dwLowDateTime == ft2.dwLowDateTime; -} -#elif defined(AZ_PLATFORM_MAC) || defined(AZ_PLATFORM_LINUX) -#define FileTimeType utimbuf - -inline void GetThumbFileTime(const char* fileName, utimbuf& times) -{ - struct stat sb; - if (stat(fileName, &sb) == 0) - { - times.actime = sb.st_atime; - times.modtime = sb.st_mtime; - } -} - -inline void SetThumbFileTime(const char* fileName, const utimbuf& times) -{ - utime(fileName, ×); -} - -inline bool ThumbFileTimeIsEqual(const utimbuf& ft1, const utimbuf& ft2) -{ - return ft1.modtime == ft2.modtime; -} -#endif - -void CThumbnailGenerator::GenerateForDirectory(const QString& path) -{ - return; - - ////////////////////////////////////////////////////////////////////////// - QStringList files; - //CString dir = GetIEditor()->GetPrimaryCDFolder(); - QString dir = path; - scan_directory(dir, "", "*.*", files, true); - - I3DEngine* engine = GetIEditor()->Get3DEngine(); - - int thumbSize = 128; - CImageEx image; - image.Allocate(thumbSize, thumbSize); - - char drive[_MAX_DRIVE]; - char fdir[_MAX_DIR]; - char fname[_MAX_FNAME]; - char fext[_MAX_EXT]; - char bmpFile[1024]; - - GetIEditor()->ShowConsole(true); - CWaitProgress wait("Generating CGF Thumbnails"); - for (int i = 0; i < files.size(); i++) - { - QString file = dir + files[i]; - _splitpath_s(file.toUtf8().data(), drive, fdir, fname, fext); - - //if (_stricmp(fext,".cgf") != 0 && _stricmp(fext,".bld") != 0) - if (_stricmp(fext, ".cgf") != 0) - { - continue; - } - - if (!wait.Step(100 * i / files.size())) - { - break; - } - - _makepath_s(bmpFile, drive, fdir, fname, ".tmb"); - - FileTimeType ft1, ft2; - GetThumbFileTime(file.toUtf8().data(), ft1); - GetThumbFileTime(bmpFile, ft2); - // Both cgf and bmp have same time stamp. - if (ThumbFileTimeIsEqual(ft1, ft2)) - { - continue; - } - - //CLogFile::FormatLine( "Generating thumbnail for %s...",file ); - - _smart_ptr obj = engine->LoadStatObjAutoRef(file.toUtf8().data(), NULL, NULL, false); - if (obj) - { - assert(!"IStatObj::MakeObjectPicture does not exist anymore"); - // obj->MakeObjectPicture( (unsigned char*)image.GetData(),thumbSize ); - - CImageUtil::SaveBitmap(bmpFile, image); - SetThumbFileTime(bmpFile, ft1); -#if defined(AZ_PLATFORM_WINDOWS) - SetFileAttributes(bmpFile, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED); -#endif - obj->Release(); - } - } - //GetIEditor()->ShowConsole( false ); -} - -void CThumbnailGenerator::GenerateForFile([[maybe_unused]] const QString& fileName) -{ -} diff --git a/Code/Sandbox/Editor/ThumbnailGenerator.h b/Code/Sandbox/Editor/ThumbnailGenerator.h deleted file mode 100644 index ef5a833e60..0000000000 --- a/Code/Sandbox/Editor/ThumbnailGenerator.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H -#define CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H - -#pragma once - - -class CThumbnailGenerator -{ -public: - CThumbnailGenerator(void); - ~CThumbnailGenerator(void); - - void GenerateForDirectory(const QString& path); - void GenerateForFile(const QString& fileName); -}; - -#endif // CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H diff --git a/Code/Sandbox/Editor/TimeOfDay.qrc b/Code/Sandbox/Editor/TimeOfDay.qrc deleted file mode 100644 index 7f45cf485f..0000000000 --- a/Code/Sandbox/Editor/TimeOfDay.qrc +++ /dev/null @@ -1,34 +0,0 @@ - - - TimeOfDay/main-00.png - TimeOfDay/main-01.png - TimeOfDay/main-02.png - TimeOfDay/main-03.png - TimeOfDay/main-04.png - TimeOfDay/main-05.png - TimeOfDay/main-06.png - TimeOfDay/main-07.png - TimeOfDay/main-08.png - TimeOfDay/main-09.png - TimeOfDay/main-10.png - TimeOfDay/main-11.png - TimeOfDay/main-12.png - Common/spline_edit-00.png - Common/spline_edit-01.png - Common/spline_edit-02.png - Common/spline_edit-03.png - Common/spline_edit-04.png - Common/spline_edit-05.png - Common/spline_edit-06.png - Common/spline_edit-07.png - Common/spline_edit-08.png - Common/spline_edit-09.png - Common/spline_edit-10.png - Common/spline_edit-11.png - Common/spline_edit-12.png - Common/spline_edit-13.png - Common/spline_edit-14.png - Common/spline_edit-15.png - Common/spline_edit-16.png - - diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.cpp b/Code/Sandbox/Editor/TimeOfDayDialog.cpp deleted file mode 100644 index 80aa4d5172..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.cpp +++ /dev/null @@ -1,1443 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "TimeOfDayDialog.h" - -// Qt -#include - -// AzToolsFramework -#include - -// CryCommon -#include - -// Editor -#include "Settings.h" -#include "Controls/CurveEditorCtrl.h" -#include "Mission.h" -#include "CryEditDoc.h" -#include "Clipboard.h" -#include "QtViewPaneManager.h" -#include "Undo/Undo.h" -#include "LyViewPaneNames.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -#define PANE_LAYOUT_SECTION _T("DockingPaneLayouts\\TimeOfDay") -#define PANE_LAYOUT_VERSION_ENTRY _T("PaneLayoutVersion") - -namespace TimeOfDayDetails -{ - const float kEpsilon = 0.00001f; - - const int kTimeOfDayDialogLayoutVersion = 0x0002; // bump this up on every substantial pane layout change - - static void SetKeyTangentType(ISplineInterpolator* pSpline, int key, ESplineKeyTangentType type) - { - int flags = (pSpline->GetKeyFlags(key) & ~SPLINE_KEY_TANGENT_IN_MASK) & ~SPLINE_KEY_TANGENT_OUT_MASK; - pSpline->SetKeyFlags(key, flags | (type << SPLINE_KEY_TANGENT_IN_SHIFT) | (type << SPLINE_KEY_TANGENT_OUT_SHIFT)); - } - - static QTime qTimeFromFloat(float time) - { - // The float time goes from 0.0 - 23.98 (since max time is 23:59), so - // convert this to seconds so we can construct a QTime object from that - int seconds = (time * 60.0f) * 60; - return QTime(0, 0).addSecs(seconds); - } - - static float floatFromQTime(const QTime& time) - { - return static_cast(time.msecsSinceStartOfDay() / 60000) / 60.0; - } - - AZ_INLINE static bool SkipUserInterface(int value) - { - // Check for obsolete parameters that we still want to keep around to migrate legacy data to new data - // but don't want to display in the UI - const ITimeOfDay::ETimeOfDayParamID enumValue = static_cast(value); - - // Split the check into two parts to try to keep the logic clear. - // The First set of parameters are always checked... - bool skipParameter = (enumValue == ITimeOfDay::PARAM_HDR_DYNAMIC_POWER_FACTOR) || - (enumValue == ITimeOfDay::PARAM_TERRAIN_OCCL_MULTIPLIER) || - (enumValue == ITimeOfDay::PARAM_SUN_COLOR_MULTIPLIER); - - return skipParameter; - } -} - -CHDRPane::CHDRPane(CTimeOfDayDialog* pTODDlg) - : QWidget(pTODDlg) - , m_pTODDlg(pTODDlg) - , m_pVars(new CVarBlock) -{ - assert(m_pTODDlg); -#if !defined(NDEBUG) - bool ok = -#endif - Init(); - assert(ok); -} - -bool CHDRPane::Init() -{ - m_filmCurveCtrl = new CCurveEditorCtrl(this); - m_filmCurveCtrl->SetControlPointCount(21); - m_filmCurveCtrl->SetMouseEnable(false); - m_filmCurveCtrl->SetPadding(16); - m_filmCurveCtrl->SetFlags( - CCurveEditorCtrl::eFlag_ShowVerticalRuler | - CCurveEditorCtrl::eFlag_ShowHorizontalRuler | - CCurveEditorCtrl::eFlag_ShowCursorAlways | - CCurveEditorCtrl::eFlag_ShowVerticalRulerText | - CCurveEditorCtrl::eFlag_ShowHorizontalRulerText | - CCurveEditorCtrl::eFlag_ShowPaddingBorder); - m_filmCurveCtrl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - m_propsCtrl = new ReflectedPropertyControl(this); - m_propsCtrl->Setup(); - - QVBoxLayout* l = new QVBoxLayout; - l->setMargin(0); - l->addWidget(m_filmCurveCtrl); - l->addWidget(m_propsCtrl); - setLayout(l); - - m_propsCtrl->SetSelChangeCallback(AZStd::bind(&CHDRPane::OnPropertySelected, this, AZStd::placeholders::_1)); - - return true; -} - -void CHDRPane::OnPropertySelected(IVariable *pVar) -{ - if (pVar && pVar->GetType() == IVariable::ARRAY) - { - pVar = nullptr; - } - - emit propertySelected(pVar); -} - -bool CHDRPane::GetFilmCurveParams(float& shoulderScale, float& midScale, float& toeScale, float& whitePoint) const -{ - int checked = 0; - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - for (int i = 0; pTimeOfDay->GetVariableCount(); ++i) - { - ITimeOfDay::SVariableInfo varInfo; - bool ok = pTimeOfDay->GetVariableInfo(i, varInfo); - if (ok == false) - { - continue; - } - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - switch (varInfo.nParamId) - { - case ITimeOfDay::PARAM_HDR_FILMCURVE_SHOULDER_SCALE: - shoulderScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_LINEAR_SCALE: - midScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_TOE_SCALE: - toeScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_WHITEPOINT: - whitePoint = varInfo.fValue[0]; - ++checked; - break; - } - - if (checked == 4) - { - return true; - } - } - - return false; -} - -static float EvalFilmCurve(float x, float ss, float ms, float ts) -{ - return (x * (ss * 6.2f * x + 0.5f * ms)) / max((x * (ss * 6.2f * x + 1.7f) + ts * 0.06f), TimeOfDayDetails::kEpsilon); -} - -void CHDRPane::UpdateFilmCurve() -{ - float shoulderScale = 0, midScale = 0, toeScale = 0, whitePoint = 0; -#if !defined(NDEBUG) - bool ok = -#endif - GetFilmCurveParams(shoulderScale, midScale, toeScale, whitePoint); - assert(ok); - const float minX = -4.0f, minY = 0.0f, maxX = 4.0f; - float maxY = 1.0f, stepY = 0.1f; - - int numSamplePoints = m_filmCurveCtrl->GetControlPointCount(); - - for (int i = 0; i < numSamplePoints; ++i) - { - float t = static_cast(i) / (numSamplePoints - 1); - float logX = minX + ((maxX - minX) * t); - float x = powf(10.0f, logX); // Conventionally, the x domain is logarithmic. - - float v = EvalFilmCurve(x, shoulderScale, midScale, toeScale) / - max(EvalFilmCurve(whitePoint, shoulderScale, midScale, toeScale), TimeOfDayDetails::kEpsilon); - v = powf(v, 2.2f); // converting to a linear space - - // Update the maximum Y so that a proper domain can be set later. - if (v > maxY) - { - maxY = ceil(v / stepY) * stepY; - } - - m_filmCurveCtrl->SetControlPoint(i, Vec2(logX, v)); - } - - // maxY is not fixed, so adjust Y grid count properly according to it. - const UINT gridX = 4; // X grid is fixed. - UINT gridY = static_cast(maxY / stepY); - while (gridY > 20) // > 20 means too many, so reduce the count properly. - { - gridY = (gridY + 9) / 10; - stepY *= 10.0f; - } - maxY = stepY * gridY; - // Also prepare labels for the grid since the default labeling is improper - // especially for the X axis due to its log scale. - QStringList labelsX, labelsY; - for (int i = 0; i <= gridX; ++i) - { - QString label; - label.asprintf("%.4g", powf(10.0f, minX + (maxX - minX) * static_cast(i) / gridX)); - labelsX.push_back(label); - } - for (int i = 0; i <= gridY; ++i) - { - QString label; - label.asprintf("%.1f", i * stepY); - labelsY.push_back(label); - } - m_filmCurveCtrl->SetGrid(gridX, gridY, labelsX, labelsY); - m_filmCurveCtrl->MarkY(1.0f); // Mark the output of 1 so that users can quickly recognize where the clamping happens. - m_filmCurveCtrl->SetDomainBounds(minX, minY, maxX, maxY); - - m_filmCurveCtrl->update(); -} -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Adapter for Multi element interpolators that allow to split it to several -// different interpolators for each element separately. -////////////////////////////////////////////////////////////////////////// -class CMultiElementSplineInterpolatorAdapter - : public ISplineInterpolator -{ -public: - CMultiElementSplineInterpolatorAdapter() - : m_pInterpolator(0) - , m_element(0) {} - CMultiElementSplineInterpolatorAdapter(ISplineInterpolator* pSpline, int element) - { - m_pInterpolator = pSpline; - m_element = element; - } - // Dimension of the spline from 0 to 3, number of parameters used in ValueType. - virtual int GetNumDimensions() { return m_pInterpolator->GetNumDimensions(); } - virtual int InsertKey(float time, ValueType value) - { - ValueType v = {0, 0, 0, 0}; - v[m_element] = value[0]; - return m_pInterpolator->InsertKey(time, v); - }; - virtual void RemoveKey(int key) { m_pInterpolator->RemoveKey(key); }; - - virtual void FindKeysInRange(float startTime, float endTime, int& firstFoundKey, int& numFoundKeys) - { m_pInterpolator->FindKeysInRange(startTime, endTime, firstFoundKey, numFoundKeys); } - virtual void RemoveKeysInRange(float startTime, float endTime) { m_pInterpolator->RemoveKeysInRange(startTime, endTime); } - - virtual int GetKeyCount() { return m_pInterpolator->GetKeyCount(); } - virtual void SetKeyTime(int key, float time) { return m_pInterpolator->SetKeyTime(key, time); }; - virtual float GetKeyTime(int key) { return m_pInterpolator->GetKeyTime(key); } - - virtual void SetKeyValue(int key, ValueType value) - { - ValueType v = {0, 0, 0, 0}; - m_pInterpolator->GetKeyValue(key, v); - v[m_element] = value[0]; - m_pInterpolator->SetKeyValue(key, v); - } - virtual bool GetKeyValue(int key, ValueType& value) - { - ValueType v = {0, 0, 0, 0}; - v[m_element] = value[0]; - return m_pInterpolator->GetKeyValue(key, value); - value[0] = v[m_element]; - } - - virtual void SetKeyInTangent([[maybe_unused]] int key, [[maybe_unused]] ValueType tin) {}; - virtual void SetKeyOutTangent([[maybe_unused]] int key, [[maybe_unused]] ValueType tout) {}; - virtual void SetKeyTangents([[maybe_unused]] int key, [[maybe_unused]] ValueType tin, [[maybe_unused]] ValueType tout) {}; - virtual bool GetKeyTangents([[maybe_unused]] int key, [[maybe_unused]] ValueType& tin, [[maybe_unused]] ValueType& tout) { return false; }; - - // Changes key flags, @see ESplineKeyFlags - virtual void SetKeyFlags(int key, int flags) { return m_pInterpolator->SetKeyFlags(key, flags); }; - // Retrieve key flags, @see ESplineKeyFlags - virtual int GetKeyFlags(int key) { return m_pInterpolator->GetKeyFlags(key); } - - virtual void Interpolate(float time, ValueType& value) - { - m_pInterpolator->Interpolate(time, value); - value[0] = value[m_element]; - }; - - virtual void SerializeSpline(XmlNodeRef& node, bool bLoading) { return m_pInterpolator->SerializeSpline(node, bLoading); }; - - virtual ISplineBackup* Backup() { return m_pInterpolator->Backup(); }; - virtual void Restore(ISplineBackup* pBackup) { return m_pInterpolator->Restore(pBackup); }; - -public: - ISplineInterpolator* m_pInterpolator; - int m_element; -}; - -////////////////////////////////////////////////////////////////////////// -class CTimeOfDaySplineSet - : public ISplineSet -{ -public: - void AddSpline(ISplineInterpolator* pSpline) { m_splines.push_back(pSpline); }; - void RemoveAllSplines() { m_splines.clear(); } - - virtual ISplineInterpolator* GetSplineFromID(const string& id) - { - int i = atoi(id.c_str()); - if (i >= 0 && i < (int)m_splines.size()) - { - return m_splines[i]; - } - return 0; - }; - virtual string GetIDFromSpline(ISplineInterpolator* pSpline) - { - for (int i = 0; i < (int)m_splines.size(); i++) - { - if (m_splines[i] == pSpline) - { - string s; - s.Format("%d", i); - return s; - } - } - return ""; - } - virtual int GetSplineCount() const { return (int)m_splines.size(); } - virtual int GetKeyCountAtTime(float time, float threshold) const - { - int count = 0; - for (int i = 0; i < (int)m_splines.size(); i++) - { - if (m_splines[i]->FindKey(time, threshold) > 0) - { - count++; - } - } - return count; - } - -public: - std::vector m_splines; -}; - -////////////////////////////////////////////////////////////////////////// -CTimeOfDayDialog::CTimeOfDayDialog(QWidget* parent /* = nullptr */) - : QMainWindow(parent) - , m_ui(new Ui::TimeOfDayDialog) - , m_timelineCtrl(new TimelineWidget(this)) - , m_pHDRPane(new CHDRPane(this)) -{ - gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(this); - GetIEditor()->RegisterNotifyListener(this); - - m_ui->setupUi(this); - m_ui->parameters->Setup(); - splitDockWidget(m_ui->hdrPaneDock, m_ui->tasksDock, Qt::Horizontal); - - // Calculate our maximum time from the slider (23:59) - m_maxTime = m_ui->timelineSlider->maximum() / 60.0f; - - Init(); -} - -////////////////////////////////////////////////////////////////////////// -CTimeOfDayDialog::~CTimeOfDayDialog() -{ - m_alive = false; - GetIEditor()->UnregisterNotifyListener(this); - GetIEditor()->GetUndoManager()->RemoveListener(this); - - gEnv->pSystem->GetISystemEventDispatcher()->RemoveListener(this); - - QSettings settings; - settings.beginGroup(QStringLiteral("EnvironmentEditor")); - settings.setValue(QStringLiteral("state"), saveState()); -} - -const GUID& CTimeOfDayDialog::GetClassID() -{ - // {85FB1272-D858-4ca5-ABB4-04D484ABF51E} - static const GUID guid = { - 0x85fb1272, 0xd858, 0x4ca5, { 0xab, 0xb4, 0x4, 0xd4, 0x84, 0xab, 0xf5, 0x1e } - }; - return guid; -} - -void CTimeOfDayDialog::RegisterViewClass() -{ - AzToolsFramework::ViewPaneOptions options; - options.paneRect = QRect(100, 100, 1500, 800); - options.canHaveMultipleInstances = true; - options.isDockable = true; - - AzToolsFramework::RegisterViewPane(LyViewPane::TimeOfDayEditor, LyViewPane::CategoryOther, options); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::UpdateValues() -{ - if (!m_alive) - { - return; - } - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - - RefreshPropertiesValues(); - - SetTimeRange(advInfo.fStartTime, advInfo.fEndTime, advInfo.fAnimSpeed); - UpdateUI(false); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - - - switch (event) - { - case ESYSTEM_EVENT_TIME_OF_DAY_SET: - // We update the UI in response to a system event (instead of with direct callbacks in the dialog) because time could be set by any of the dialog, - // e_TimeOfDay cvar, a Flow Graph Node or Track View. - UpdateUI(); - break; - default: - // do nothing - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::Init() -{ - // Load toolbar images for the main toolbar - m_ui->actionUndo->setIcon(QIcon(":/TimeOfDay/main-00.png")); - m_ui->actionRedo->setIcon(QIcon(":/TimeOfDay/main-01.png")); - m_ui->actionImportFile->setIcon(QIcon(":/TimeOfDay/main-02.png")); - m_ui->actionExportFile->setIcon(QIcon(":/TimeOfDay/main-03.png")); - m_ui->actionPlayPause->setIcon(QIcon(":/TimeOfDay/main-04.png")); - m_ui->actionSetTimeTo0000->setIcon(QIcon(":/TimeOfDay/main-05.png")); - m_ui->actionSetTimeTo0600->setIcon(QIcon(":/TimeOfDay/main-06.png")); - m_ui->actionSetTimeTo1200->setIcon(QIcon(":/TimeOfDay/main-07.png")); - m_ui->actionSetTimeTo1800->setIcon(QIcon(":/TimeOfDay/main-08.png")); - m_ui->actionSetTimeTo2400->setIcon(QIcon(":/TimeOfDay/main-09.png")); - m_ui->actionStartStopRecording->setIcon(QIcon(":/TimeOfDay/main-10.png")); - m_ui->actionHold->setIcon(QIcon(":/TimeOfDay/main-11.png")); - m_ui->actionFetch->setIcon(QIcon(":/TimeOfDay/main-12.png")); - - // Load the images for the spline edit toolbar - m_ui->tangentsToAutoButton->setIcon(QIcon(":/Common/spline_edit-00.png")); - m_ui->inTangentToZeroButton->setIcon(QIcon(":/Common/spline_edit-01.png")); - m_ui->inTangentToStepButton->setIcon(QIcon(":/Common/spline_edit-02.png")); - m_ui->inTangentToLinearButton->setIcon(QIcon(":/Common/spline_edit-03.png")); - m_ui->outTangentToZerobutton->setIcon(QIcon(":/Common/spline_edit-04.png")); - m_ui->outTangentToStepButton->setIcon(QIcon(":/Common/spline_edit-05.png")); - m_ui->outTangentToLinearButton->setIcon(QIcon(":/Common/spline_edit-06.png")); - m_ui->fitSplinesHorizontalButton->setIcon(QIcon(":/Common/spline_edit-07.png")); - m_ui->fitSplinesVerticalButton->setIcon(QIcon(":/Common/spline_edit-08.png")); - m_ui->splineSnapGridX->setIcon(QIcon(":/Common/spline_edit-09.png")); - m_ui->splineSnapGridY->setIcon(QIcon(":/Common/spline_edit-10.png")); - m_ui->previousKeyButton->setIcon(QIcon(":/Common/spline_edit-14.png")); - m_ui->nextKeyButton->setIcon(QIcon(":/Common/spline_edit-15.png")); - m_ui->removeAllExceptSelectedButton->setIcon(QIcon(":/Common/spline_edit-16.png")); - - m_timelineCtrl->SetTicksTextScale(24.0f); - m_timelineCtrl->SetTimeRange(Range(0, 1)); - - m_ui->spline->SetDefaultKeyTangentType(SPLINE_KEY_TANGENT_LINEAR); - m_ui->spline->SetTimelineCtrl(m_timelineCtrl); - m_ui->spline->SetTimeRange(Range(0, 1.0f)); - m_ui->spline->SetValueRange(Range(-1.0f, 1.0f)); - m_ui->spline->SetMinTimeEpsilon(0.00001f); - m_ui->spline->SetTooltipValueScale(24, 1); - - m_ui->colorGradient->SetNoZoom(false); - m_ui->colorGradient->SetTimeRange(0, 1.0f); - m_ui->colorGradient->LockFirstAndLastKeys(true); - m_ui->colorGradient->SetTooltipValueScale(24, 1); - - CreateProperties(); - UpdateValues(); - UpdateUI(); - - QSettings settings; - settings.beginGroup(QStringLiteral("EnvironmentEditor")); - QByteArray state = settings.value(QStringLiteral("state")).toByteArray(); - if (!state.isEmpty()) - { - restoreState(state); - } - - ResetSpline(0); - - m_ui->hdrPaneDock->setWidget(m_pHDRPane); - m_pHDRPane->UpdateFilmCurve(); - - QString copyAllLabel(tr("Copy All Parameters")); - QString pasteAllLabel(tr("Paste All Parameters")); - m_ui->parameters->AddCustomPopupMenuItem(copyAllLabel, AZStd::bind(&CTimeOfDayDialog::CopyAllProperties, this)); - m_ui->parameters->AddCustomPopupMenuItem(pasteAllLabel, AZStd::bind(&CTimeOfDayDialog::PasteAllProperties, this)); - m_pHDRPane->properties().AddCustomPopupMenuItem(copyAllLabel, AZStd::bind(&CTimeOfDayDialog::CopyAllProperties, this)); - m_pHDRPane->properties().AddCustomPopupMenuItem(pasteAllLabel, AZStd::bind(&CTimeOfDayDialog::PasteAllProperties, this)); - - m_ui->parameters->SetSelChangeCallback(AZStd::bind(&CTimeOfDayDialog::OnPropertySelected, this, AZStd::placeholders::_1)); - connect(m_pHDRPane, &CHDRPane::propertySelected, this, &CTimeOfDayDialog::HdrPropertySelected); - m_pHDRPane->properties().SetUpdateCallback(AZStd::bind(&CTimeOfDayDialog::OnUpdateProperties, this, AZStd::placeholders::_1)); - m_ui->parameters->SetUpdateCallback(AZStd::bind(&CTimeOfDayDialog::OnUpdateProperties, this, AZStd::placeholders::_1)); - - connect(m_ui->importFromFileClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnImport); - connect(m_ui->exportToFileClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnExport); - connect(m_ui->resetValuesClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnResetToDefaultValues); - connect(m_ui->expandAllClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnExpandAll); - connect(m_ui->collapseAllClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnCollapseAll); - - connect(m_ui->currentTimeEdit, &QTimeEdit::timeChanged, this, [=](const QTime& time) { SetTime(TimeOfDayDetails::floatFromQTime(time)); }); - connect(m_ui->startTimeEdit, &QTimeEdit::timeChanged, this, &CTimeOfDayDialog::StartTimeChanged); - connect(m_ui->endTimeEdit, &QTimeEdit::timeChanged, this, &CTimeOfDayDialog::EndTimeChanged); - auto doubleValueChanged = static_cast(&QDoubleSpinBox::valueChanged); - connect(m_ui->playSpeedDoubleSpinBox, doubleValueChanged, this, &CTimeOfDayDialog::OnChangeTimeAnimSpeed); - - connect(m_ui->playClickable, &QLabel::linkActivated, this, [=]() { m_ui->actionPlayPause->setChecked(true); }); - connect(m_ui->stopClickable, &QLabel::linkActivated, this, [=]() { m_ui->actionPlayPause->setChecked(false); }); - - connect(m_ui->forceSkyUpdateCheckBox, &QCheckBox::stateChanged, this, [=](int state) { gSettings.bForceSkyUpdate = state == Qt::Checked; }); - - connect(m_ui->actionUndo, &QAction::triggered, this, &CTimeOfDayDialog::OnUndo); - connect(m_ui->actionRedo, &QAction::triggered, this, &CTimeOfDayDialog::OnRedo); - connect(m_ui->actionImportFile, &QAction::triggered, this, &CTimeOfDayDialog::OnImport); - connect(m_ui->actionExportFile, &QAction::triggered, this, &CTimeOfDayDialog::OnExport); - - connect(m_ui->actionSetTimeTo0000, &QAction::triggered, this, [=]() { SetTime(0); }); - connect(m_ui->actionSetTimeTo0600, &QAction::triggered, this, [=]() { SetTime(6); }); - connect(m_ui->actionSetTimeTo1200, &QAction::triggered, this, [=]() { SetTime(12); }); - connect(m_ui->actionSetTimeTo1800, &QAction::triggered, this, [=]() { SetTime(18); }); - connect(m_ui->actionSetTimeTo2400, &QAction::triggered, this, [=]() { SetTime(m_maxTime); }); - - connect(m_ui->actionHold, &QAction::triggered, this, &CTimeOfDayDialog::OnHold); - connect(m_ui->actionFetch, &QAction::triggered, this, &CTimeOfDayDialog::OnFetch); - - connect(m_ui->tangentsToAutoButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_AUTO); }); - connect(m_ui->inTangentToZeroButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_ZERO); }); - connect(m_ui->inTangentToStepButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_STEP); }); - connect(m_ui->inTangentToLinearButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_LINEAR); }); - connect(m_ui->outTangentToZerobutton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_ZERO); }); - connect(m_ui->outTangentToStepButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_STEP); }); - connect(m_ui->outTangentToLinearButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_LINEAR); }); - connect(m_ui->fitSplinesHorizontalButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FIT_X); }); - connect(m_ui->fitSplinesVerticalButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FIT_Y); }); - connect(m_ui->splineSnapGridX, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_SNAP_GRID_X); }); - connect(m_ui->splineSnapGridY, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_SNAP_GRID_Y); }); - connect(m_ui->previousKeyButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_PREVIOUS_KEY); }); - connect(m_ui->nextKeyButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_NEXT_KEY); }); - connect(m_ui->removeAllExceptSelectedButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FLATTEN_ALL); }); - - connect(m_ui->timelineSlider, &AzQtComponents::SliderInt::valueChanged, this, [=](int value) { SetTime(value / 60.0f); }); - - connect(m_ui->spline, &SplineWidget::beforeChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_ui->spline, &SplineWidget::change, this, [=]() { OnSplineChange(m_ui->spline); }); - connect(m_ui->spline, &SplineWidget::scrollZoomRequested, this, &CTimeOfDayDialog::OnSplineCtrlScrollZoom); - connect(m_ui->spline, &SplineWidget::timeChange, this, &CTimeOfDayDialog::OnTimelineCtrlChange); - connect(m_ui->spline, &SplineWidget::keySelectionChange, this, [=]() { SetTimeFromActiveKey(); }); - - connect(m_ui->colorGradient, &CColorGradientCtrl::beforeChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_ui->colorGradient, &CColorGradientCtrl::change, this, [=]() { OnSplineChange(m_ui->colorGradient); }); - connect(m_ui->colorGradient, &CColorGradientCtrl::activeKeyChange, this, [=]() { SetTimeFromActiveKey(true); }); - //connect(m_timelineCtrl.data(), &TimelineWidget::startChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_timelineCtrl, &TimelineWidget::change, this, &CTimeOfDayDialog::OnTimelineCtrlChange); - - //ITimeOfDay *pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - //m_ui->currentTimeEdit->setTime(qTimeFromFloat(pTimeOfDay->GetTime())); - - GetIEditor()->GetUndoManager()->AddListener(this); -} - -void CTimeOfDayDialog::HdrPropertySelected(IVariable* v) -{ - if (v) - { - m_ui->parameters->ClearSelection(); - } - ResetSpline(v); -} - -void CTimeOfDayDialog::StartTimeChanged([[maybe_unused]] const QTime& time) -{ - float converted = TimeOfDayDetails::floatFromQTime(m_ui->startTimeEdit->time()); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fStartTime = converted; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -void CTimeOfDayDialog::EndTimeChanged([[maybe_unused]] const QTime& time) -{ - float converted = TimeOfDayDetails::floatFromQTime(m_ui->endTimeEdit->time()); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fEndTime = converted; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::CreateProperties() -{ - m_pVars = new CVarBlock; - - std::map groups; - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - for (int i = 0; i < pTimeOfDay->GetVariableCount(); i++) - { - ITimeOfDay::SVariableInfo varInfo; - if (!pTimeOfDay->GetVariableInfo(i, varInfo)) - { - continue; - } - - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - if (!varInfo.pInterpolator) - { - continue; - } - - IVariable* pGroupVar = stl::find_in_map(groups, varInfo.group, 0); - if (!pGroupVar) - { - // Create new group - pGroupVar = new CVariableArray(); - pGroupVar->SetName(varInfo.group); - pGroupVar->SetUserData(-1); - if (strcmp(varInfo.group, "HDR") == 0) // HDR parameters should go into the separate HDR pane. - { - m_pHDRPane->variables()->AddVariable(pGroupVar); - } - else - { - m_pVars->AddVariable(pGroupVar); - } - groups[varInfo.group] = pGroupVar; - } - - IVariable* pVar = 0; - if (varInfo.type == ITimeOfDay::TYPE_COLOR) - { - ////////////////////////////////////////////////////////////////////////// - // Add Var. - pVar = new CVariable(); - pVar->SetDataType(IVariable::DT_COLOR); - pVar->Set(Vec3(varInfo.fValue[0], varInfo.fValue[1], varInfo.fValue[2])); - } - else if (varInfo.type == ITimeOfDay::TYPE_FLOAT) - { - // Add Var. - pVar = new CVariable(); - pVar->Set(varInfo.fValue[0]); - pVar->SetLimits(varInfo.fValue[1], varInfo.fValue[2]); - } - - if (pVar) - { - pVar->SetName(varInfo.name); - pVar->SetHumanName(varInfo.displayName); - pGroupVar->AddVariable(pVar); - pVar->SetUserData(i); - } - } - - m_ui->parameters->AddVarBlock(m_pVars); - m_ui->parameters->ExpandAll(); - m_ui->parameters->EnableNotifyWithoutValueChange(true); - - m_pHDRPane->properties().AddVarBlock(m_pHDRPane->variables()); - m_pHDRPane->properties().ExpandAll(); - m_pHDRPane->properties().EnableNotifyWithoutValueChange(true); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnBeforeSplineChange() -{ - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoTimeOfDayObject()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSplineChange(const QWidget* source) -{ - RefreshPropertiesValues(); - - if (source == m_ui->spline) - { - // Update the time of day settings on spline changes (e.g. keys being moved) - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - pTimeOfDay->Update(true, bForceUpdate); - - m_timelineCtrl->update(); - m_ui->colorGradient->update(); - } - else if (source == m_timelineCtrl) - { - m_ui->colorGradient->update(); - m_ui->spline->update(); - } - else - { - m_ui->spline->SplinesChanged(); - m_ui->spline->update(); - m_timelineCtrl->update(); - } - - - if (m_ui->spline->GetSplineCount() > 0) - { - ISplineInterpolator* pSpline = m_ui->spline->GetSpline(0); - if (NULL != pSpline) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - const uint numVars = pTimeOfDay->GetVariableCount(); - for (uint i = 0; i < numVars; ++i) - { - ITimeOfDay::SVariableInfo varInfo; - pTimeOfDay->GetVariableInfo(i, varInfo); - } - } - } -} - -/** - * Update our time based on the currently active key - */ -void CTimeOfDayDialog::SetTimeFromActiveKey(bool useColorGradient) -{ - if (m_ui->spline->GetSplineCount() < 1) - { - return; - } - - ISplineInterpolator* pSpline = m_ui->spline->GetSpline(0); - if (!pSpline) - { - return; - } - - int activeKey = -1; - if (useColorGradient) - { - // If this method was triggered from our color gradient control, then - // retrieve its active key - activeKey = m_ui->colorGradient->GetActiveKey(); - } - else - { - // Otherwise this method was triggered from our main spline control, so - // we need to find the selected key by cycling through its keys - int numKeys = pSpline->GetKeyCount(); - for (int i = 0; i < numKeys; ++i) - { - if (pSpline->IsKeySelectedAtAnyDimension(i)) - { - activeKey = i; - break; - } - } - } - - if (activeKey == -1) - { - return; - } - - SetTime(pSpline->GetKeyTime(activeKey) * m_maxTime); -} - -////////////////////////////////////////////////////////////////////////// -float CTimeOfDayDialog::GetTime() const -{ - // This used to get the time from GetIEditor()->GetDocument()->GetCurrentMission()->GetTime(); but that seems like legacy CryEngine, so we're - // switching to grabbing it from the 3DEngine if possible - float time = .0f; - if (gEnv->p3DEngine->GetTimeOfDay()) - { - time = gEnv->p3DEngine->GetTimeOfDay()->GetTime(); - } - return time; -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::SetTimeRange(float fTimeStart, float fTimeEnd, float fSpeed) -{ - m_ui->startTimeEdit->setTime(TimeOfDayDetails::qTimeFromFloat(fTimeStart)); - m_ui->endTimeEdit->setTime(TimeOfDayDetails::qTimeFromFloat(fTimeEnd)); - - m_ui->playSpeedDoubleSpinBox->setValue(fSpeed); - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fStartTime = fTimeStart; - advInfo.fEndTime = fTimeEnd; - advInfo.fAnimSpeed = fSpeed; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::RefreshPropertiesValues() -{ - m_ui->parameters->EnableUpdateCallback(false); - m_pHDRPane->properties().EnableUpdateCallback(false); - - // Interpolate internal values - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - for (int i = 0, numVars = pTimeOfDay->GetVariableCount(); i < numVars; i++) - { - ITimeOfDay::SVariableInfo varInfo; - if (!pTimeOfDay->GetVariableInfo(i, varInfo)) - { - continue; - } - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - IVariable* pVar = FindVariable(varInfo.name); - - if (!pVar) - { - continue; - } - - switch (varInfo.type) - { - case ITimeOfDay::TYPE_FLOAT: - pVar->Set(varInfo.fValue[0]); - break; - case ITimeOfDay::TYPE_COLOR: - pVar->Set(Vec3(varInfo.fValue[0], varInfo.fValue[1], varInfo.fValue[2])); - break; - } - } - m_ui->parameters->EnableUpdateCallback(true); - m_pHDRPane->properties().EnableUpdateCallback(true); - - m_pHDRPane->UpdateFilmCurve(); - - // Notify that time of day values changed. - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); -} - -void CTimeOfDayDialog::UpdateUI(bool updateProperties) -{ - float timeOfDayInHours = GetTime(); - - // update the Current Time edit field and Time Of Day Time Slider - QTime qTime = TimeOfDayDetails::qTimeFromFloat(timeOfDayInHours); - - QSignalBlocker sliderBlocker(m_ui->timelineSlider); - QSignalBlocker editBlocker(m_ui->currentTimeEdit); - - int v = qTime.msecsSinceStartOfDay(); - v /= 60000; - m_ui->timelineSlider->setValue(v); - m_ui->currentTimeEdit->setTime(qTime); - - m_ui->spline->SetTimeMarker(timeOfDayInHours / m_maxTime); - m_ui->colorGradient->SetTimeMarker(timeOfDayInHours / m_maxTime); - - if (updateProperties) - { - RefreshPropertiesValues(); - } - else - { - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::SetTime(float time) -{ - const bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - // This is probably legacy and deprecated, but leaving it here just in case it's needed by some legacy game. - if (GetIEditor()->GetDocument()->GetCurrentMission()) - { - GetIEditor()->GetDocument()->GetCurrentMission()->SetTime(time); - } - - // pTimeOfDay->SetTime will trigger a ESYSTEM_EVENT_TIME_OF_DAY_SET, which in turn will result in UpdateUI() being called - pTimeOfDay->SetTime(time, bForceUpdate); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnCloseScene: - case eNotify_OnBeginNewScene: - case eNotify_OnBeginSceneOpen: - { - // prevent crash during redraw which can happen before eNotify_OnEndSceneOpen - m_ui->spline->RemoveAllSplines(); - m_ui->colorGradient->SetSpline(0); - } - break; - case eNotify_OnEndSceneOpen: - case eNotify_OnEndNewScene: - { - UpdateValues(); - - m_pHDRPane->properties().ClearSelection(); - if (ReflectedPropertyItem* pSelectedItem = m_ui->parameters->GetSelectedItem()) - { - if (IVariable* pVar = pSelectedItem->GetVariable()) - { - ResetSpline(pVar); - } - } - } - break; - - case eNotify_OnIdleUpdate: - if (m_ui->actionPlayPause->isChecked()) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - float fHour = pTimeOfDay->GetTime(); - - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - // get the TOD cycle speed from UI - advInfo.fAnimSpeed = m_ui->playSpeedDoubleSpinBox->value(); - float dt = gEnv->pTimer->GetFrameTime(); - float fTime = fHour + dt * advInfo.fAnimSpeed; - if (fTime > advInfo.fEndTime) - { - fTime = advInfo.fStartTime; - } - if (fTime < advInfo.fStartTime) - { - fTime = advInfo.fEndTime; - } - SetTime(fTime); - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnTimelineCtrlChange() -{ - float fTime = m_timelineCtrl->GetTimeMarker(); - SetTime(fTime * m_maxTime); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnChangeTimeAnimSpeed(double value) -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - // set current speed based on if we animating it currently or not - advInfo.fAnimSpeed = value; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSplineCtrlScrollZoom() -{ - if (m_ui->spline && m_ui->colorGradient) - { - m_ui->colorGradient->SetZoom(m_ui->spline->GetZoom().x); - m_ui->colorGradient->SetOrigin(m_ui->spline->GetScrollOffset().x); - m_ui->colorGradient->update(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnImport() -{ - char szFilters[] = "Time Of Day Settings (*.xml);;Time Of Day Settings Old (*.tod)"; - QString fileName; - - if (CFileUtil::SelectFile(szFilters, GetIEditor()->GetLevelFolder(), fileName)) - { - XmlNodeRef root = GetISystem()->LoadXmlFromFile(fileName.toStdString().c_str()); - if (root) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - float fTime = GetTime(); - pTimeOfDay->Serialize(root, true); - pTimeOfDay->SetTime(fTime, true); - - UpdateValues(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnExport() -{ - char szFilters[] = "Time Of Day Settings (*.xml)"; - QString fileName; - if (CFileUtil::SelectSaveFile(szFilters, "xml", GetIEditor()->GetLevelFolder(), fileName)) - { - // Write the light settings into the archive - XmlNodeRef node = XmlHelpers::CreateXmlNode("TimeOfDay"); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - pTimeOfDay->Serialize(node, false); - XmlHelpers::SaveXmlNode(GetIEditor()->GetFileUtil(), node, fileName.toStdString().c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnExpandAll() -{ - m_ui->parameters->ExpandAll(); - m_pHDRPane->properties().ExpandAll(); -} -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnResetToDefaultValues() -{ - auto answer = QMessageBox::question(QApplication::activeWindow(), "Reset Values", "Are you sure you want to reset all values to their default values?"); - - if (answer == QMessageBox::Yes) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - // Load the default time of day settings and use those to reset the time of day. - XmlNodeRef root = GetISystem()->LoadXmlFromFile("default_time_of_day.xml"); - if (root) - { - pTimeOfDay->Serialize(root, true); - } - else - { - QMessageBox::warning(QApplication::activeWindow(), "Reset Values", "Unable to read default time of day file (Editor/default_time_of_day.xml), initializing variables to default values.", QMessageBox::Ok); - - // If for some reason the file is missing or corrupted, recreate the variables with their default states. - // Note that these variables may be out of sync with the default_time_of_day.xml file. - pTimeOfDay->ResetVariables(); - } - - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - SetTimeRange(advInfo.fStartTime, advInfo.fEndTime, advInfo.fAnimSpeed); - RefreshPropertiesValues(); - - m_pHDRPane->properties().ClearSelection(); - ReflectedPropertyItem* selectedItem = m_ui->parameters->GetSelectedItem(); - if (selectedItem) - { - IVariable* var = selectedItem->GetVariable(); - if (var) - { - ResetSpline(var); - } - } - } -} -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnCollapseAll() -{ - m_ui->parameters->CollapseAll(); - m_pHDRPane->properties().CollapseAll(); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnUpdateProperties(IVariable* pVar) -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - int nIndex = -1; - if (pVar) - { - nIndex = pVar->GetUserData().toInt(); - } - - if (nIndex != -1) - { - ITimeOfDay::SVariableInfo varInfo; - if (pTimeOfDay->GetVariableInfo(nIndex, varInfo)) - { - float fTime = GetTime(); - float fSplineTime = fTime / m_maxTime; - - const float cNearestKeySearchEpsilon = 0.00001f; - int nKey = varInfo.pInterpolator->FindKey(fSplineTime, cNearestKeySearchEpsilon); - int nLastKey = varInfo.pInterpolator->GetKeyCount() - 1; - - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoTimeOfDayObject()); - } - - switch (varInfo.type) - { - case ITimeOfDay::TYPE_FLOAT: - { - float fVal = 0; - pVar->Get(fVal); - if (m_ui->actionStartStopRecording->isChecked()) - { - if (nKey < 0) - { - nKey = varInfo.pInterpolator->InsertKeyFloat(fSplineTime, fVal); - } - else - { - varInfo.pInterpolator->SetKeyValueFloat(nKey, fVal); - if (nKey == 0) - { - varInfo.pInterpolator->SetKeyValueFloat(nLastKey, fVal); - } - else if (nKey == nLastKey) - { - varInfo.pInterpolator->SetKeyValueFloat(0, fVal); - } - } - if (m_ui->spline && m_ui->spline->GetDefaultKeyTangentType() != SPLINE_KEY_TANGENT_NONE) - { - TimeOfDayDetails::SetKeyTangentType(varInfo.pInterpolator, nKey, m_ui->spline->GetDefaultKeyTangentType()); - } - } - - float v3[3] = {fVal, varInfo.fValue[1], varInfo.fValue[2]}; - pTimeOfDay->SetVariableValue(nIndex, v3); - } - break; - case ITimeOfDay::TYPE_COLOR: - { - Vec3 vVal; - pVar->Get(vVal); - float v3[3] = {vVal.x, vVal.y, vVal.z}; - if (m_ui->actionStartStopRecording->isChecked()) - { - if (nKey < 0) - { - nKey = varInfo.pInterpolator->InsertKeyFloat3(fSplineTime, v3); - } - else - { - varInfo.pInterpolator->SetKeyValueFloat3(nKey, v3); - if (nKey == 0) - { - varInfo.pInterpolator->SetKeyValueFloat3(nLastKey, v3); - } - else if (nKey == nLastKey) - { - varInfo.pInterpolator->SetKeyValueFloat3(0, v3); - } - } - if (m_ui->spline && m_ui->spline->GetDefaultKeyTangentType() != SPLINE_KEY_TANGENT_NONE) - { - TimeOfDayDetails::SetKeyTangentType(varInfo.pInterpolator, nKey, m_ui->spline->GetDefaultKeyTangentType()); - } - } - pTimeOfDay->SetVariableValue(nIndex, v3); - - m_ui->colorGradient->update(); - } - break; - } - - if (m_ui->spline) - { - m_ui->spline->update(); - } - - if (varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_SHOULDER_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_LINEAR_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_TOE_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_WHITEPOINT) - { - m_pHDRPane->UpdateFilmCurve(); - } - - bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - pTimeOfDay->Update(false, bForceUpdate); - - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnPropertySelected(IVariable *pVar) -{ - if (pVar) - { - m_pHDRPane->properties().ClearSelection(); - } - - if (pVar && pVar->GetType() == IVariable::ARRAY) - { - pVar = nullptr; - } - - ResetSpline(pVar); -} - - -void CTimeOfDayDialog::ResetSpline(IVariable* pVar) -{ - if (pVar) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SVariableInfo varInfo; - int index = pVar->GetUserData().toInt(); - if (!pTimeOfDay->GetVariableInfo(index, varInfo)) - { - return; - } - - m_ui->spline->SetTimeRange(Range(0, 1.0f)); - m_ui->spline->RemoveAllSplines(); - - if (varInfo.type == ITimeOfDay::TYPE_COLOR) - { - QColor afColorArray[4]; - afColorArray[0] = QColor(255, 0, 0); - afColorArray[1] = QColor(0, 255, 0); - afColorArray[2] = QColor(0, 0, 255); - afColorArray[3] = QColor(255, 0, 255); //Pink... so you know it's wrong if you see it. - m_ui->spline->AddSpline(varInfo.pInterpolator, 0, afColorArray); - m_ui->spline->SetValueRange(Range(0, 1)); - - m_ui->colorGradient->SetSpline(varInfo.pInterpolator, TRUE); - m_ui->colorGradient->setEnabled(true); - m_ui->colorGradient->update(); - } - else - { - m_ui->colorGradient->setEnabled(false); - m_ui->colorGradient->SetSpline(0); - m_ui->colorGradient->update(); - - m_ui->spline->SetValueRange(Range(varInfo.fValue[1], varInfo.fValue[2])); - m_ui->spline->AddSpline(varInfo.pInterpolator, 0, QColor(0, 255, 0)); - } - m_ui->spline->SetSplineSet(0); - m_ui->spline->FitSplineToViewWidth(); - m_ui->spline->FitSplineHeightToValueRange(); - } - else - { - m_ui->spline->RemoveAllSplines(); - m_ui->colorGradient->setEnabled(false); - m_ui->colorGradient->SetSpline(0); - } - m_ui->spline->update(); -} - - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnHold() -{ - XmlNodeRef node = XmlHelpers::CreateXmlNode("TimeOfDay"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(node, false); - node->saveToFile((Path::GetUserSandboxFolder() + "TimeOfDayHold.xml").toUtf8().data()); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnFetch() -{ - XmlNodeRef node = XmlHelpers::LoadXmlFromFile((Path::GetUserSandboxFolder() + "TimeOfDayHold.xml").toUtf8().data()); - if (node) - { - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(node, true); - UpdateValues(); - UpdateUI(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnUndo() -{ - GetIEditor()->Undo(); - m_ui->spline->update(); - m_ui->colorGradient->update(); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnRedo() -{ - GetIEditor()->Redo(); - m_ui->spline->update(); - m_ui->colorGradient->update(); -} - -////////////////////////////////////////////////////////////////////////// -IVariable* CTimeOfDayDialog::FindVariable(const char* name) const -{ - IVariable* pVar = m_pVars->FindVariable(name); - if (!pVar) - { - pVar = m_pHDRPane->variables()->FindVariable(name); - } - - return pVar; -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::CopyAllProperties() -{ - CClipboard clipboard(this); - XmlNodeRef collectionNode = XmlHelpers::CreateXmlNode("PropertyCtrls"); - - ReflectedPropertyItem* pRoot = m_ui->parameters->GetRootItem(); - if (pRoot) // Main properties - { - XmlNodeRef rootNode = collectionNode->newChild("PropertyCtrl"); - for (int i = 0; i < pRoot->GetChildCount(); ++i) - { - m_ui->parameters->CopyItem(rootNode, pRoot->GetChild(i), true); - } - } - - pRoot = m_pHDRPane->properties().GetRootItem(); - if (pRoot) // HDR properties - { - XmlNodeRef rootNode = collectionNode->newChild("PropertyCtrl"); - for (int i = 0; i < pRoot->GetChildCount(); ++i) - { - m_pHDRPane->properties().CopyItem(rootNode, pRoot->GetChild(i), true); - } - } - - clipboard.Put(collectionNode); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::PasteAllProperties() -{ - CClipboard clipboard(this); - CUndo undo("Paste Properties"); - - XmlNodeRef collectionNode = clipboard.Get(); - if (collectionNode != NULL && collectionNode->isTag("PropertyCtrls") - && collectionNode->getChildCount() == 2) - { - // Main properties - XmlNodeRef rootNode = collectionNode->getChild(0); - m_ui->parameters->SetValuesFromNode(rootNode); - - // HDR properties - rootNode = collectionNode->getChild(1); - m_pHDRPane->properties().SetValuesFromNode(rootNode); - } -} - -void CTimeOfDayDialog::SignalNumUndoRedo(const unsigned int& numUndo, const unsigned int& numRedo) -{ - m_ui->actionUndo->setEnabled(numUndo > 0); - m_ui->actionRedo->setEnabled(numRedo > 0); -} - -void CTimeOfDayDialog::resizeEvent([[maybe_unused]] QResizeEvent* event) -{ - if (m_ui->spline->GetSplineCount() == 0) - { - m_ui->spline->FitSplineToViewWidth(); - m_ui->spline->FitSplineToViewHeight(); - } -} - -CUndoTimeOfDayObject::CUndoTimeOfDayObject() -{ - m_undo = XmlHelpers::CreateXmlNode("Undo"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_undo, false); -} - -void CUndoTimeOfDayObject::Undo(bool bUndo) -{ - if (bUndo) - { - m_redo = XmlHelpers::CreateXmlNode("Redo"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_redo, false); - } - - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_undo, true); - UpdateTimeOfDayDialog(); -} - -void CUndoTimeOfDayObject::Redo() -{ - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_redo, true); - UpdateTimeOfDayDialog(); -} - -void CUndoTimeOfDayObject::UpdateTimeOfDayDialog() -{ - CTimeOfDayDialog* targetDialog = FindViewPane(CTimeOfDayDialog::ClassName()); - if (targetDialog != nullptr) - { - targetDialog->UpdateValues(); - } -} - -#include diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.h b/Code/Sandbox/Editor/TimeOfDayDialog.h deleted file mode 100644 index 8e9a9e92a8..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H -#define CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Controls/TimelineCtrl.h" -#include -#include "Undo/IUndoManagerListener.h" -#include "LyViewPaneNames.h" -#include -#endif - -////////////////////////////////////////////////////////////////////////// - -class QResizeEvent; -class CCurveEditorCtrl; -class CHDRPane; - -namespace Ui { - class TimeOfDayDialog; -} - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -////////////////////////////////////////////////////////////////////////// -// Window that holds effector info. -////////////////////////////////////////////////////////////////////////// -class SANDBOX_API CTimeOfDayDialog - : public QMainWindow - , public IEditorNotifyListener - , public ISystemEventListener - , public IUndoManagerListener -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT -public: - static const char* ClassName() { return LyViewPane::TimeOfDayEditor; } - static const GUID& GetClassID(); - - CTimeOfDayDialog(QWidget* parent = nullptr); - ~CTimeOfDayDialog(); - - static void RegisterViewClass(); - void UpdateValues(); - - // overrides from ISystemEventListener - void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override; - -protected: - void OnBeforeSplineChange(); - void OnSplineChange(const QWidget* source); - void OnPlayAnimFrom0(); - void OnChangeTimeAnimSpeed(double speed); - - void OnImport(); - void OnExport(); - void OnExpandAll(); - void OnResetToDefaultValues(); - void OnCollapseAll(); - - void OnHold(); - void OnFetch(); - void OnUndo(); - void OnRedo(); - - void OnPropertySelected(IVariable* node); - void OnSplineCtrlScrollZoom(); - void OnTimelineCtrlChange(); - - void Init(); - - void OnUpdateProperties(IVariable* var); - - void CreateProperties(); - - void SetTime(float time); - void SetTimeRange(float fTimeStart, float fTimeEnd, float fSpeed); - float GetTime() const; - - void RefreshPropertiesValues(); - void ResetSpline(IVariable* var); - - IVariable* FindVariable(const char* name) const; - - void CopyAllProperties(); - void PasteAllProperties(); - - void HdrPropertySelected(IVariable* v); - void StartTimeChanged(const QTime& time); - void EndTimeChanged(const QTime& time); - - ////////////////////////////////////////////////////////////////////////// - // IEditorNotifyListener - ////////////////////////////////////////////////////////////////////////// - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - ////////////////////////////////////////////////////////////////////////// - - // IUndoManagerListener - void SignalNumUndoRedo(const unsigned int& numUndo, const unsigned int& numRedo) override; - - void resizeEvent(QResizeEvent* event) override; - -private: - void UpdateUI(bool updateProperties=true); - void SetTimeFromActiveKey(bool useColorGradient = false); - - bool m_alive = true; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - QScopedPointer m_ui; - - CHDRPane* m_pHDRPane; - CVarBlockPtr m_pVars; - - TimelineWidget* m_timelineCtrl; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - float m_maxTime; -}; - -class CHDRPane - : public QWidget -{ - Q_OBJECT -public: - CHDRPane(CTimeOfDayDialog* pTODDlg); - - ReflectedPropertyControl& properties() { return *m_propsCtrl; } - CVarBlockPtr variables() { return m_pVars; } - - void UpdateFilmCurve(); - -signals: - void propertySelected(IVariable* variable); - -protected: - bool Init(); - void OnPropertySelected(IVariable*); - - bool GetFilmCurveParams(float& shoulderScale, float& midScale, float& toeScale, float& whitePoint) const; - - CTimeOfDayDialog* m_pTODDlg; - CCurveEditorCtrl* m_filmCurveCtrl; - ReflectedPropertyControl* m_propsCtrl; - CVarBlockPtr m_pVars; -}; - -/** Undo object stored when track is modified. -*/ -class CUndoTimeOfDayObject - : public IUndoObject -{ -public: - CUndoTimeOfDayObject(); - -protected: - virtual int GetSize() { return sizeof(*this); } - virtual QString GetDescription() { return "Time of Day"; }; - - virtual void Undo(bool bUndo); - virtual void Redo(); - -private: - void UpdateTimeOfDayDialog(); - - XmlNodeRef m_undo; - XmlNodeRef m_redo; -}; - -#endif // CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.ui b/Code/Sandbox/Editor/TimeOfDayDialog.ui deleted file mode 100644 index 35e8e483a0..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.ui +++ /dev/null @@ -1,980 +0,0 @@ - - - TimeOfDayDialog - - - - 0 - 0 - 1073 - 600 - - - - MainWindow - - - QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::AnimatedDocks - - - - - 2 - - - - - - 1 - 0 - - - - - - - - 2 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Set In/Out Tangents to Auto - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Set In Tangent to Zero - - - - - - - 18 - 18 - - - - true - - - - - - - Set In Tangent to Step - - - - - - - 18 - 18 - - - - true - - - - - - - Set In Tangent to Linear - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Set Out Tangent to Zero - - - - - - - 18 - 18 - - - - true - - - - - - - Set Out Tangent to Step - - - - - - - 18 - 18 - - - - true - - - - - - - Set Out Tangent to Linear - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Fit Splines to the Visible Width - - - - - - - 18 - 18 - - - - true - - - - - - - Fit Splines to the Visible Height - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Snap to time grid - - - - 18 - 18 - - - - true - - - true - - - - - - - Snap to value grid - - - - 18 - 18 - - - - true - - - true - - - - - - - Qt::Vertical - - - - - - - Previous Key - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Next Key - - - - - - - 18 - 18 - - - - true - - - - - - - Remove all Keys BUT This - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Horizontal - - - - 69 - 20 - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 0 - 35 - - - - - - - - - - - - 1 - 1 - - - - - - - - - 0 - - - - - Timeline - - - - 6 - - - 0 - - - - - 23:59 - - - Qt::AlignRight|Qt::AlignTop|Qt::AlignTrailing - - - - - - - 00:00 - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - 12:00 - - - Qt::AlignHCenter|Qt::AlignTop - - - - - - - Qt::WheelFocus - - - 1439 - - - - - - - - - - - - - - - - - toolBar - - - - 32 - 32 - - - - false - - - TopToolBarArea - - - false - - - - - - - - - - - - - - - - - - - - - - - 350 - 40 - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - HDR Settings - - - 1 - - - - - 0 - 0 - - - - - 150 - 0 - - - - - - - - - 0 - 0 - - - - - 450 - 50 - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - Parameters - - - 2 - - - - - - - - 0 - 0 - - - - - 200 - 0 - - - - - - - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - Time of Day Tasks - - - 1 - - - - - - - - 0 - 0 - - - - - 0 - - - - - Tasks - - - - - - Import From File - - - - - - - Export To File - - - - - - - Reset Values - - - - - - - Expand All - - - - - - - Collapse All - - - - - - - - - - Time - - - - - - Current Time - - - currentTimeEdit - - - - - - - - - - Start Time - - - startTimeEdit - - - - - - - - - - End Time - - - endTimeEdit - - - - - - - - - - Play Speed - - - playSpeedDoubleSpinBox - - - - - - - 0.001000000000000 - - - - - - - - - - Update Tasks - - - - - - Play - - - - - - - Stop - - - - - - - Force sky update - - - true - - - - - - - - - - Qt::Vertical - - - - 20 - 139 - - - - - - - - - - - - - false - - - Undo - - - Undo - - - - - false - - - Redo - - - Redo - - - - - Import File - - - Import File - - - - - Export File - - - Export File - - - - - true - - - Play/Pause - - - Play/Pause - - - - - 00 - - - Set Time to 00:00 - - - - - 06 - - - Set Time to 06:00 - - - - - 12 - - - Set Time to 12:00 - - - - - 18 - - - Set Time to 18:00 - - - - - 24 - - - Set Time to 23:59 - - - - - true - - - true - - - Start/Stop Recording - - - Start/Stop Recording - - - - - Hold - - - Hold - - - - - Fetch - - - Fetch - - - - - - ReflectedPropertyControl - QWidget -
Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h
- 1 -
- - QCollapsibleGroupBox - QGroupBox -
QtUI/QCollapsibleGroupBox.h
- 1 -
- - ClickableLabel - QLabel -
QtUI/ClickableLabel.h
-
- - SplineWidget - QWidget -
Controls/SplineCtrlEx.h
- 1 -
- - CColorGradientCtrl - QWidget -
Controls/ColorGradientCtrl.h
- 1 -
- - AzQtComponents::DoubleSpinBox - QDoubleSpinBox -
AzQtComponents/Components/Widgets/SpinBox.h
-
- - TimeOfDaySlider - QWidget -
Controls/TimeOfDaySlider.h
- 1 -
-
- - timelineSlider - - - -
diff --git a/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp b/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp index 06184c0fc3..0179b779e8 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp @@ -1505,12 +1505,6 @@ void CTrackViewDialog::OnEditorNotifyEvent(EEditorNotifyEvent event) m_bIgnoreUpdates = false; OnGameOrSimModeLock(false); break; - case eNotify_OnMissionChange: - if (!m_bIgnoreUpdates) - { - ReloadSequences(); - } - break; case eNotify_OnReloadTrackView: if (!m_bIgnoreUpdates) { diff --git a/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp b/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp index 3979bf3cca..0bde26edf1 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp @@ -832,32 +832,7 @@ void CTrackViewNodesCtrl::UpdateAnimNodeRecord(CRecord* record, CTrackViewAnimNo } else if (nodeType == AnimNodeType::Material) { - // Check if a valid material can be found by the node name. - _smart_ptr pMaterial = nullptr; - QString matName; - int subMtlIndex = GetMatNameAndSubMtlIndexFromName(matName, animNode->GetName()); - pMaterial = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(matName.toUtf8().data()); - if (pMaterial) - { - bool bMultiMat = pMaterial->GetSubMtlCount() > 0; - bool bMultiMatWithoutValidIndex = bMultiMat && (subMtlIndex < 0 || subMtlIndex >= pMaterial->GetSubMtlCount()); - bool bLeafMatWithIndex = !bMultiMat && subMtlIndex != -1; - if (bMultiMatWithoutValidIndex || bLeafMatWithIndex) - { - pMaterial = nullptr; - } - } - - if (!pMaterial) - { - record->setForeground(0, TextColorForInvalidMaterial); - } - else - { - // set to default color from palette - // materials that originally pointed to material groups and are changed to sub-materials need this to reset their color - record->setForeground(0, palette().color(foregroundRole())); - } + record->setForeground(0, TextColorForInvalidMaterial); } // Mark the active director and other directors properly. @@ -2163,43 +2138,6 @@ int CTrackViewNodesCtrl::ShowPopupMenuSingleSelection(SContextMenu& contextMenu, bAppended = true; } - // Sub material menu - if (bOnNode && animNode->GetType() == AnimNodeType::Material) - { - QString matName; - int subMtlIndex = GetMatNameAndSubMtlIndexFromName(matName, animNode->GetName()); - _smart_ptr pMtl = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(matName.toUtf8().data()); - bool bMultMatNode = pMtl ? pMtl->GetSubMtlCount() > 0 : false; - - bool bMatAppended = false; - - if (bMultMatNode) - { - for (int k = 0; k < pMtl->GetSubMtlCount(); ++k) - { - _smart_ptr pSubMaterial = pMtl->GetSubMtl(k); - - if (pSubMaterial) - { - QString subMaterialName = pSubMaterial->GetName(); - - if (!subMaterialName.isEmpty()) - { - AddMenuSeperatorConditional(contextMenu.main, bAppended); - QString subMatName = QString("[%1] %2").arg(k + 1).arg(subMaterialName); - QAction* a = contextMenu.main.addAction(subMatName); - a->setData(eMI_SelectSubmaterialBase + k); - a->setCheckable(true); - a->setChecked(k == subMtlIndex); - bMatAppended = true; - } - } - } - } - - bAppended = bAppended || bMatAppended; - } - // Delete track menu if (bOnTrackNotSub) { diff --git a/Code/Sandbox/Editor/Util/CubemapUtils.cpp b/Code/Sandbox/Editor/Util/CubemapUtils.cpp index a143b7e5ce..bd650abaa8 100644 --- a/Code/Sandbox/Editor/Util/CubemapUtils.cpp +++ b/Code/Sandbox/Editor/Util/CubemapUtils.cpp @@ -30,6 +30,7 @@ #include "Util/ImageTIF.h" #include "Objects/BaseObject.h" +#include class CubemapSizeModel : public QAbstractListModel diff --git a/Code/Sandbox/Editor/Util/FileUtil.cpp b/Code/Sandbox/Editor/Util/FileUtil.cpp index fc5eca1952..8dd379f096 100644 --- a/Code/Sandbox/Editor/Util/FileUtil.cpp +++ b/Code/Sandbox/Editor/Util/FileUtil.cpp @@ -2088,7 +2088,6 @@ void CFileUtil::GatherAssetFilenamesFromLevel(std::set& rOutFilenames, rOutFilenames.clear(); CBaseObjectsArray objArr; CUsedResources usedRes; - IMaterialManager* pMtlMan = GetIEditor()->Get3DEngine()->GetMaterialManager(); GetIEditor()->GetObjectManager()->GetObjects(objArr); @@ -2116,66 +2115,6 @@ void CFileUtil::GatherAssetFilenamesFromLevel(std::set& rOutFilenames, rOutFilenames.insert(tmpStr); } } - - uint32 mtlCount = 0; - - pMtlMan->GetLoadedMaterials(NULL, mtlCount); - - if (mtlCount > 0) - { - AZStd::vector<_smart_ptr> arrMtls; - - arrMtls.resize(mtlCount); - pMtlMan->GetLoadedMaterials(&arrMtls, mtlCount); - - for (size_t i = 0; i < mtlCount; ++i) - { - _smart_ptr pMtl = arrMtls[i]; - - size_t subMtls = pMtl->GetSubMtlCount(); - - // for the main material - IRenderShaderResources* pShaderRes = pMtl->GetShaderItem().m_pShaderResources; - - // add the material filename - rOutFilenames.insert(pMtl->GetName()); - - if (pShaderRes) - { - for ( auto iter= pShaderRes->GetTexturesResourceMap()->begin() ; - iter!= pShaderRes->GetTexturesResourceMap()->end() ; ++iter ) - { - SEfResTexture* pTex = &(iter->second); - // add the texture filename - rOutFilenames.insert(pTex->m_Name.c_str()); - } - } - - // for the submaterials - for (size_t s = 0; s < subMtls; ++s) - { - _smart_ptr pSubMtl = pMtl->GetSubMtl(s); - - // fill up dependencies - if (pSubMtl) - { - IRenderShaderResources* pShaderRes2 = pSubMtl->GetShaderItem().m_pShaderResources; - - rOutFilenames.insert(pSubMtl->GetName()); - - if (pShaderRes2) - { - for (auto iter = pShaderRes2->GetTexturesResourceMap()->begin(); - iter != pShaderRes2->GetTexturesResourceMap()->end(); ++iter) - { - SEfResTexture* pTex = &(iter->second); - rOutFilenames.insert(pTex->m_Name.c_str()); - } - } - } - } - } - } } uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= true*/) diff --git a/Code/Sandbox/Editor/Util/KDTree.cpp b/Code/Sandbox/Editor/Util/KDTree.cpp index b407305a93..71ec798005 100644 --- a/Code/Sandbox/Editor/Util/KDTree.cpp +++ b/Code/Sandbox/Editor/Util/KDTree.cpp @@ -14,6 +14,8 @@ #include "KDTree.h" +#include + class KDTreeNode { public: diff --git a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp b/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp deleted file mode 100644 index 206131e5a9..0000000000 --- a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "EditorDefs.h" - -#include "VariableTypeInfo.h" -#include "TypeInfo_impl.h" -#include "IShader_info.h" - -#ifndef AZ_MONOLITHIC_BUILD -#include "I3DEngine_info.h" -#endif - -#include "Variable.h" -#include "UIEnumsDatabase.h" - -// CryCommon -#include - - -IVariable* CVariableTypeInfo::Create(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault) -{ - pAddress = VarInfo.GetAddress(pAddress); - pAddressDefault = VarInfo.GetAddress(pAddressDefault); - - EType eType = GetType(VarInfo.Type); - if (eType == ARRAY) - { - return new CVariableTypeInfoStruct(VarInfo, pAddress, pAddressDefault); - } - - if (VarInfo.Type.EnumElem(0)) - { - return new CVariableTypeInfoEnum(VarInfo, pAddress, pAddressDefault); - } - - ISplineInterpolator* pSpline = 0; - if (VarInfo.Type.ToValue(pAddress, pSpline)) - { - return new CVariableTypeInfoSpline(VarInfo, pAddress, pAddressDefault, pSpline); - } - - return new CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, eType); -} - -CVariableTypeInfo::EType CVariableTypeInfo::GetType(CTypeInfo const& typeInfo) -{ - // Translation to editor type values is currently done with some clunky type and name testing. - if (typeInfo.HasSubVars()) - { - if (typeInfo.IsType() && !typeInfo.NextSubVar(0)->Type.IsType()) - { - // This is a vector type (and not a sub-classed vector type) - return IVariable::VECTOR; - } - else - { - return IVariable::ARRAY; - } - } - else if (typeInfo.IsType()) - { - return IVariable::BOOL; - } - else if (typeInfo.IsType() || typeInfo.IsType()) - { - return IVariable::INT; - } - else if (typeInfo.IsType()) - { - return IVariable::FLOAT; - } - return IVariable::STRING; -} - -CVariableTypeInfo::CVariableTypeInfo(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, EType eType) - : m_pVarInfo(&VarInfo) - , m_pData(pAddress) - , m_pDefaultData(pAddressDefault) -{ - SetName(SpacedName(VarInfo.GetName())); - SetTypes(VarInfo.Type, eType); - SetFlags(IVariable::UI_UNSORTED | IVariable::UI_HIGHLIGHT_EDITED); - SetDescription(VarInfo.GetComment()); -} - -void CVariableTypeInfo::SetTypes(CTypeInfo const& TypeInfo, EType eType) -{ - m_pTypeInfo = &TypeInfo; - m_eType = eType; - - SetDataType(DT_SIMPLE); - if (m_eType == VECTOR) - { - if (m_name == "Color") - { - SetDataType(DT_COLOR); - } - } - else if (m_eType == STRING) - { - if (m_name == "Texture" || m_name == "Glow Map" || m_name == "Normal Map" || m_name == "Trail Fading") - { - SetDataType(DT_TEXTURE); - } - else if (m_name == "Geometry") - { - SetDataType(DT_OBJECT); - } - else if (m_name == "Start Trigger" || m_name == "Stop Trigger") - { - SetDataType(DT_AUDIO_TRIGGER); - } - else if (m_name == "GeomCache") - { - SetDataType(DT_GEOM_CACHE); - } - } -} - -// IVariable implementation. -CVariableTypeInfo::EType CVariableTypeInfo::GetType() const -{ - return m_eType; -} - -int CVariableTypeInfo::GetSize() const -{ - return m_pTypeInfo->Size; -} - -void CVariableTypeInfo::GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax) -{ - // Get hard limits from variable type, or vector element type. - const CTypeInfo* pLimitType = m_pTypeInfo; - if ((m_eType == VECTOR || m_eType == VECTOR2) && m_pTypeInfo->NextSubVar(0)) - { - pLimitType = &m_pTypeInfo->NextSubVar(0)->Type; - } - bHardMin = pLimitType->GetLimit(eLimit_Min, fMin); - bHardMax = pLimitType->GetLimit(eLimit_Max, fMax); - pLimitType->GetLimit(eLimit_Step, fStep); - - // Check var attrs for additional limits. - if (m_pVarInfo->GetAttr("SoftMin", fMin)) - { - bHardMin = false; - } - else if (m_pVarInfo->GetAttr("Min", fMin)) - { - bHardMin = true; - } - - if (m_pVarInfo->GetAttr("SoftMax", fMax)) - { - bHardMax = false; - } - else if (m_pVarInfo->GetAttr("Max", fMax)) - { - bHardMax = true; - } -} - -void CVariableTypeInfo::Set(const char* value) -{ - m_pTypeInfo->FromString(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const QString& value) -{ - Set(value.toUtf8().data()); -} - -void CVariableTypeInfo::Set(float value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(int value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(bool value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const Vec2& value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const Vec3& value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Get(QString& value) const -{ - value = (const char*)m_pTypeInfo->ToString(m_pData); -} - -void CVariableTypeInfo::Get(float& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(int& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(bool& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(Vec2& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(Vec3& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -bool CVariableTypeInfo::HasDefaultValue() const -{ - return m_pTypeInfo->ValueEqual(m_pData, m_pDefaultData); -} - -void CVariableTypeInfo::ResetToDefault() -{ - QString strVal = m_pTypeInfo->ToString(m_pDefaultData).c_str(); - Set(strVal); -} - -IVariable* CVariableTypeInfo::Clone([[maybe_unused]] bool bRecursive) const -{ - // Simply use a string var for universal conversion. - IVariable* pClone = new CVariable(); - QString str; - Get(str); - pClone->Set(str); - - //add extra information for the clone: Name, DataType - pClone->SetName(GetName()); - pClone->SetDataType(GetDataType()); - //use UserData to save eType since String Variable's GetType always return STRING - pClone->SetUserData(GetType()); - - return pClone; -} - -void CVariableTypeInfo::CopyValue(IVariable* fromVar) -{ - assert(fromVar); - QString str; - fromVar->Get(str); - Set(str); -} - -CVariableTypeInfoEnum::CTypeInfoEnumList::CTypeInfoEnumList(CTypeInfo const& info) - : TypeInfo(info) -{ -} - -QString CVariableTypeInfoEnum::CTypeInfoEnumList::GetItemName(uint index) -{ - return TypeInfo.EnumElem(index); -} - -CVariableTypeInfoEnum::CVariableTypeInfoEnum(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, IVarEnumList* pEnumList) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, UNKNOWN) -{ - // Use custom enum, or enum defined in TypeInfo. - m_enumList = pEnumList ? pEnumList : new CTypeInfoEnumList(VarInfo.Type); -} - -IVarEnumList* CVariableTypeInfoEnum::GetEnumList() const -{ - return m_enumList; -} - -CVariableTypeInfoSpline::CVariableTypeInfoSpline(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, ISplineInterpolator* pSpline) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, STRING) - , m_pSpline(pSpline) -{ - if (m_pSpline && m_pSpline->GetNumDimensions() == 3) - { - SetDataType(DT_CURVE | DT_COLOR); - } - else - { - SetDataType(DT_CURVE | DT_PERCENT); - } -} - -CVariableTypeInfoSpline::~CVariableTypeInfoSpline() -{ - delete m_pSpline; -} - -ISplineInterpolator* CVariableTypeInfoSpline::GetSpline() -{ - //if m_pSpline wasn't created or the data used to create spline was changed, we need create the m_pSpline - int flags = GetFlags(); - if (m_pSpline == nullptr || flags & UI_CREATE_SPLINE) - { - if (m_pSpline != nullptr) - { - delete m_pSpline; - m_pSpline = nullptr; - } - m_pTypeInfo->ToValue(m_pData, m_pSpline); - flags &= ~UI_CREATE_SPLINE; - SetFlags(flags); - } - return m_pSpline; -} - -void CVariableTypeInfoSpline::OnSetValue(bool bRecursive) -{ - m_pTypeInfo->ToValue(m_pData, m_pSpline); - CVariableTypeInfo::OnSetValue(bRecursive); -} - -CVariableTypeInfoStruct::CVariableTypeInfoStruct(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, ARRAY) -{ - ProcessSubStruct(VarInfo, pAddress, pAddressDefault); -} - -void CVariableTypeInfoStruct::ProcessSubStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault) -{ - for AllSubVars(pSubVar, VarInfo.Type) - { - if (!*pSubVar->GetName()) - { - EType eType = GetType(pSubVar->Type); - if (eType == ARRAY) - { - // Recursively process nameless or base struct. - ProcessSubStruct(*pSubVar, pSubVar->GetAddress(pAddress), pSubVar->GetAddress(pAddressDefault)); - } - else if (pSubVar == VarInfo.Type.NextSubVar(0)) - { - // Inline edit first sub-var in main field. - SetTypes(pSubVar->Type, eType); - } - } - else - { - IVariable* pVar = CVariableTypeInfo::Create(*pSubVar, pAddress, pAddressDefault); - m_Vars.push_back(pVar); - } - } -} - -QString CVariableTypeInfoStruct::GetDisplayValue() const -{ - return (const char*)m_pTypeInfo->ToString(m_pData); -} - -void CVariableTypeInfoStruct::OnSetValue(bool bRecursive) -{ - CVariableBase::OnSetValue(bRecursive); - if (bRecursive) - { - for (Vars::iterator it = m_Vars.begin(); it != m_Vars.end(); ++it) - { - (*it)->OnSetValue(true); - } - } -} - -void CVariableTypeInfoStruct::SetFlagRecursive(EFlags flag) -{ - CVariableBase::SetFlagRecursive(flag); - for (Vars::iterator it = m_Vars.begin(); it != m_Vars.end(); ++it) - { - (*it)->SetFlagRecursive(flag); - } -} - -void CVariableTypeInfoStruct::CopyValue(IVariable* fromVar) -{ - assert(fromVar); - if (fromVar->GetType() != IVariable::ARRAY) - { - CVariableTypeInfo::CopyValue(fromVar); - } - - int numSrc = fromVar->GetNumVariables(); - int numTrg = m_Vars.size(); - for (int i = 0; i < numSrc && i < numTrg; i++) - { - // Copy Every child variable. - m_Vars[i]->CopyValue(fromVar->GetVariable(i)); - } -} - -int CVariableTypeInfoStruct::GetNumVariables() const -{ - return m_Vars.size(); -} - -IVariable* CVariableTypeInfoStruct::GetVariable(int index) const -{ - return m_Vars[index]; -} - -CUIEnumsDBList::CUIEnumsDBList(CUIEnumsDatabase_SEnum const* pEnumList) - : m_pEnumList(pEnumList) -{ -} - -QString CUIEnumsDBList::GetItemName(uint index) -{ - if (index >= m_pEnumList->strings.size()) - { - return NULL; - } - return m_pEnumList->strings[index]; -} diff --git a/Code/Sandbox/Editor/Util/VariableTypeInfo.h b/Code/Sandbox/Editor/Util/VariableTypeInfo.h deleted file mode 100644 index 1e36d1ca96..0000000000 --- a/Code/Sandbox/Editor/Util/VariableTypeInfo.h +++ /dev/null @@ -1,221 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H -#define CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H -#pragma once - -#include "Variable.h" -#include "UIEnumsDatabase.h" -#include "VariableTypeInfo.h" - -#include - -////////////////////////////////////////////////////////////////////////// -// Adaptors for TypeInfo-defined variables to IVariable - -inline QString SpacedName(const char* sName) -{ - // Split name with spaces. - QString sSpacedName = sName; - for (int i = 1; i < sSpacedName.length(); i++) - { - if (sSpacedName[i].isUpper() && sSpacedName[i - 1].isLower()) - { - sSpacedName.insert(i, ' '); - i++; - } - } - return sSpacedName; -} - -////////////////////////////////////////////////////////////////////////// -// Scalar variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfo - : public CVariableBase -{ -public: - // Dynamic constructor function - static IVariable* Create(CTypeInfo::CVarInfo const& VarInfo, void* pBaseAddress, const void* pBaseAddressDefault); - - static EType GetType(CTypeInfo const& TypeInfo); - - CVariableTypeInfo(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, EType eType); - - void SetTypes(CTypeInfo const& TypeInfo, EType eType); - - // IVariable implementation. - virtual EType GetType() const; - virtual int GetSize() const; - - virtual void GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax); - - ////////////////////////////////////////////////////////////////////////// - // Access operators. - ////////////////////////////////////////////////////////////////////////// - - virtual void Set(const char* value); - - virtual void Set(const QString& value); - - virtual void Set(float value); - - virtual void Set(int value); - - virtual void Set(bool value); - - virtual void Set(const Vec2& value); - - virtual void Set(const Vec3& value); - - virtual void Get(QString& value) const; - - virtual void Get(float& value) const; - - virtual void Get(int& value) const; - - virtual void Get(bool& value) const; - - virtual void Get(Vec2& value) const; - - virtual void Get(Vec3& value) const; - - virtual bool HasDefaultValue() const; - - virtual void ResetToDefault(); - - virtual IVariable* Clone(bool bRecursive) const; - - // To do: This could be more efficient ? - virtual void CopyValue(IVariable* fromVar); - -protected: - CTypeInfo::CVarInfo const* m_pVarInfo; - CTypeInfo const* m_pTypeInfo; // TypeInfo system structure for this var. - void* m_pData; // Existing address in memory. Directly modified. - const void* m_pDefaultData; // Address of default data for this var. - EType m_eType; // Type info for editor. - IEditor* m_pEditor; -}; - -////////////////////////////////////////////////////////////////////////// -// Enum variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoEnum - : public CVariableTypeInfo -{ - struct CTypeInfoEnumList - : IVarEnumList - { - CTypeInfo const& TypeInfo; - - CTypeInfoEnumList(CTypeInfo const& info); - - virtual QString GetItemName(uint index); - }; - -public: - - // Constructor. - CVariableTypeInfoEnum(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, IVarEnumList* pEnumList = 0); - - ////////////////////////////////////////////////////////////////////////// - // Additional IVariable implementation. - ////////////////////////////////////////////////////////////////////////// - - IVarEnumList* GetEnumList() const; - -protected: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - TSmartPtr m_enumList; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -////////////////////////////////////////////////////////////////////////// -// Spline variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoSpline - : public CVariableTypeInfo -{ - -public: - - // Constructor. - CVariableTypeInfoSpline(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, ISplineInterpolator* pSpline); - - ~CVariableTypeInfoSpline(); - - virtual ISplineInterpolator* GetSpline(); - - //! Overrides CVariableTypeInfo to keep m_pSpline in sync with CVariableTypeInfo::m_pData - //! when Set(value) functions are called - void OnSetValue(bool bRecursive) override; - -private: - ISplineInterpolator* m_pSpline; -}; - -////////////////////////////////////////////////////////////////////////// -// Struct variable -// Inherits implementation from CVariableArray -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoStruct - : public CVariableTypeInfo -{ -public: - // Constructor. - CVariableTypeInfoStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault); - - void ProcessSubStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault); - - ////////////////////////////////////////////////////////////////////////// - // IVariable implementation. - ////////////////////////////////////////////////////////////////////////// - - virtual QString GetDisplayValue() const; - - virtual void OnSetValue(bool bRecursive); - - void SetFlagRecursive(EFlags flag) override; - - void CopyValue(IVariable* fromVar); - - int GetNumVariables() const; - - IVariable* GetVariable(int index) const; - -protected: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - typedef std::vector Vars; - Vars m_Vars; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -struct EDITOR_CORE_API CUIEnumsDBList - : IVarEnumList -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - CUIEnumsDatabase_SEnum const* m_pEnumList; - - CUIEnumsDBList(CUIEnumsDatabase_SEnum const* pEnumList); - - virtual QString GetItemName(uint index); -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H diff --git a/Code/Sandbox/Editor/editor_core_files.cmake b/Code/Sandbox/Editor/editor_core_files.cmake index 85db7ec86b..1aecbd03f6 100644 --- a/Code/Sandbox/Editor/editor_core_files.cmake +++ b/Code/Sandbox/Editor/editor_core_files.cmake @@ -54,13 +54,11 @@ set(FILES Util/MemoryBlock.cpp Util/Variable.cpp Util/UndoUtil.cpp - Util/VariableTypeInfo.cpp Util/VariablePropertyType.cpp Clipboard.h Util/MemoryBlock.h Util/Variable.h Util/UndoUtil.h - Util/VariableTypeInfo.h Util/VariablePropertyType.h Util/RefCountBase.h Util/PathUtil.h diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index a0c22c9a14..f6537909e9 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -323,11 +323,6 @@ set(FILES AzAssetBrowser/AzAssetBrowserWindow.cpp AzAssetBrowser/AzAssetBrowserWindow.h AzAssetBrowser/AzAssetBrowserWindow.ui - AzAssetBrowser/Preview/LegacyPreviewer.cpp - AzAssetBrowser/Preview/LegacyPreviewer.h - AzAssetBrowser/Preview/LegacyPreviewer.ui - AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp - AzAssetBrowser/Preview/LegacyPreviewerFactory.h AssetDatabase/AssetDatabaseLocationListener.h AssetDatabase/AssetDatabaseLocationListener.cpp AssetImporter/AssetImporterManager/AssetImporterDragAndDropHandler.cpp @@ -376,8 +371,7 @@ set(FILES Controls/MultiMonHelper.h Controls/NumberCtrl.cpp Controls/NumberCtrl.h - Controls/PreviewModelCtrl.cpp - Controls/PreviewModelCtrl.h + Controls/NumberCtrl.h Controls/SplineCtrl.cpp Controls/SplineCtrl.h Controls/SplineCtrlEx.cpp @@ -386,8 +380,6 @@ set(FILES Controls/TextEditorCtrl.h Controls/TimelineCtrl.cpp Controls/TimelineCtrl.h - Controls/TimeOfDaySlider.cpp - Controls/TimeOfDaySlider.h Controls/WndGridHelper.h Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp Controls/ReflectedPropertyControl/PropertyAnimationCtrl.h @@ -460,8 +452,6 @@ set(FILES LevelFileDialog.qrc LevelFileDialog.h LevelFileDialog.ui - PanelPreview.cpp - PanelPreview.h QuickAccessBar.cpp QuickAccessBar.h QuickAccessBar.ui @@ -495,10 +485,6 @@ set(FILES IconListDialog.ui UndoDropDown.cpp UndoDropDown.h - TimeOfDayDialog.cpp - TimeOfDayDialog.h - TimeOfDayDialog.ui - TimeOfDay.qrc DimensionsDialog.cpp DimensionsDialog.h DimensionsDialog.ui @@ -528,11 +514,7 @@ set(FILES GameResourcesExporter.cpp GameExporter.h GameResourcesExporter.h - Geometry/EdGeometry.cpp - Geometry/EdMesh.cpp Geometry/TriMesh.cpp - Geometry/EdGeometry.h - Geometry/EdMesh.h Geometry/TriMesh.h AboutDialog.h AboutDialog.ui @@ -560,8 +542,6 @@ set(FILES LevelIndependentFileMan.h LogFileImpl.cpp LogFileImpl.h - Mission.cpp - Mission.h Objects/ClassDesc.cpp Objects/ClassDesc.h Objects/IEntityObjectListener.h @@ -654,8 +634,6 @@ set(FILES LightmapCompiler/SimpleTriangleRasterizer.cpp ResourceSelectorHost.cpp ResourceSelectorHost.h - ThumbnailGenerator.cpp - ThumbnailGenerator.h ToolBox.cpp TrackViewNewSequenceDialog.cpp TrackViewNewSequenceDialog.ui @@ -687,9 +665,6 @@ set(FILES ShaderEnum.h SurfaceTypeValidator.cpp SurfaceTypeValidator.h - EnvironmentPanel.cpp - EnvironmentPanel.h - EnvironmentPanel.ui TrackView/AtomOutputFrameCapture.cpp TrackView/AtomOutputFrameCapture.h TrackView/TrackViewDialog.qrc @@ -881,9 +856,6 @@ set(FILES Grid.h LayoutWnd.cpp LayoutWnd.h - ModelViewport.cpp - ModelViewport.h - ModelViewportDC.cpp EditorViewportWidget.cpp EditorViewportWidget.h ViewportManipulatorController.cpp diff --git a/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp b/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp index 5aa5301693..5b76ca8804 100644 --- a/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include "../EditorCommon/QViewport.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp index 362452a67e..2d9598ba83 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -108,114 +107,6 @@ struct QViewport::SPreviousContext bool isMainViewport; }; -static void DrawGridLine(IRenderAuxGeom& aux, ColorB col, const float alpha, const float alphaFalloff, const float slide, const float halfSlide, [[maybe_unused]] const float maxSlide, const Vec3& stepDir, const Vec3& orthoDir, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - ColorB colEnd = col; - - float weight = 1.0f - (slide / halfSlide); - if (slide > halfSlide) - { - weight = (slide - halfSlide) / halfSlide; - } - - float orthoWeight = 1.0f; - - if (gridSettings.circular) - { - float invWeight = 1.0f - weight; - orthoWeight = sqrtf((invWeight * 2) - (invWeight * invWeight)); - } - else - { - orthoWeight = 1.0f; - } - - col.a = aznumeric_cast((1.0f - (weight * (1.0f - alphaFalloff))) * alpha); - colEnd.a = aznumeric_cast(alphaFalloff * alpha); - - Vec3 orthoStep = state.gridOrigin.q * (orthoDir * halfSlide * orthoWeight); - - Vec3 point = state.gridOrigin * (-(stepDir * halfSlide) + (stepDir * slide)); - Vec3 points[3] = { - point, - point - orthoStep, - point + orthoStep - }; - - aux.DrawLine(points[0], col, points[1], colEnd); - aux.DrawLine(points[0], col, points[2], colEnd); -} - -static void DrawGridLines(IRenderAuxGeom& aux, const uint count, const uint interStepCount, const Vec3& stepDir, const float stepSize, const Vec3& orthoDir, const float offset, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - const uint countHalf = count / 2; - Vec3 step = stepDir * stepSize; - Vec3 orthoStep = orthoDir * aznumeric_cast(countHalf); - Vec3 maxStep = step * aznumeric_cast(countHalf);// + stepDir*fabs(offset); - const float maxStepLen = count * stepSize; - const float halfStepLen = countHalf * stepSize; - - float interStepSize = interStepCount > 0 ? (stepSize / interStepCount) : stepSize; - const float alphaMulMain = (float)gridSettings.mainColor.a; - const float alphaMulInter = (float)gridSettings.middleColor.a; - const float alphaFalloff = 1.0f - (gridSettings.alphaFalloff / 100.0f); - - for (int i = 0; i < count + 2; i++) - { - float pointSlide = i * stepSize + offset; - if (pointSlide > 0.0f && pointSlide < maxStepLen) - { - DrawGridLine(aux, gridSettings.mainColor, alphaMulMain, alphaFalloff, pointSlide, halfStepLen, maxStepLen, stepDir, orthoDir, state, gridSettings); - } - - for (int d = 1; d < interStepCount; d++) - { - float interSlide = ((i - 1) * stepSize) + offset + (d * interStepSize); - if (interSlide > 0.0f && interSlide < maxStepLen) - { - DrawGridLine(aux, gridSettings.middleColor, alphaMulInter, alphaFalloff, interSlide, halfStepLen, maxStepLen, stepDir, orthoDir, state, gridSettings); - } - } - } -} - -static void DrawGrid(IRenderAuxGeom& aux, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - const uint count = gridSettings.count * 2; - const float gridSize = gridSettings.spacing * gridSettings.count * 2.0f; - const float halfGridSize = gridSettings.spacing * gridSettings.count; - - const float stepSize = gridSize / count; - DrawGridLines(aux, count, gridSettings.interCount, Vec3(1.0f, 0.0f, 0.0f), stepSize, Vec3(0.0f, 1.0f, 0.0f), state.gridCellOffset.x, state, gridSettings); - DrawGridLines(aux, count, gridSettings.interCount, Vec3(0.0f, 1.0f, 0.0f), stepSize, Vec3(1.0f, 0.0f, 0.0f), state.gridCellOffset.y, state, gridSettings); -} - -static void DrawOrigin(IRenderAuxGeom& aux, const ColorB& col) -{ - const float scale = 0.3f; - const float lineWidth = 4.0f; - aux.DrawLine(Vec3(-scale, 0, 0), col, Vec3(scale, 0, 0), col, lineWidth); - aux.DrawLine(Vec3(0, -scale, 0), col, Vec3(0, scale, 0), col, lineWidth); - aux.DrawLine(Vec3(0, 0, -scale), col, Vec3(0, 0, scale), col, lineWidth); -} - -static void DrawOrigin(IRenderAuxGeom& aux, const int left, const int top, const float scale, const Matrix34 cameraTM) -{ - Vec3 originPos = Vec3(aznumeric_cast(left), aznumeric_cast(top), 0); - Quat originRot = Quat(0.707107f, 0.707107f, 0, 0) * Quat(cameraTM).GetInverted(); - Vec3 x = originPos + originRot * Vec3(1, 0, 0) * scale; - Vec3 y = originPos + originRot * Vec3(0, 1, 0) * scale; - Vec3 z = originPos + originRot * Vec3(0, 0, 1) * scale; - ColorF xCol(1, 0, 0); - ColorF yCol(0, 1, 0); - ColorF zCol(0, 0, 1); - const float lineWidth = 2.0f; - - aux.DrawLine(originPos, xCol, x, xCol, lineWidth); - aux.DrawLine(originPos, yCol, y, yCol, lineWidth); - aux.DrawLine(originPos, zCol, z, zCol, lineWidth); -} - struct QViewport::SPrivate { CDLight m_VPLight0; @@ -494,49 +385,6 @@ void QViewport::Update() { m_averageFrameTime = 0.01f * m_lastFrameTime + 0.99f * m_averageFrameTime; } - - if (GetIEditor()->GetEnv()->pRenderer == 0 || - GetIEditor()->GetEnv()->p3DEngine == 0) - { - return; - } - - if (!isVisible()) - { - return; - } - - if (!m_renderContextCreated) - { - return; - } - - if (m_updating) - { - return; - } - - AutoBool updating(&m_updating); - - if (m_resizeWindowEvent) - { - HWND windowHandle = reinterpret_cast(QWidget::winId()); - AzFramework::WindowNotificationBus::Event(windowHandle, &AzFramework::WindowNotificationBus::Handler::OnWindowResized, m_width, m_height); - m_resizeWindowEvent = false; - } - - if (hasFocus()) - { - ProcessMouse(); - ProcessKeys(); - } - - if ((m_width <= 0) || (m_height <= 0)) - { - return; - } - - RenderInternal(); } void QViewport::CaptureMouse() @@ -860,210 +708,16 @@ void QViewport::PreRender() m_state->lastCameraParentFrame = m_state->cameraParentFrame; m_state->lastCameraTarget = currentTM; - m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip, GetIEditor()->GetEnv()->p3DEngine->GetMaxViewDistance()); + m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip); m_camera->SetMatrix(Matrix34(m_state->cameraParentFrame * currentTM)); } void QViewport::Render() { - IRenderAuxGeom* aux = GetIEditor()->GetEnv()->pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags oldFlags = aux->GetRenderFlags(); - - if (m_settings->grid.showGrid) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - DrawGrid(*aux, *m_state, m_settings->grid); - } - - if (m_settings->grid.origin) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - DrawOrigin(*aux, m_settings->grid.originColor); - } - - if (m_settings->camera.showViewportOrientation) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOn | e_DepthTestOn); - TransformationMatrices backupSceneMatrices; - GetIEditor()->GetEnv()->pRenderer->Set2DMode(m_width, m_height, backupSceneMatrices); - DrawOrigin(*aux, 50, m_height - 50, 20.0f, m_camera->GetMatrix()); - GetIEditor()->GetEnv()->pRenderer->Unset2DMode(backupSceneMatrices); - } - - // Force grid, origin and viewport orientation to render by calling Flush(). This ensures that they are always drawn behind other geometry - aux->Flush(); - aux->SetRenderFlags(oldFlags); - - // wireframe mode - CScopedWireFrameMode scopedWireFrame(GetIEditor()->GetEnv()->pRenderer, m_settings->rendering.wireframe ? R_WIREFRAME_MODE : R_SOLID_MODE); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(*m_camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - GetIEditor()->GetEnv()->pRenderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - GetIEditor()->GetEnv()->pRenderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - GetIEditor()->GetEnv()->pRenderer->EF_ClearSkinningDataPool(); - GetIEditor()->GetEnv()->pRenderer->EF_StartEf(passInfo); - - SRendParams rp; - - - //--------------------------------------------------------------------------------------- - //---- add light ------------------------------------------------------------- - //--------------------------------------------------------------------------------------- - ///////////////////////////////////////////////////////////////////////////////////// - // Confetti Start - ///////////////////////////////////////////////////////////////////////////////////// - // If time of day enabled, add sun light to preview - Confetti Vera. - if (m_settings->rendering.sunlight) - { - rp.AmbientColor.r = GetIEditor()->Get3DEngine()->GetSunColor().x / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.g = GetIEditor()->Get3DEngine()->GetSunColor().y / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.b = GetIEditor()->Get3DEngine()->GetSunColor().z / 255.0f * m_settings->lighting.m_brightness; - - m_private->m_sun.SetPosition(passInfo.GetCamera().GetPosition() + GetIEditor()->Get3DEngine()->GetSunDir()); - // The radius value respect the sun radius settings in Engine. - // Please refer to the function C3DEngine::UpdateSun(const SRenderingPassInfo &passInfo). -- Vera, Confetti - m_private->m_sun.m_fRadius = 100000000; //Radius of the sun from Engine. - m_private->m_sun.SetLightColor(GetIEditor()->Get3DEngine()->GetSunColor()); - m_private->m_sun.SetSpecularMult(GetIEditor()->Get3DEngine()->GetGlobalParameter(E3DPARAM_SUN_SPECULAR_MULTIPLIER)); - m_private->m_sun.m_Flags |= DLF_DIRECTIONAL | DLF_SUN | DLF_THIS_AREA_ONLY | DLF_LM | DLF_SPECULAROCCLUSION | - ((GetIEditor()->Get3DEngine()->IsSunShadows() && passInfo.RenderShadows()) ? DLF_CASTSHADOW_MAPS : 0); - m_private->m_sun.m_sName = "Sun"; - - GetIEditor()->GetEnv()->pRenderer->EF_ADDDlight(&m_private->m_sun, passInfo); - } - ///////////////////////////////////////////////////////////////////////////////////// - // Confetti End - ///////////////////////////////////////////////////////////////////////////////////// - else // Add directional light - { - rp.AmbientColor.r = m_settings->lighting.m_ambientColor.r / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.g = m_settings->lighting.m_ambientColor.g / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.b = m_settings->lighting.m_ambientColor.b / 255.0f * m_settings->lighting.m_brightness; - - // Directional light - if (m_settings->lighting.m_useLightRotation) - { - m_LightRotationRadian += m_averageFrameTime; - } - if (m_LightRotationRadian > gf_PI) - { - m_LightRotationRadian = -gf_PI; - } - - Matrix33 LightRot33 = Matrix33::CreateRotationZ(m_LightRotationRadian); - - f32 lightMultiplier = m_settings->lighting.m_lightMultiplier; - f32 lightSpecMultiplier = m_settings->lighting.m_lightSpecMultiplier; - - f32 lightOrbit = 15.0f; - Vec3 LPos0 = Vec3(-lightOrbit, lightOrbit, lightOrbit / 2); - m_private->m_VPLight0.SetPosition(LightRot33 * LPos0); - - Vec3 d0; - d0.x = f32(m_settings->lighting.m_directionalLightColor.r) / 255.0f; - d0.y = f32(m_settings->lighting.m_directionalLightColor.g) / 255.0f; - d0.z = f32(m_settings->lighting.m_directionalLightColor.b) / 255.0f; - m_private->m_VPLight0.SetLightColor(ColorF(d0.x * lightMultiplier, d0.y * lightMultiplier, d0.z * lightMultiplier, 0)); - m_private->m_VPLight0.SetSpecularMult(lightSpecMultiplier); - - m_private->m_VPLight0.m_Flags = DLF_SUN | DLF_DIRECTIONAL; - GetIEditor()->GetEnv()->pRenderer->EF_ADDDlight(&m_private->m_VPLight0, passInfo); - } - - //--------------------------------------------------------------------------------------- - - Matrix34 tm(IDENTITY); - rp.pMatrix = &tm; - rp.pPrevMatrix = &tm; - - rp.dwFObjFlags = 0; - - SRenderContext rc; - rc.camera = m_camera.get(); - rc.viewport = this; - rc.passInfo = &passInfo; - rc.renderParams = &rp; - - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportRender(rc); - } - SignalRender(rc); - - if ((m_settings->rendering.fps == true) && (m_averageFrameTime != 0.0f)) - { - GetIEditor()->GetEnv()->pRenderer->Draw2dLabel(12.0f, 12.0f, 1.25f, ColorF(1, 1, 1, 1), false, "FPS: %.2f", 1.0f / m_averageFrameTime); - } - - GetIEditor()->GetEnv()->pRenderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); - - if (m_mouseMovementsSinceLastFrame > 0) - { - m_mouseMovementsSinceLastFrame = 0; - - // Make sure we deliver at least last mouse movement event - OnMouseEvent(m_pendingMouseMoveEvent); - } } void QViewport::RenderInternal() { - { - threadID mainThread = 0; - threadID renderThread = 0; - GetIEditor()->GetEnv()->pRenderer->GetThreadIDs(mainThread, renderThread); - const threadID currentThreadId = CryGetCurrentThreadId(); - - // I'm not sure if this criteria is right. It might not be restrictive enough, but it's at least strict enough to prevent - // the crash we encountered. - const uint32 workerThreadId = AZ::JobContext::GetGlobalContext()->GetJobManager().GetWorkerThreadId(); - const bool isValidThread = (workerThreadId != AZ::JobManager::InvalidWorkerThreadId) || mainThread == currentThreadId || renderThread == currentThreadId; - - if (!isValidThread) - { - AZ_Assert(false, "Attempting to render QViewport on unsupported thread %" PRI_THREADID, currentThreadId); - return; - } - } - - - SetCurrentContext(); - GetIEditor()->GetEnv()->pSystem->RenderBegin(); - - ColorF viewportBackgroundColor(m_settings->background.topColor.r / 255.0f, m_settings->background.topColor.g / 255.0f, m_settings->background.topColor.b / 255.0f); - GetIEditor()->GetEnv()->pRenderer->ClearTargetsImmediately(FRT_CLEAR, viewportBackgroundColor); - GetIEditor()->GetEnv()->pRenderer->ResetToDefault(); - - // Call PreRender to interpolate the new camera position - PreRender(); - GetIEditor()->GetEnv()->pRenderer->SetCamera(*m_camera); - - IRenderAuxGeom* aux = GetIEditor()->GetEnv()->pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags oldFlags = aux->GetRenderFlags(); - - if (m_settings->background.useGradient) - { - Vec3 frustumVertices[8]; - m_camera->GetFrustumVertices(frustumVertices); - Vec3 lt = Vec3::CreateLerp(frustumVertices[0], frustumVertices[4], 0.10f); - Vec3 lb = Vec3::CreateLerp(frustumVertices[1], frustumVertices[5], 0.10f); - Vec3 rb = Vec3::CreateLerp(frustumVertices[2], frustumVertices[6], 0.10f); - Vec3 rt = Vec3::CreateLerp(frustumVertices[3], frustumVertices[7], 0.10f); - aux->SetRenderFlags(e_Mode3D | e_AlphaNone | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - ColorB topColor = m_settings->background.topColor; - ColorB bottomColor = m_settings->background.bottomColor; - aux->DrawTriangle(lt, topColor, rt, topColor, rb, bottomColor); - aux->DrawTriangle(lb, bottomColor, rb, bottomColor, lt, topColor); - aux->Flush(); - } - aux->SetRenderFlags(oldFlags); - - Render(); - - bool renderStats = false; - GetIEditor()->GetEnv()->pSystem->RenderEnd(renderStats, false); - RestorePreviousContext(); } void QViewport::GetImageOffscreen(CImageEx& image, const QSize& customSize) diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.h b/Code/Sandbox/Plugins/EditorCommon/QViewport.h index 2b18724d01..72b2024bc4 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.h +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.h @@ -28,7 +28,6 @@ struct SRenderingPassInfo; struct SRendParams; struct Ray; struct IRenderer; -struct I3DEngine; struct SSystemGlobalEnvironment; namespace Serialization { class IArchive; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui index bdb94bd489..a276adeb78 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui @@ -127,11 +127,6 @@ - - QWidget -
Controls/PreviewModelCtrl.h
- 1 -
AzToolsFramework::AspectRatioAwarePixmapWidget QWidget diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp index 8011a87ed2..7f3735dacf 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp @@ -26,9 +26,9 @@ #include #include -#include #include #include +#include #include diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp index e472ad57db..040d635bbd 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp @@ -33,8 +33,8 @@ #include #include -#include #include +#include namespace Audio { diff --git a/Gems/CMakeLists.txt b/Gems/CMakeLists.txt index 3b630cfd2f..8a9a140008 100644 --- a/Gems/CMakeLists.txt +++ b/Gems/CMakeLists.txt @@ -9,7 +9,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -add_subdirectory(ImageProcessing) add_subdirectory(TextureAtlas) add_subdirectory(LmbrCentral) add_subdirectory(LyShine) @@ -23,7 +22,6 @@ add_subdirectory(HttpRequestor) add_subdirectory(Gestures) add_subdirectory(FastNoise) add_subdirectory(GradientSignal) -add_subdirectory(GameEffectSystem) add_subdirectory(AudioSystem) add_subdirectory(AudioEngineWwise) add_subdirectory(GraphCanvas) @@ -45,7 +43,6 @@ add_subdirectory(GameState) add_subdirectory(Vegetation) add_subdirectory(GameStateSamples) add_subdirectory(SliceFavorites) -add_subdirectory(SVOGI) add_subdirectory(Metastream) add_subdirectory(ScriptCanvas) add_subdirectory(ScriptedEntityTweener) diff --git a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index 0759e1bbe9..b9b512da36 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp @@ -77,7 +77,6 @@ namespace EMotionFX m_app.RegisterComponentDescriptor(AzFramework::TransformComponent::CreateDescriptor()); m_envPrev = gEnv; - m_env.p3DEngine = nullptr; m_env.pRenderer = &m_data.m_renderer; m_env.pSystem = &m_data.m_system; gEnv = &m_env; diff --git a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp index 88b0df6e73..c825ab8834 100644 --- a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp +++ b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp @@ -115,7 +115,6 @@ struct MockGlobalEnvironment m_stubEnv.pCryPak = &m_stubPak; m_stubEnv.pConsole = &m_stubConsole; m_stubEnv.pSystem = &m_stubSystem; - m_stubEnv.p3DEngine = nullptr; gEnv = &m_stubEnv; } diff --git a/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml b/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml deleted file mode 100644 index 0e958e3c7d..0000000000 --- a/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/Gems/GameEffectSystem/Assets/seedList.seed b/Gems/GameEffectSystem/Assets/seedList.seed deleted file mode 100644 index b011adc47b..0000000000 --- a/Gems/GameEffectSystem/Assets/seedList.seed +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/Gems/GameEffectSystem/CMakeLists.txt b/Gems/GameEffectSystem/CMakeLists.txt deleted file mode 100644 index 20a680bce9..0000000000 --- a/Gems/GameEffectSystem/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -add_subdirectory(Code) diff --git a/Gems/GameEffectSystem/Code/CMakeLists.txt b/Gems/GameEffectSystem/Code/CMakeLists.txt deleted file mode 100644 index f5735b5107..0000000000 --- a/Gems/GameEffectSystem/Code/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -ly_add_target( - NAME GameEffectSystem.Static STATIC - NAMESPACE Gem - FILES_CMAKE - gameeffectsystem_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - include - source - BUILD_DEPENDENCIES - PUBLIC - Legacy::CryCommon -) - -ly_add_target( - NAME GameEffectSystem ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Gem - FILES_CMAKE - gameeffectsystem_shared_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - include - BUILD_DEPENDENCIES - PRIVATE - Gem::GameEffectSystem.Static -) diff --git a/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake b/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake deleted file mode 100644 index a8f66da7e0..0000000000 --- a/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - source/GameEffectSystem_precompiled.cpp - source/GameEffectSystem_precompiled.h - include/GameEffectSystem/IGameEffectSystem.h - include/GameEffectSystem/IGameRenderNode.h - include/GameEffectSystem/GameEffectsSystemDefines.h - include/GameEffectSystem/GameEffects/IGameEffect.h - include/GameEffectSystem/GameEffects/GameEffectBase.h - source/GameEffectsSystem.h - source/GameEffectsSystem.cpp - source/GameEffects/GameEffectSoftCodeLibrary.cpp - source/RenderElements/GameRenderElement.h - source/RenderElements/GameRenderElement.cpp - source/RenderElements/GameRenderElementSoftCodeLibrary.cpp - source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp -) diff --git a/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake b/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake deleted file mode 100644 index 565deee4c2..0000000000 --- a/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - source/GameEffectSystemGem.h - source/GameEffectSystemGem.cpp -) - diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h deleted file mode 100644 index 464c0bcdf0..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECTBASE_H_ -#define _GAMEEFFECTBASE_H_ - -#include -#include -#include "TypeLibrary.h" - -// Forward declares -struct SGameEffectParams; - -//================================================================================================== -// Name: Flag macros -// Desc: Flag macros to make code more readable -// Author: James Chilvers -//================================================================================================== -#define SET_FLAG(currentFlags, flag, state) ((state) ? (currentFlags |= flag) : (currentFlags &= ~flag)); -#define IS_FLAG_SET(currentFlags, flag) ((currentFlags & flag) ? true : false) -//-------------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: CGameEffect -// Desc: Game effect - Ideal for handling a specific visual game feature -// Author: James Chilvers -//================================================================================================== -class CGameEffect - : public IGameEffect -{ - DECLARE_TYPE(CGameEffect, IGameEffect); // Exposes this type for SoftCoding - -public: - CGameEffect(); - virtual ~CGameEffect(); - - void Initialize(const SGameEffectParams* gameEffectParams = NULL) override; - void Release() override; - void Update(float frameTime) override; - - void SetActive(bool isActive) override; - - void SetFlag(uint32 flag, bool state) override { SET_FLAG(m_flags, flag, state); } - bool IsFlagSet(uint32 flag) const override { return IS_FLAG_SET(m_flags, flag); } - uint32 GetFlags() const override { return m_flags; } - void SetFlags(uint32 flags) override { m_flags = flags; } - - void GetMemoryUsage(ICrySizer* pSizer) const override { pSizer->AddObject(this, sizeof(*this)); } - - void UnloadData() override { } - -protected: - // General data functions - static _smart_ptr LoadMaterial(const char* pMaterialName); - -private: - IGameEffect* Next() const override { return m_next; } - IGameEffect* Prev() const override { return m_prev; } - void SetNext(IGameEffect* newNext) override { m_next = newNext; } - void SetPrev(IGameEffect* newPrev) override { m_prev = newPrev; } - - IGameEffect* m_prev; - IGameEffect* m_next; - uint16 m_flags; - IGameEffectSystem* m_gameEffectSystem = nullptr; - -#if DEBUG_GAME_FX_SYSTEM - CryFixedStringT<32> m_debugName; -#endif -}; //----------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: CGameEffect -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -inline CGameEffect::CGameEffect() -{ - m_prev = NULL; - m_next = NULL; - m_flags = 0; - EBUS_EVENT_RESULT(m_gameEffectSystem, GameEffectSystemRequestBus, GetIGameEffectSystem); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: ~CGameEffect -// Desc: Destructor -//-------------------------------------------------------------------------------------------------- -inline CGameEffect::~CGameEffect() -{ -#if DEBUG_GAME_FX_SYSTEM - // Output message if effect hasn't been released before being deleted - const bool bEffectIsReleased = - (m_flags & GAME_EFFECT_RELEASED) || // -> Needs to be released before deleted - !(m_flags & GAME_EFFECT_INITIALISED) || // -> Except when not initialised - (gEnv->IsEditor()); // -> Or the editor (memory safely released by editor) - if (!bEffectIsReleased) - { - string dbgMessage = m_debugName + " being destroyed without being released first"; - FX_ASSERT_MESSAGE(bEffectIsReleased, dbgMessage.c_str()); - } -#endif - - if (m_gameEffectSystem) - { - // -> Effect should have been released and been unregistered, but to avoid - // crashes call unregister here too - m_gameEffectSystem->UnRegisterEffect(this); - } -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Initialise -// Desc: Initializes game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Initialize(const SGameEffectParams* gameEffectParams) -{ -#if DEBUG_GAME_FX_SYSTEM - m_debugName = GetName(); // Store name so it can be accessed in destructor and debugging -#endif - - if (!IsFlagSet(GAME_EFFECT_INITIALISED)) - { - SGameEffectParams params; - if (gameEffectParams) - { - params = *gameEffectParams; - } - - SetFlag(GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE, params.autoUpdatesWhenActive); - SetFlag(GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE, params.autoUpdatesWhenNotActive); - SetFlag(GAME_EFFECT_AUTO_RELEASE, params.autoRelease); - SetFlag(GAME_EFFECT_AUTO_DELETE, params.autoDelete); - - m_gameEffectSystem->RegisterEffect(this); - - SetFlag(GAME_EFFECT_INITIALISED, true); - SetFlag(GAME_EFFECT_RELEASED, false); - } -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Release -// Desc: Releases game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Release() -{ - SetFlag(GAME_EFFECT_RELEASING, true); - if (IsFlagSet(GAME_EFFECT_ACTIVE)) - { - SetActive(false); - } - m_gameEffectSystem->UnRegisterEffect(this); - SetFlag(GAME_EFFECT_INITIALISED, false); - SetFlag(GAME_EFFECT_RELEASING, false); - SetFlag(GAME_EFFECT_RELEASED, true); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Update -// Desc: Updates game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Update(float frameTime) -{ - FX_ASSERT_MESSAGE(IsFlagSet(GAME_EFFECT_INITIALISED), - "Effect being updated without being initialised first"); - FX_ASSERT_MESSAGE((IsFlagSet(GAME_EFFECT_RELEASED) == false), - "Effect being updated after being released"); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: SetActive -// Desc: Sets active status -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::SetActive(bool isActive) -{ - FX_ASSERT_MESSAGE(IsFlagSet(GAME_EFFECT_INITIALISED), - "Effect changing active status without being initialised first"); - FX_ASSERT_MESSAGE((IsFlagSet(GAME_EFFECT_RELEASED) == false), - "Effect changing active status after being released"); - - SetFlag(GAME_EFFECT_ACTIVE, isActive); - m_gameEffectSystem->RegisterEffect(this); // Re-register effect with game effects system -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: LoadMaterial -// Desc: Loads and calls AddRef on material -//-------------------------------------------------------------------------------------------------- -inline _smart_ptr CGameEffect::LoadMaterial(const char* pMaterialName) -{ - _smart_ptr pMaterial = NULL; - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (pMaterialName && p3DEngine) - { - IMaterialManager* pMaterialManager = p3DEngine->GetMaterialManager(); - if (pMaterialManager) - { - pMaterial = pMaterialManager->LoadMaterial(pMaterialName); - } - } - return pMaterial; -} //------------------------------------------------------------------------------------------------ - - -#endif//_GAMEEFFECTBASE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h deleted file mode 100644 index b2f9aed17f..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECT_INTERFACE_H_ -#define _GAMEEFFECT_INTERFACE_H_ - -#include - -//================================================================================================== -// Name: EGameEffectFlags -// Desc: Game effect flags -// Author: James Chilvers -//================================================================================================== -enum EGameEffectFlags -{ - GAME_EFFECT_INITIALISED = (1 << 0), - GAME_EFFECT_RELEASED = (1 << 1), - GAME_EFFECT_AUTO_RELEASE = (1 << 2), // Release called when Game Effect System is destroyed - GAME_EFFECT_AUTO_DELETE = (1 << 3), // Delete is called when Game Effect System is destroyed - GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE = (1 << 4), - GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE = (1 << 5), - GAME_EFFECT_REGISTERED = (1 << 6), - GAME_EFFECT_ACTIVE = (1 << 7), - GAME_EFFECT_DEBUG_EFFECT = (1 << 8), // Set true for any debug effects to avoid confusion - GAME_EFFECT_UPDATE_WHEN_PAUSED = (1 << 9), - GAME_EFFECT_RELEASING = (1 << 10) -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: SGameEffectParams -// Desc: Game effect parameters -// Author: James Chilvers -//================================================================================================== -struct SGameEffectParams -{ - friend class CGameEffect; - - // Make constructor private to stop SGameEffectParams ever being created, should always inherit - // this - // for each effect to avoid casting problems -protected: - SGameEffectParams() - { - autoUpdatesWhenActive = true; - autoUpdatesWhenNotActive = false; - autoRelease = false; - autoDelete = false; - } - -public: - bool autoUpdatesWhenActive; - bool autoUpdatesWhenNotActive; - bool autoRelease; // Release called when Game Effect System is destroyed - bool autoDelete; // Delete is called when Game Effect System is destroyed -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: IGameEffect -// Desc: Interface for all game effects -// Author: James Chilvers -//================================================================================================== -struct IGameEffect -{ - DECLARE_TYPELIB(IGameEffect); // Allow soft coding on this interface - - friend class CGameEffectsSystem; - -public: - virtual ~IGameEffect() {} - - virtual void Initialize(const SGameEffectParams* gameEffectParams = NULL) = 0; - virtual void Release() = 0; - virtual void Update(float frameTime) = 0; - - virtual void SetActive(bool isActive) = 0; - - virtual void SetFlag(uint32 flag, bool state) = 0; - virtual bool IsFlagSet(uint32 flag) const = 0; - virtual uint32 GetFlags() const = 0; - virtual void SetFlags(uint32 flags) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual const char* GetName() const = 0; - - virtual void UnloadData() = 0; - -private: - virtual IGameEffect* Next() const = 0; - virtual IGameEffect* Prev() const = 0; - virtual void SetNext(IGameEffect* newNext) = 0; - virtual void SetPrev(IGameEffect* newPrev) = 0; -}; //----------------------------------------------------------------------------------------------- - -#endif//_GAMEEFFECT_INTERFACE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h deleted file mode 100644 index 296a9975e2..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h +++ /dev/null @@ -1,179 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ -#define _EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ -#pragma once - -// Includes -#include "TypeLibrary.h" - -#include - -// Defines -#define GAME_FX_SYSTEM GetIGameEffectSystem() - -#ifndef _RELEASE -#define DEBUG_GAME_FX_SYSTEM 1 -#else -#define DEBUG_GAME_FX_SYSTEM 0 -#endif - -#if DEBUG_GAME_FX_SYSTEM -// Register effect's DebugOnInput and DebugDisplay callback functions -#define REGISTER_EFFECT_DEBUG_DATA(inputEventCallback, debugDisplayCallback, effectName) \ - static CGameEffectsSystem::SRegisterEffectDebugData effectName(inputEventCallback, \ - debugDisplayCallback, \ - #effectName) - -// Debug views -enum EGameEffectsSystemDebugView -{ - eGAME_FX_DEBUG_VIEW_None = 0, - eGAME_FX_DEBUG_VIEW_Profiling, - eGAME_FX_DEBUG_VIEW_EffectList, - eGAME_FX_DEBUG_VIEW_BoundingBox, - eGAME_FX_DEBUG_VIEW_BoundingSphere, - eGAME_FX_DEBUG_VIEW_Particles, - eMAX_GAME_FX_DEBUG_VIEWS - // ** If you add/remove a view then remember to update GAME_FX_DEBUG_VIEW_NAMES ** -}; - -#else -#define REGISTER_EFFECT_DEBUG_DATA(inputEventCallback, debugDisplayCallback, effectName) -#endif - -// FX Asserts -#if DEBUG_GAME_FX_SYSTEM -#define FX_ASSERT_MESSAGE(condition, message) \ - CRY_ASSERT_MESSAGE(condition, message); \ - if (!(condition)) \ - { \ - CryLogAlways("\n*************************************************************************" \ - "************"); \ - CryLogAlways("FX ASSERT"); \ - CryLogAlways("Condition: %s", #condition); \ - CryLogAlways("Message: %s", message); \ - CryLogAlways("File: %s", __FILE__); \ - CryLogAlways("Line: %d", __LINE__); \ - CryLogAlways("***************************************************************************" \ - "**********\n"); \ - } -#else -#define FX_ASSERT_MESSAGE(condition, message) -#endif - -// Profile tags -#define ENABLE_GAME_FX_PROFILE_TAGS 0 - -#if ENABLE_GAME_FX_PROFILE_TAGS -#define GAME_FX_PROFILE_BEGIN(_TAG_NAME_) \ - { \ - CryProfile::PushProfilingMarker(#_TAG_NAME_); \ - gEnv->pRenderer->PushProfileMarker(#_TAG_NAME_); \ - } -#define GAME_FX_PROFILE_END(_TAG_NAME_) \ - { \ - CryProfile::PopProfilingMarker(); \ - gEnv->pRenderer->PopProfileMarker(#_TAG_NAME_); \ - } -#define GAME_FX_PROFILE_MARKER(...) \ - { \ - PIXSetMarker(0, __VA_ARGS__); \ - } -#else -#define GAME_FX_PROFILE_BEGIN(_TAG_NAME_) \ - { \ - } -#define GAME_FX_PROFILE_END(_TAG_NAME_) \ - { \ - } -#define GAME_FX_PROFILE_MARKER(...) \ - { \ - } -#endif // ENABLE_GAME_FX_PROFILE_TAGS - -#define GAME_FX_LISTENER_NAME "GameEffectsSystem" -#define GAME_FX_LIBRARY_NAME "GameEffectsLibrary" -#define GAME_RENDER_NODE_LISTENER_NAME "GameRenderNodeListener" -#define GAME_RENDER_NODE_LIBRARY_NAME "GameRenderNodeLibrary" -#define GAME_RENDER_ELEMENT_LISTENER_NAME "GameRenderElementListener" -#define GAME_RENDER_ELEMENT_LIBRARY_NAME "GameRenderElementLibrary" - -// Macro to remove specific code when soft code is enabled -#ifdef SOFTCODE_ENABLED -#define REMOVE_IN_SOFT_CODE(_softCodeOnlyCode_) -#else -#define REMOVE_IN_SOFT_CODE(_softCodeOnlyCode_) _softCodeOnlyCode_ -#endif - -// Register effect's Game callbacks -#define REGISTER_GAME_CALLBACKS(enteredGameCallback, effectName) \ - static SRegisterGameCallbacks effectName(enteredGameCallback) - -// Create Game FX Soft Code instance -#ifdef SOFTCODE_ENABLED -#define CREATE_GAME_FX_SOFT_CODE_INSTANCE(T) \ - (static_cast(GAME_FX_SYSTEM.CreateSoftCodeInstance(#T))) -#else -#define CREATE_GAME_FX_SOFT_CODE_INSTANCE(T) (new T) -#endif - -// Safely release and delete effect through macro -#define SAFE_DELETE_GAME_EFFECT(pGameEffect) \ - if (pGameEffect) \ - { \ - pGameEffect->Release(); \ - SAFE_DELETE(pGameEffect); \ - } - -// Safely delete game render nodes -#define SAFE_DELETE_GAME_RENDER_NODE(pGameRenderNode) \ - if (pGameRenderNode) \ - { \ - pGameRenderNode->ReleaseGameRenderNode(); \ - gEnv->p3DEngine->FreeRenderNodeState(pGameRenderNode); \ - pGameRenderNode = NULL; \ - } - -// Safely delete game render elements -#define SAFE_DELETE_GAME_RENDER_ELEMENT(pGameRenderElement) \ - if (pGameRenderElement) \ - { \ - pGameRenderElement->ReleaseGameRenderElement(); \ - pGameRenderElement = NULL; \ - } - -// FX input -#define GAME_FX_INPUT_ReleaseDebugEffect AzFramework::InputDeviceKeyboard::Key::NavigationEnd.GetNameCrc32() -#define GAME_FX_INPUT_ResetParticleManager AzFramework::InputDeviceKeyboard::Key::NavigationDelete.GetNameCrc32() -#define GAME_FX_INPUT_PauseParticleManager AzFramework::InputDeviceKeyboard::Key::NavigationEnd.GetNameCrc32() -#define GAME_FX_INPUT_ReloadEffectData AzFramework::InputDeviceKeyboard::Key::NumPadDecimal.GetNameCrc32() -#define GAME_FX_INPUT_IncrementDebugEffectId AzFramework::InputDeviceKeyboard::Key::NumPadAdd.GetNameCrc32() -#define GAME_FX_INPUT_DecrementDebugEffectId AzFramework::InputDeviceKeyboard::Key::NumPadSubtract.GetNameCrc32() -#define GAME_FX_INPUT_IncrementDebugView AzFramework::InputDeviceKeyboard::Key::NavigationArrowRight.GetNameCrc32() -#define GAME_FX_INPUT_DecrementDebugView AzFramework::InputDeviceKeyboard::Key::NavigationArrowLeft.GetNameCrc32() - -// Forward declares -struct IGameEffect; -struct IGameRenderNode; -struct IGameRenderElement; -class CGameRenderNodeSoftCodeListener; -class CGameRenderElementSoftCodeListener; - -// Typedefs -typedef void (* EnteredGameCallback)(); -typedef void (* DebugOnInputEventCallback)(int); -typedef void (* DebugDisplayCallback)(const Vec2& textStartPos, float textSize, float textYStep); -typedef _smart_ptr IGameRenderNodePtr; -typedef _smart_ptr IGameRenderElementPtr; - -#endif//_EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h deleted file mode 100644 index 22ca06b781..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECTSYSTEM_INTERFACE_H_ -#define _GAMEEFFECTSYSTEM_INTERFACE_H_ - -#include -#include -#include -#include - -class IGameEffectSystem; -struct ITypeLibrary; - -/** - * For requesting the GameEffectSystem. - */ -class GameEffectSystemRequests - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - virtual IGameEffectSystem* GetIGameEffectSystem() = 0; -}; -using GameEffectSystemRequestBus = AZ::EBus; - -/** - * Dispatches notifications from the GameEffectSystem. - */ -class GameEffectSystemNotifications - : public AZ::EBusTraits -{ -public: - /// Called when it's appropriate to release all registered GameEffects - virtual void OnReleaseGameEffects() { } -}; -using GameEffectSystemNotificationBus = AZ::EBus; - -/// Returns global instance of IGameEffectSystem. -/// This function exists to support the legacy GAME_FX_SYSYTEM macro, -/// this is not the suggested way to fetch a singleton. -inline IGameEffectSystem& GetIGameEffectSystem() -{ - IGameEffectSystem* instance = nullptr; - EBUS_EVENT_RESULT(instance, GameEffectSystemRequestBus, GetIGameEffectSystem); - return *instance; -} - -class IGameEffectSystem -{ -public: - virtual SC_API void RegisterEffect(IGameEffect* effect) = 0; - virtual SC_API void UnRegisterEffect(IGameEffect* effect) = 0; - - virtual SC_API void GameRenderNodeInstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - virtual SC_API void GameRenderElementInstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - -#ifdef SOFTCODE_ENABLED - // Create soft code instance using libs - virtual SC_API void* CreateSoftCodeInstance(const char* pTypeName); - // Register soft code lib for creation of instances - virtual SC_API void RegisterSoftCodeLib(ITypeLibrary* pLib); -#endif - - SC_API static void RegisterEnteredGameCallback(EnteredGameCallback enteredGameCallback); - -#ifdef DEBUG_GAME_FX_SYSTEM - SC_API static void RegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback displayCallback, - const char* effectName); -#endif//DEBUG_GAME_FX_SYSTEM -}; - -#if DEBUG_GAME_FX_SYSTEM -// Creating a static version of SRegisterEffectDebugData inside an effect cpp registers the -// effect's debug data with the game effects system -struct SRegisterEffectDebugData -{ - SRegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback debugDisplayCallback, const char* effectName) - { - IGameEffectSystem::RegisterEffectDebugData(inputEventCallback, debugDisplayCallback, - effectName); - } -}; - -struct SEffectDebugData -{ - SEffectDebugData(DebugOnInputEventCallback paramInputCallback, - DebugDisplayCallback paramDisplayCallback, const char* paramEffectName) - { - inputCallback = paramInputCallback; - displayCallback = paramDisplayCallback; - effectName = paramEffectName; - } - DebugOnInputEventCallback inputCallback; - DebugDisplayCallback displayCallback; - const char* effectName; -}; -#endif//DEBUG_GAME_FX_SYSTEM - -// Creating a static version of SRegisterGameCallbacks inside an effect cpp registers the -// effect's game callback functions with the game effects system -struct SRegisterGameCallbacks -{ - SRegisterGameCallbacks(EnteredGameCallback enteredGameCallback) - { - IGameEffectSystem::RegisterEnteredGameCallback(enteredGameCallback); - } -}; - -//-------------------------------------------------------------------------------------------------- -// Desc: Game Effect System Static data - contains access to any data where static initialisation -// order is critical, this will enforce initialisation on first use -//-------------------------------------------------------------------------------------------------- -struct SGameEffectSystemStaticData -{ - static PodArray& GetEnteredGameCallbackList() - { - static PodArray enteredGameCallbackList; - return enteredGameCallbackList; - } - -#if DEBUG_GAME_FX_SYSTEM - static PodArray& GetEffectDebugList() - { - static PodArray effectDebugList; - return effectDebugList; - } -#endif//DEBUG_GAME_FX_SYSTEM -}; -// Easy access macros -#define s_enteredGameCallbackList SGameEffectSystemStaticData::GetEnteredGameCallbackList() -#if DEBUG_GAME_FX_SYSTEM -#define s_effectDebugList SGameEffectSystemStaticData::GetEffectDebugList() -#endif//DEBUG_GAME_FX_SYSTEM - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEnteredGameCallback -// Desc: Registers entered game callback -//-------------------------------------------------------------------------------------------------- -inline void IGameEffectSystem::RegisterEnteredGameCallback(EnteredGameCallback enteredGameCallback) -{ - if (enteredGameCallback) - { - s_enteredGameCallbackList.push_back(enteredGameCallback); - } -} //------------------------------------------------------------------------------------------------- - -#endif//_GAMEEFFECTSYSTEM_INTERFACE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h deleted file mode 100644 index e236dbc8a6..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ -#define _EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ -#pragma once - -#include -#include - -// Forward declares -struct IGameRenderNodeParams; - -//================================================================================================== -// Name: IGameRenderNode -// Desc: Base interface for all game render nodes -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNode - : public IRenderNode - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderNode); // Allow soft coding on this interface - - virtual ~IGameRenderNode() {} - - virtual bool InitialiseGameRenderNode() = 0; - virtual void ReleaseGameRenderNode() = 0; - - virtual void SetParams(const IGameRenderNodeParams* pParams = NULL) = 0; -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: IGameRenderNodeParams -// Desc: Game render node params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNodeParams -{ - virtual ~IGameRenderNodeParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp b/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp deleted file mode 100644 index 589364a33a..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "GameEffectSystem_precompiled.h" -#include "GameEffectSystemGem.h" - -namespace -{ - /** - * Console command function for reloading the game effect system's data. - */ - void CmdReloadGameFx([[maybe_unused]] IConsoleCmdArgs* pArgs) - { - IGameEffectSystem* iGameEffectSystem = nullptr; - GameEffectSystemRequestBus::BroadcastResult(iGameEffectSystem, &GameEffectSystemRequestBus::Events::GetIGameEffectSystem); - if (iGameEffectSystem) - { - CGameEffectsSystem* cGameEffectsSystem = reinterpret_cast(iGameEffectSystem); - cGameEffectsSystem->ReloadData(); - } - } -} - -GameEffectSystemGem::GameEffectSystemGem() - : CryHooksModule() - , m_gameEffectSystem(nullptr) - , g_gameFXSystemDebug(0) -{ - GameEffectSystemRequestBus::Handler::BusConnect(); -} - -GameEffectSystemGem::~GameEffectSystemGem() -{ - GameEffectSystemRequestBus::Handler::BusDisconnect(); -} - -void GameEffectSystemGem::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - switch (event) - { - case ESYSTEM_EVENT_GAME_POST_INIT: - // Put your init code here - // All other Gems will exist at this point - REGISTER_CVAR(g_gameFXSystemDebug, 0, 0, "Toggles game effects system debug state"); - REGISTER_COMMAND("g_reloadGameFx", &CmdReloadGameFx, 0, "Reload all game fx"); - - m_gameEffectSystem = new CGameEffectsSystem(); - m_gameEffectSystem->Initialize(); - m_gameEffectSystem->LoadData(); - break; - - case ESYSTEM_EVENT_FULL_SHUTDOWN: - case ESYSTEM_EVENT_FAST_SHUTDOWN: - if (m_gameEffectSystem) - { - m_gameEffectSystem->ReleaseData(); - m_gameEffectSystem->Destroy(); - - delete m_gameEffectSystem; - m_gameEffectSystem = nullptr; - } - break; - } -} - -IGameEffectSystem* GameEffectSystemGem::GetIGameEffectSystem() -{ - return m_gameEffectSystem; -} - -AZ_DECLARE_MODULE_CLASS(Gem_GameEffectSystem, GameEffectSystemGem) diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h b/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h deleted file mode 100644 index 930bbca726..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GEM_GAMEEFFECTSYSTEM_H_ -#define _GEM_GAMEEFFECTSYSTEM_H_ - -#include "GameEffectsSystem.h" - -class GameEffectSystemGem - : public CryHooksModule - , public GameEffectSystemRequestBus::Handler -{ -public: - AZ_RTTI(GameEffectSystemGem, "{44350C39-A90B-46EB-AC1C-DB505113F4A6}", CryHooksModule); - -public: - GameEffectSystemGem(); - ~GameEffectSystemGem() override; - - void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override; - IGameEffectSystem* GetIGameEffectSystem() override; - -private: - CGameEffectsSystem* m_gameEffectSystem; - int g_gameFXSystemDebug; -}; - -#endif//_GEM_GAMEEFFECTSYSTEM_H_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp b/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp deleted file mode 100644 index 9a1af37a08..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "GameEffectSystem_precompiled.h" diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h b/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h deleted file mode 100644 index a551219e7c..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ -#define AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ - -#include -#include -#include -#include -#include - -#endif//AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp deleted file mode 100644 index 14f55b2af6..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameEffectSoftCodeLibrary -// Desc: Game Effect Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameEffectSystem/GameEffectsSystemDefines.h" -#include "GameEffectSystem/GameEffects/IGameEffect.h" - -IMPLEMENT_TYPELIB(IGameEffect, GAME_FX_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp b/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp deleted file mode 100644 index b9a2d4dfa7..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp +++ /dev/null @@ -1,1012 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: CGameEffectsSystem -// Desc: System to handle game effects, render nodes and render elements -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameEffectsSystem.h" -#include "BitFiddling.h" -#include "RenderElements/GameRenderElement.h" -#include -#include - -#include - -//-------------------------------------------------------------------------------------------------- -// Desc: Defines -//-------------------------------------------------------------------------------------------------- -#define GAME_FX_DATA_FILE "scripts/effects/gameeffects.xml" -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Desc: Debug data -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -int CGameEffectsSystem::s_currentDebugEffectId = 0; - -const char* GAME_FX_DEBUG_VIEW_NAMES[eMAX_GAME_FX_DEBUG_VIEWS] = { - "None", "Profiling", - "Effect List", "Bounding Box", - "Bounding Sphere", "Particles" -}; - -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Desc: Static data -//-------------------------------------------------------------------------------------------------- -int CGameEffectsSystem::s_postEffectCVarNameOffset = 0; -//-------------------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: CGameRenderNodeSoftCodeListener -// Desc: Game Render Node Soft Code Listener -// Author: James Chilvers -//================================================================================================== -class CGameRenderNodeSoftCodeListener - : public ISoftCodeListener -{ -public: - CGameRenderNodeSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_RENDER_NODE_LIBRARY_NAME, this, - GAME_RENDER_NODE_LISTENER_NAME); - } - } - virtual ~CGameRenderNodeSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_RENDER_NODE_LIBRARY_NAME, this); - } - } - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - GAME_FX_SYSTEM.GameRenderNodeInstanceReplaced(pOldInstance, pNewInstance); - } -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: CGameRenderElementSoftCodeListener -// Desc: Game Render Element Soft Code Listener -// Author: James Chilvers -//================================================================================================== -class CGameRenderElementSoftCodeListener - : public ISoftCodeListener -{ -public: - CGameRenderElementSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_RENDER_ELEMENT_LIBRARY_NAME, this, - GAME_RENDER_ELEMENT_LISTENER_NAME); - } - } - virtual ~CGameRenderElementSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_RENDER_ELEMENT_LIBRARY_NAME, this); - } - } - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - GAME_FX_SYSTEM.GameRenderElementInstanceReplaced(pOldInstance, pNewInstance); - } -}; //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: CGameEffectsSystem -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -CGameEffectsSystem::CGameEffectsSystem() - : AzFramework::InputChannelEventListener(AzFramework::InputChannelEventListener::GetPriorityDebug()) -{ -#if DEBUG_GAME_FX_SYSTEM - AzFramework::InputChannelEventListener::Connect(); -#endif - -#ifdef SOFTCODE_ENABLED - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_FX_LIBRARY_NAME, this, GAME_FX_LISTENER_NAME); - } - - m_gameRenderNodes.clear(); - m_gameRenderNodeSoftCodeListener = new CGameRenderNodeSoftCodeListener; - - m_gameRenderElements.clear(); - m_gameRenderElementSoftCodeListener = new CGameRenderElementSoftCodeListener; - - RegisterSoftCodeLib(IGameEffect::TLibrary::Instance()); - RegisterSoftCodeLib(IGameRenderNode::TLibrary::Instance()); - RegisterSoftCodeLib(IGameRenderElement::TLibrary::Instance()); -#endif - - Reset(); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ~CGameEffectsSystem -// Desc: Destructor -//-------------------------------------------------------------------------------------------------- -CGameEffectsSystem::~CGameEffectsSystem() -{ -#if DEBUG_GAME_FX_SYSTEM - AzFramework::InputChannelEventListener::Disconnect(); -#endif - -#ifdef SOFTCODE_ENABLED - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_FX_LIBRARY_NAME, this); - } - - SAFE_DELETE(m_gameRenderNodeSoftCodeListener); - SAFE_DELETE(m_gameRenderElementSoftCodeListener); - m_softCodeTypeLibs.clear(); - m_gameRenderNodes.clear(); - m_gameRenderElements.clear(); -#endif - - AZ::TickBus::Handler::BusDisconnect(); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Destroy -// Desc: Destroys effects system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Destroy() -{ - EBUS_EVENT(GameEffectSystemNotificationBus, OnReleaseGameEffects); - AutoReleaseAndDeleteFlaggedEffects(m_effectsToUpdate); - AutoReleaseAndDeleteFlaggedEffects(m_effectsNotToUpdate); - FX_ASSERT_MESSAGE(m_effectsToUpdate == nullptr && m_effectsNotToUpdate == nullptr, - "Game Effects System being destroyed even though game effects still exist!"); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Reset -// Desc: Resets effects systems data -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Reset() -{ - m_isInitialised = false; - m_effectsToUpdate = NULL; - m_effectsNotToUpdate = NULL; - m_nextEffectToUpdate = NULL; - s_postEffectCVarNameOffset = 0; - -#if DEBUG_GAME_FX_SYSTEM - m_debugView = eGAME_FX_DEBUG_VIEW_None; -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Initialize -// Desc: Initializes effects system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Initialize() -{ - if (m_isInitialised == false) - { - Reset(); - SetPostEffectCVarCallbacks(); - - AZ::TickBus::Handler::BusConnect(); - - m_isInitialised = true; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRulesInitialise -// Desc: Game Rules initialise -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRulesInitialise() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: LoadData -// Desc: Loads data for game effects system and effects -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::LoadData() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReleaseData -// Desc: Releases any loaded data for game effects system and any effects with registered callbacks -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::ReleaseData() -{ - if (s_hasLoadedData) - { -#if DEBUG_GAME_FX_SYSTEM - // Unload all debug effects which rely on effect data - for (size_t i = 0; i < s_effectDebugList.Size(); i++) - { - if (s_effectDebugList[i].inputCallback) - { - s_effectDebugList[i].inputCallback(GAME_FX_INPUT_ReleaseDebugEffect); - } - } -#endif - - for (IGameEffect* ge = m_effectsToUpdate; ge; ge = ge->Next()) - { - ge->UnloadData(); - } - for (IGameEffect* ge = m_effectsNotToUpdate; ge; ge = ge->Next()) - { - ge->UnloadData(); - } - s_hasLoadedData = false; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReloadData -// Desc: Reloads any loaded data for game effects registered callbacks -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::ReloadData() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: EnteredGame -// Desc: Called when entering a game -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::EnteredGame() -{ - const int callbackCount = s_enteredGameCallbackList.size(); - EnteredGameCallback enteredGameCallbackFunc = NULL; - for (int i = 0; i < callbackCount; i++) - { - enteredGameCallbackFunc = s_enteredGameCallbackList[i]; - if (enteredGameCallbackFunc) - { - enteredGameCallbackFunc(); - } - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: AutoReleaseAndDeleteFlaggedEffects -// Desc: Calls release and delete on any effects with the these flags set -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::AutoReleaseAndDeleteFlaggedEffects(IGameEffect* effectList) -{ - if (effectList) - { - IGameEffect* effect = effectList; - while (effect) - { - m_nextEffectToUpdate = effect->Next(); - - bool autoRelease = effect->IsFlagSet(GAME_EFFECT_AUTO_RELEASE); - bool autoDelete = effect->IsFlagSet(GAME_EFFECT_AUTO_DELETE); - - if (autoRelease || autoDelete) - { - SOFTCODE_RETRY(effect, effect->Release()); - if (autoDelete) - { - SAFE_DELETE(effect); - } - } - - effect = m_nextEffectToUpdate; - } - m_nextEffectToUpdate = NULL; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: InstanceReplaced -// Desc: Replaces instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::InstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pNewInstance && pOldInstance) - { - IGameEffect* pNewGameEffectInstance = static_cast(pNewInstance); - IGameEffect* pOldGameEffectInstance = static_cast(pOldInstance); - - // Copy over flags and remove registered flag so new effect instance can be registered - // We haven't used the SOFT macro on the m_flags member because the oldInstance's flags - // would then be Nulled out, and they are needed for the effect to be deregistered - uint32 oldGameEffectFlags = pOldGameEffectInstance->GetFlags(); - SET_FLAG(oldGameEffectFlags, GAME_EFFECT_REGISTERED, false); - pNewGameEffectInstance->SetFlags(oldGameEffectFlags); - - // Register new effect instance, old instance will get unregistered by destructor - GAME_FX_SYSTEM.RegisterEffect(pNewGameEffectInstance); - - // Reload all data used by effects, then data can be added/removed for soft coding - ReloadData(); - - // Data used by effect will be copied to new effect, so mustn't release it but - // must set flag so destructor doesn't assert - pOldGameEffectInstance->SetFlag(GAME_EFFECT_RELEASED, true); - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRenderNodeInstanceReplaced -// Desc: Replaces Game Render Node instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRenderNodeInstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pOldInstance && pNewInstance) - { - IGameRenderNode* pOldGameRenderNodeInstance = (IGameRenderNode*)pOldInstance; - IGameRenderNode* pNewGameRenderNodeInstance = (IGameRenderNode*)pNewInstance; - - // Unregister old node from engine - gEnv->p3DEngine->FreeRenderNodeState(pOldGameRenderNodeInstance); - - // Register new node with engine - gEnv->p3DEngine->RegisterEntity(pNewGameRenderNodeInstance); - - for (TGameRenderNodeVec::iterator iter(m_gameRenderNodes.begin()); - iter != m_gameRenderNodes.end(); ++iter) - { - IGameRenderNodePtr* ppRenderNode = *iter; - if (ppRenderNode) - { - IGameRenderNodePtr& pRenderNode = *ppRenderNode; - - if (pRenderNode == pOldGameRenderNodeInstance) - { - pRenderNode = pNewGameRenderNodeInstance; - } - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRenderElementInstanceReplaced -// Desc: Replaces Game Render Element instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRenderElementInstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pOldInstance && pNewInstance) - { - IGameRenderElement* pOldGameRenderElementInstance = (IGameRenderElement*)pOldInstance; - IGameRenderElement* pNewGameRenderElementInstance = (IGameRenderElement*)pNewInstance; - - pNewGameRenderElementInstance->UpdatePrivateImplementation(); - - for (TGameRenderElementVec::iterator iter(m_gameRenderElements.begin()); - iter != m_gameRenderElements.end(); ++iter) - { - IGameRenderElementPtr* ppRenderElement = *iter; - if (ppRenderElement) - { - IGameRenderElementPtr& pRenderElement = *ppRenderElement; - - if (pRenderElement == pOldGameRenderElementInstance) - { - pRenderElement = pNewGameRenderElementInstance; - } - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: SetPostEffectCVarCallbacks -// Desc: Sets Post effect CVar callbacks for testing and tweaking post effect values -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::SetPostEffectCVarCallbacks() -{ -#if DEBUG_GAME_FX_SYSTEM - ICVar* postEffectCvar = NULL; - const char postEffectNames[][64] = - { - "g_postEffect.FilterGrain_Amount", "g_postEffect.FilterRadialBlurring_Amount", - "g_postEffect.FilterRadialBlurring_ScreenPosX", - "g_postEffect.FilterRadialBlurring_ScreenPosY", "g_postEffect.FilterRadialBlurring_Radius", - "g_postEffect.Global_User_ColorC", "g_postEffect.Global_User_ColorM", - "g_postEffect.Global_User_ColorY", "g_postEffect.Global_User_ColorK", - "g_postEffect.Global_User_Brightness", "g_postEffect.Global_User_Contrast", - "g_postEffect.Global_User_Saturation", "g_postEffect.Global_User_ColorHue" - }; - - int postEffectNameCount = sizeof(postEffectNames) / sizeof(*postEffectNames); - - if (postEffectNameCount > 0) - { - // Calc name offset - const char* postEffectName = postEffectNames[0]; - s_postEffectCVarNameOffset = 0; - while ((*postEffectName) != 0) - { - s_postEffectCVarNameOffset++; - if ((*postEffectName) == '.') - { - break; - } - postEffectName++; - } - - // Set callback functions - for (int i = 0; i < postEffectNameCount; i++) - { - postEffectCvar = gEnv->pConsole->GetCVar(postEffectNames[i]); - if (postEffectCvar) - { - postEffectCvar->SetOnChangeCallback(PostEffectCVarCallback); - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: PostEffectCVarCallback -// Desc: Callback function of post effect cvars to set their values -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::PostEffectCVarCallback(ICVar* cvar) -{ - const char* effectName = cvar->GetName() + s_postEffectCVarNameOffset; - gEnv->p3DEngine->SetPostEffectParam(effectName, cvar->GetFVal()); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEffect -// Desc: Registers effect with effect system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterEffect(IGameEffect* effect) -{ - FX_ASSERT_MESSAGE(m_isInitialised, - "Game Effects System trying to register an effect without being initialised"); - FX_ASSERT_MESSAGE(effect, "Trying to Register a NULL effect"); - - if (effect) - { - // If effect is registered, then unregister first - if (effect->IsFlagSet(GAME_EFFECT_REGISTERED)) - { - UnRegisterEffect(effect); - } - - // Add effect to effect list - IGameEffect** effectList = NULL; - bool isActive = effect->IsFlagSet(GAME_EFFECT_ACTIVE); - bool autoUpdatesWhenActive = effect->IsFlagSet(GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE); - bool autoUpdatesWhenNotActive = effect->IsFlagSet(GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE); - if ((isActive && autoUpdatesWhenActive) || ((!isActive) && autoUpdatesWhenNotActive)) - { - effectList = &m_effectsToUpdate; - } - else - { - effectList = &m_effectsNotToUpdate; - } - - if (*effectList) - { - (*effectList)->SetPrev(effect); - effect->SetNext(*effectList); - } - (*effectList) = effect; - - effect->SetFlag(GAME_EFFECT_REGISTERED, true); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnRegisterEffect -// Desc: UnRegisters effect from effect system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnRegisterEffect(IGameEffect* effect) -{ - FX_ASSERT_MESSAGE( - m_isInitialised, - "Game Effects System trying to unregister an effect without being initialised"); - FX_ASSERT_MESSAGE(effect, "Trying to UnRegister a NULL effect"); - - if (effect && effect->IsFlagSet(GAME_EFFECT_REGISTERED)) - { - // If the effect is the next one to be updated, then point m_nextEffectToUpdate to the next - // effect after it - if (effect == m_nextEffectToUpdate) - { - m_nextEffectToUpdate = m_nextEffectToUpdate->Next(); - } - - if (effect->Prev()) - { - effect->Prev()->SetNext(effect->Next()); - } - else - { - if (m_effectsToUpdate == effect) - { - m_effectsToUpdate = effect->Next(); - } - else - { - FX_ASSERT_MESSAGE((m_effectsNotToUpdate == effect), - "Effect isn't either updating list"); - m_effectsNotToUpdate = effect->Next(); - } - } - - if (effect->Next()) - { - effect->Next()->SetPrev(effect->Prev()); - } - - effect->SetNext(NULL); - effect->SetPrev(NULL); - - effect->SetFlag(GAME_EFFECT_REGISTERED, false); - } -} //------------------------------------------------------------------------------------------------- - -void CGameEffectsSystem::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) -{ - Update(deltaTime); -} - -//-------------------------------------------------------------------------------------------------- -// Name: Update -// Desc: Updates effects system and any effects registered in it's update list -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Update(float frameTime) -{ - FX_ASSERT_MESSAGE(m_isInitialised, - "Game Effects System trying to update without being initialised"); - - // Update effects - if (m_effectsToUpdate) - { - IGameEffect* effect = m_effectsToUpdate; - while (effect) - { - m_nextEffectToUpdate = effect->Next(); - if (effect->IsFlagSet(GAME_EFFECT_UPDATE_WHEN_PAUSED)) - { - SOFTCODE_RETRY(effect, effect->Update(frameTime)); - } - effect = m_nextEffectToUpdate; - } - } - - m_nextEffectToUpdate = NULL; - -#if DEBUG_GAME_FX_SYSTEM - DrawDebugDisplay(); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: CreateSoftCodeInstance -// Desc: Creates soft code instance -//-------------------------------------------------------------------------------------------------- -#ifdef SOFTCODE_ENABLED -void* CGameEffectsSystem::CreateSoftCodeInstance(const char* pTypeName) -{ - void* pNewInstance = NULL; - - if (pTypeName) - { - for (std::vector::iterator iter(m_softCodeTypeLibs.begin()); - iter != m_softCodeTypeLibs.end(); ++iter) - { - ITypeLibrary* pLib = *iter; - if (pLib) - { - if (pNewInstance = pLib->CreateInstanceVoid(pTypeName)) - { - break; - } - } - } - } - - return pNewInstance; -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterSoftCodeLib -// Desc: Register soft code lib for creation of instances -//-------------------------------------------------------------------------------------------------- -#ifdef SOFTCODE_ENABLED -void CGameEffectsSystem::RegisterSoftCodeLib(ITypeLibrary* pLib) -{ - m_softCodeTypeLibs.push_back(pLib); -}; -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterGameRenderNode -// Desc: Registers game render node -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterGameRenderNode([[maybe_unused]] IGameRenderNodePtr& pGameRenderNode) -{ -#ifdef SOFTCODE_ENABLED - for (TGameRenderNodeVec::iterator iter(m_gameRenderNodes.begin()); - iter != m_gameRenderNodes.end(); ++iter) - { - IGameRenderNodePtr* ppIterRenderNode = *iter; - if (ppIterRenderNode == NULL) - { - *iter = &pGameRenderNode; - return; - } - } - m_gameRenderNodes.push_back(&pGameRenderNode); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnregisterGameRenderNode -// Desc: Unregisters game render node -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnregisterGameRenderNode([[maybe_unused]] IGameRenderNodePtr& pGameRenderNode) -{ -#ifdef SOFTCODE_ENABLED - TGameRenderNodeVec::iterator iter( - std::find(m_gameRenderNodes.begin(), m_gameRenderNodes.end(), &pGameRenderNode)); - if (iter != m_gameRenderNodes.end()) - { - *iter = NULL; - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterGameRenderElement -// Desc: Registers game render element -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterGameRenderElement([[maybe_unused]] IGameRenderElementPtr& pGameRenderElement) -{ -#ifdef SOFTCODE_ENABLED - for (TGameRenderElementVec::iterator iter(m_gameRenderElements.begin()); - iter != m_gameRenderElements.end(); ++iter) - { - IGameRenderElementPtr* ppIterRenderElement = *iter; - if (ppIterRenderElement == NULL) - { - *iter = &pGameRenderElement; - return; - } - } - m_gameRenderElements.push_back(&pGameRenderElement); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnregisterGameRenderElement -// Desc: Unregisters game render element -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnregisterGameRenderElement([[maybe_unused]] IGameRenderElementPtr& pGameRenderElement) -{ -#ifdef SOFTCODE_ENABLED - TGameRenderElementVec::iterator iter( - std::find(m_gameRenderElements.begin(), m_gameRenderElements.end(), &pGameRenderElement)); - if (iter != m_gameRenderElements.end()) - { - *iter = NULL; - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: DrawDebugDisplay -// Desc: Draws debug display -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::DrawDebugDisplay() -{ - static ColorF textCol(1.0f, 1.0f, 1.0f, 1.0f); - static ColorF controlCol(0.6f, 0.6f, 0.6f, 1.0f); - - static Vec2 textPos(10.0f, 10.0f); - static float textSize = 1.4f; - static float textYSpacing = 18.0f; - - static float effectNameXOffset = 100.0f; - static ColorF effectNameCol(0.0f, 1.0f, 0.0f, 1.0f); - - Vec2 currentTextPos = textPos; - - int debugEffectCount = s_effectDebugList.Size(); - if (GetISystem()->GetIConsole()->GetCVar("g_gameFXSystemDebug")->GetIVal() && debugEffectCount > 0) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &textCol.r, - false, "Debug view:"); - gEnv->pRenderer->Draw2dLabel(currentTextPos.x + effectNameXOffset, currentTextPos.y, - textSize, &effectNameCol.r, false, - GAME_FX_DEBUG_VIEW_NAMES[m_debugView]); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Change debug view: Left/Right arrows)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &textCol.r, - false, "Debug effect:"); - gEnv->pRenderer->Draw2dLabel(currentTextPos.x + effectNameXOffset, currentTextPos.y, - textSize, &effectNameCol.r, false, - s_effectDebugList[s_currentDebugEffectId].effectName); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Change effect: NumPad +/-)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Reload effect data: NumPad .)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Reset Particle System: Delete)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Pause Particle System: End)"); - currentTextPos.y += textYSpacing; - - if (s_effectDebugList[s_currentDebugEffectId].displayCallback) - { - s_effectDebugList[s_currentDebugEffectId].displayCallback(currentTextPos, textSize, - textYSpacing); - } - - if (m_debugView == eGAME_FX_DEBUG_VIEW_EffectList) - { - static Vec2 listPos(350.0f, 50.0f); - static float nameSize = 150.0f; - static float tabSize = 60.0f; - currentTextPos = listPos; - - const int EFFECT_LIST_COUNT = 2; - IGameEffect* pEffectListArray[EFFECT_LIST_COUNT] = { - m_effectsToUpdate, - m_effectsNotToUpdate - }; - - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &effectNameCol.r, false, "Name"); - currentTextPos.x += nameSize; - - const int FLAG_COUNT = 9; - - const char* flagName[FLAG_COUNT] = { - "Init", "Rel", "ARels", "ADels", "AUWA", - "AUWnA", "Reg", "Actv", "DBG" - }; - const int flag[FLAG_COUNT] = { - GAME_EFFECT_INITIALISED, GAME_EFFECT_RELEASED, - GAME_EFFECT_AUTO_RELEASE, GAME_EFFECT_AUTO_DELETE, - GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE, - GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE, - GAME_EFFECT_REGISTERED, GAME_EFFECT_ACTIVE, - GAME_EFFECT_DEBUG_EFFECT - }; - - for (int i = 0; i < FLAG_COUNT; i++) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &effectNameCol.r, false, flagName[i]); - currentTextPos.x += tabSize; - } - - currentTextPos.y += textYSpacing; - - for (int l = 0; l < EFFECT_LIST_COUNT; l++) - { - IGameEffect* pCurrentEffect = pEffectListArray[l]; - while (pCurrentEffect) - { - currentTextPos.x = listPos.x; - - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &textCol.r, false, pCurrentEffect->GetName()); - currentTextPos.x += nameSize; - - for (int i = 0; i < FLAG_COUNT; i++) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &textCol.r, false, - pCurrentEffect->IsFlagSet(flag[i]) ? "1" - : "0"); - currentTextPos.x += tabSize; - } - - currentTextPos.y += textYSpacing; - pCurrentEffect = pCurrentEffect->Next(); - } - } - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnInputChannelEventFiltered -// Desc: Handles any debug input for the game effects system to test effects -//-------------------------------------------------------------------------------------------------- -bool CGameEffectsSystem::OnInputChannelEventFiltered([[maybe_unused]] const AzFramework::InputChannel& inputChannel) -{ -#if DEBUG_GAME_FX_SYSTEM - - int debugEffectCount = s_effectDebugList.Size(); - - if ((GetISystem()->GetIConsole()->GetCVar("g_gameFXSystemDebug")->GetIVal()) && (debugEffectCount > 0)) - { - if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(inputChannel.GetInputDevice().GetInputDeviceId()) && - inputChannel.IsStateBegan()) - { - const AZ::Crc32& inputChannelNameCrc32 = inputChannel.GetInputChannelId().GetNameCrc32(); - if (inputChannelNameCrc32 == GAME_FX_INPUT_IncrementDebugEffectId) - { - if (s_currentDebugEffectId < (debugEffectCount - 1)) - { - s_currentDebugEffectId++; - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_DecrementDebugEffectId) - { - if (s_currentDebugEffectId > 0) - { - s_currentDebugEffectId--; - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_DecrementDebugView) - { - if (m_debugView > 0) - { - OnDeActivateDebugView(m_debugView); - m_debugView--; - OnActivateDebugView(m_debugView); - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_IncrementDebugView) - { - if (m_debugView < (eMAX_GAME_FX_DEBUG_VIEWS - 1)) - { - OnDeActivateDebugView(m_debugView); - m_debugView++; - OnActivateDebugView(m_debugView); - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_ReloadEffectData) - { - ReloadData(); - } - - // Send input to current debug effect - if (s_effectDebugList[s_currentDebugEffectId].inputCallback) - { - s_effectDebugList[s_currentDebugEffectId].inputCallback(inputChannelNameCrc32); - } - } - } -#endif - - return false; // Return false so that other listeners will get this event -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GetDebugEffect -// Desc: Gets debug instance of effect -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -IGameEffect* CGameEffectsSystem::GetDebugEffect(const char* pEffectName) const -{ - const int EFFECT_LIST_COUNT = 2; - IGameEffect* pEffectListArray[EFFECT_LIST_COUNT] = {m_effectsToUpdate, m_effectsNotToUpdate}; - - for (int l = 0; l < EFFECT_LIST_COUNT; l++) - { - IGameEffect* pCurrentEffect = pEffectListArray[l]; - while (pCurrentEffect) - { - if (pCurrentEffect->IsFlagSet(GAME_EFFECT_DEBUG_EFFECT) && - (strcmp(pCurrentEffect->GetName(), pEffectName) == 0)) - { - return pCurrentEffect; - } - pCurrentEffect = pCurrentEffect->Next(); - } - } - - return NULL; -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnActivateDebugView -// Desc: Called on debug view activation -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::OnActivateDebugView(int debugView) -{ - switch (debugView) - { - case eGAME_FX_DEBUG_VIEW_Profiling: - { - ICVar* r_displayInfoCVar = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (r_displayInfoCVar) - { - r_displayInfoCVar->Set(1); - } - break; - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnDeActivateDebugView -// Desc: Called on debug view de-activation -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::OnDeActivateDebugView(int debugView) -{ - switch (debugView) - { - case eGAME_FX_DEBUG_VIEW_Profiling: - { - ICVar* r_displayInfoCVar = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (r_displayInfoCVar) - { - r_displayInfoCVar->Set(0); - } - break; - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEffectDebugData -// Desc: Registers effect's debug data with the game effects system, which will then call the -// relevant debug callback functions for the for the effect when its selected -//using the -// s_currentDebugEffectId -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void IGameEffectSystem::RegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback displayCallback, - const char* effectName) -{ - s_effectDebugList.push_back(SEffectDebugData(inputEventCallback, displayCallback, effectName)); -} -#endif -//-------------------------------------------------------------------------------------------------- diff --git a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h b/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h deleted file mode 100644 index 4dd6fe0435..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_GAMEEFFECTSSYSTEM_H_ -#define _EFFECTS_GAMEEFFECTSSYSTEM_H_ -#pragma once - -// Includes -#include "GameEffectSystem/IGameEffectSystem.h" -#include "GameEffectSystem/GameEffectsSystemDefines.h" -#include -#include - -//================================================================================================== -// Name: CGameEffectsSystem -// Desc: System to handle game effects, game render nodes and game render elements -// Game effect: separates out effect logic from game logic -// Game render node: handles the render object in 3d space -// Game render element: handles the rendering of the object -// CVar activation system: system used to have data driven cvars activated in game -//effects -// Post effect activation system: system used to have data driven post effects -//activated in game effects -// Author: James Chilvers -//================================================================================================== -class CGameEffectsSystem - : public IGameEffectSystem - , public AzFramework::InputChannelEventListener - , public ISoftCodeListener - , public AZ::TickBus::Handler -{ - friend struct SGameEffectSystemStaticData; - -public: - void Destroy(); - void Initialize(); - void LoadData(); - void ReleaseData(); - - template - T* CreateEffect() // Use if dynamic memory allocation is required for the game effect - { // Using this function then allows easy changing of memory allocator for all dynamically - // created effects - T* newEffect = new T; - return newEffect; - } - - // Each effect automatically registers and unregisters itself - SC_API void RegisterEffect(IGameEffect* effect) override; - SC_API void UnRegisterEffect(IGameEffect* effect) override; - - void Update(float frameTime); - - SC_API void RegisterGameRenderNode(IGameRenderNodePtr& pGameRenderNode); - SC_API void UnregisterGameRenderNode(IGameRenderNodePtr& pGameRenderNode); - - SC_API void RegisterGameRenderElement(IGameRenderElementPtr& pGameRenderElement); - SC_API void UnregisterGameRenderElement(IGameRenderElementPtr& pGameRenderElement); - -#ifdef SOFTCODE_ENABLED - SC_API void* - CreateSoftCodeInstance(const char* pTypeName) override; // Create soft code instance using libs - SC_API void - RegisterSoftCodeLib(ITypeLibrary* pLib) override; // Register soft code lib for creation of instances -#endif - - bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - - // ISoftCodeListener implementation - void InstanceReplaced(void* pOldInstance, void* pNewInstance) override; - void GameRenderNodeInstanceReplaced(void* pOldInstance, void* pNewInstance) override; - void GameRenderElementInstanceReplaced(void* pOldInstance, void* pNewInstance) override; - - // SGameRulesListener implementation - void GameRulesInitialise(); - // #TODO: Have this receive events from GameRules - void EnteredGame();// override; - - void ReloadData(); - - CGameEffectsSystem(); - virtual ~CGameEffectsSystem(); - - // AZ::TickBus::Handler implementation - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - -private: - void Reset(); - void AutoReleaseAndDeleteFlaggedEffects(IGameEffect* effectList); - void AutoDeleteEffects(IGameEffect* effectList); - void SetPostEffectCVarCallbacks(); - static void PostEffectCVarCallback(ICVar* cvar); - -#if DEBUG_GAME_FX_SYSTEM - void DrawDebugDisplay(); - void OnActivateDebugView(int debugView); - void OnDeActivateDebugView(int debugView); - - int GetDebugView() const { return m_debugView; } - SC_API IGameEffect* GetDebugEffect(const char* pEffectName) const; - - static int s_currentDebugEffectId; - - int m_debugView; -#endif - - static int s_postEffectCVarNameOffset; - -#ifdef SOFTCODE_ENABLED - std::vector m_softCodeTypeLibs; - - typedef std::vector TGameRenderNodeVec; - TGameRenderNodeVec m_gameRenderNodes; - CGameRenderNodeSoftCodeListener* m_gameRenderNodeSoftCodeListener; - - typedef std::vector TGameRenderElementVec; - TGameRenderElementVec m_gameRenderElements; - CGameRenderElementSoftCodeListener* m_gameRenderElementSoftCodeListener; -#endif - - IGameEffect* m_effectsToUpdate; - IGameEffect* m_effectsNotToUpdate; - // If in update loop, this is the next effect to be updated this will get changed if the effect is unregistered - IGameEffect* m_nextEffectToUpdate; - bool m_isInitialised; - bool s_hasLoadedData; -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_GAMEEFFECTSSYSTEM_H_ diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp deleted file mode 100644 index c68b8526b0..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: CGameRenderElement -// Desc: Base class for all game render elements -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameRenderElement.h" - -//-------------------------------------------------------------------------------------------------- -// Name: CGameRenderElement -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -CGameRenderElement::CGameRenderElement() -{ - m_pREGameEffect = NULL; -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: InitialiseGameRenderElement -// Desc: Initialises game render element -//-------------------------------------------------------------------------------------------------- -bool CGameRenderElement::InitialiseGameRenderElement() -{ - m_pREGameEffect = (CREGameEffect*)gEnv->pRenderer->EF_CreateRE(eDATA_GameEffect); - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(this); - m_pREGameEffect->mfUpdateFlags(FCEF_TRANSFORM); - } - - return true; -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReleaseGameRenderElement -// Desc: Releases game render element -//-------------------------------------------------------------------------------------------------- -void CGameRenderElement::ReleaseGameRenderElement() -{ - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(NULL); - m_pREGameEffect->Release(false); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UpdatePrivateImplementation -// Desc: Updates private implementation -//-------------------------------------------------------------------------------------------------- -void CGameRenderElement::UpdatePrivateImplementation() -{ - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(this); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GetCREGameEffect -// Desc: returns the game effect render element -//-------------------------------------------------------------------------------------------------- -CREGameEffect* CGameRenderElement::GetCREGameEffect() -{ - return m_pREGameEffect; -} //------------------------------------------------------------------------------------------------- diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h deleted file mode 100644 index 37d149cdde..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ -#define _EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ -#pragma once - -// Includes -#include "GameEffectsSystem.h" -#include - -// Forward declares -struct IGameRenderElementParams; - -//================================================================================================== -// Name: IGameRenderElement -// Desc: Base interface for all game render elements -// Author: James Chilvers -//================================================================================================== -struct IGameRenderElement - : public IREGameEffect - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderElement); // Allow soft coding on this interface - - virtual ~IGameRenderElement() {} - - virtual bool InitialiseGameRenderElement() = 0; - virtual void ReleaseGameRenderElement() = 0; - virtual void UpdatePrivateImplementation() = 0; - - virtual CREGameEffect* GetCREGameEffect() = 0; - - virtual IGameRenderElementParams* GetParams() = 0; -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: CGameRenderElement -// Desc: Base class for all game render elements -// Author: James Chilvers -//================================================================================================== -class CGameRenderElement - : public IGameRenderElement -{ - DECLARE_TYPE(CGameRenderElement, IGameRenderElement); // Exposes this type for SoftCoding -public: - CGameRenderElement(); - virtual ~CGameRenderElement() {} - - virtual bool InitialiseGameRenderElement(); - virtual void ReleaseGameRenderElement(); - virtual void UpdatePrivateImplementation(); - - virtual CREGameEffect* GetCREGameEffect(); - -protected: - CREGameEffect* SOFT(m_pREGameEffect); -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: IGameRenderElementParams -// Desc: Game Render Element params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderElementParams -{ - virtual ~IGameRenderElementParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp deleted file mode 100644 index 76bb0eb325..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameRenderElementSoftCodeLibrary -// Desc: Render Node Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include -#include "RenderElements/GameRenderElement.h" - -IMPLEMENT_TYPELIB(IGameRenderElement, - GAME_RENDER_ELEMENT_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp deleted file mode 100644 index a46e964016..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameRenderNodeSoftCodeLibrary -// Desc: Render Node Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include -#include -#include - -IMPLEMENT_TYPELIB(IGameRenderNode, GAME_RENDER_NODE_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h b/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h deleted file mode 100644 index 7a88db116d..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H -#define CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H -#pragma once - -#include "Effects/RenderElements/GameRenderElement.h" -#include "Effects/GameEffectsSystem.h" - -// Forward declares -struct IGameRenderNodeParams; - -//================================================================================================== -// Name: IGameRenderNode -// Desc: Base interface for all game render nodes -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNode - : public IRenderNode - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderNode); // Allow soft coding on this interface - - virtual ~IGameRenderNode() {} - - virtual bool InitialiseGameRenderNode() = 0; - virtual void ReleaseGameRenderNode() = 0; - - virtual void SetParams(const IGameRenderNodeParams* pParams = NULL) = 0; -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: IGameRenderNodeParams -// Desc: Game render node params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNodeParams -{ - virtual ~IGameRenderNodeParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif // CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H diff --git a/Gems/GameEffectSystem/gem.json b/Gems/GameEffectSystem/gem.json deleted file mode 100644 index ad97bc61ea..0000000000 --- a/Gems/GameEffectSystem/gem.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "gem_name": "GameEffectSystem", - "GemFormatVersion": 3, - "LinkType": "DynamicStatic", - "Name": "GameEffectSystem", - "DisplayName": "Game Effect System", - "Summary": "Provides fundamentals for creating and managing visual effects.", - "Tags": ["Effects System"], - "Uuid": "d378b5a7b47747d0a7aa741945df58f3", - "Version": "1.0.0", - "IconPath": "preview.png" -} diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl index 174a5b43c4..335291d57e 100644 --- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl +++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl @@ -27,7 +27,6 @@ #include #include -#include #include #include @@ -59,10 +58,6 @@ namespace GameStateSamples { // Unload the currently loaded level levelSystem->UnloadLevel(); - if (iSystem->GetI3DEngine()) - { - iSystem->GetI3DEngine()->LoadEmptyLevel(); - } } } diff --git a/Gems/Gestures/Code/Source/Gestures_precompiled.h b/Gems/Gestures/Code/Source/Gestures_precompiled.h index c51e121abc..926c68d091 100644 --- a/Gems/Gestures/Code/Source/Gestures_precompiled.h +++ b/Gems/Gestures/Code/Source/Gestures_precompiled.h @@ -13,5 +13,4 @@ #pragma once #include -#include #include diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index 362ef61185..7b8c9813e6 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -24,7 +24,6 @@ ly_add_target( Legacy::CryCommon Gem::LmbrCentral Gem::SurfaceData - Gem::ImageProcessing.Headers Gem::ImageProcessingAtom.Headers ) @@ -42,7 +41,6 @@ ly_add_target( PRIVATE Gem::GradientSignal.Static PUBLIC - Gem::ImageProcessing.Headers # ImageProcessing/PixelFormats.h is part of a header in Includes Gem::ImageProcessingAtom.Headers # Atom/ImageProcessing/PixelFormats.h is part of a header in Includes RUNTIME_DEPENDENCIES Gem::LmbrCentral diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h index 20db212da1..3114b4e811 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace AZ { @@ -42,7 +42,7 @@ namespace GradientSignal AZ::u32 m_imageWidth = 0; AZ::u32 m_imageHeight = 0; AZ::u8 m_bytesPerPixel = 0; - ImageProcessing::EPixelFormat m_imageFormat = ImageProcessing::EPixelFormat::ePixelFormat_Unknown; + ImageProcessingAtom::EPixelFormat m_imageFormat = ImageProcessingAtom::EPixelFormat::ePixelFormat_Unknown; AZStd::vector m_imageData; }; diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index cc207b59a3..ceaf2268e1 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -28,8 +28,6 @@ #include #include #include -#include -#include #include #include @@ -257,14 +255,6 @@ namespace GradientSignal return AZ::Uuid::CreateString("{7520DF20-16CA-4CF6-A6DB-D96759A09EE4}"); } - static ImageProcessing::EPixelFormat AtomPixelFormatToLegacyPixelFormat(ImageProcessingAtom::EPixelFormat atomPixFormat) - { - // This could be dangerous to do if these enums have differences in the middle. - // So far the enumerations correspond 1-to-1. Worst case this could be changed into a massive switch block. - int pixelFormatInt = static_cast(atomPixFormat); - return static_cast(pixelFormatInt); - } - static AZStd::unique_ptr AtomLoadImageFromPath(const AZStd::string& fullPath) { ImageProcessingAtom::IImageObjectPtr imageObject; @@ -286,7 +276,7 @@ namespace GradientSignal imageAsset->m_imageWidth = imageObject->GetWidth(0); imageAsset->m_imageHeight = imageObject->GetHeight(0); - imageAsset->m_imageFormat = AtomPixelFormatToLegacyPixelFormat(imageObject->GetPixelFormat()); + imageAsset->m_imageFormat = imageObject->GetPixelFormat(); AZ::u8* mem = nullptr; AZ::u32 pitch = 0; diff --git a/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp b/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp index cfbb71936b..4ed9107c47 100644 --- a/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp +++ b/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp @@ -13,7 +13,7 @@ #include "GradientSignal_precompiled.h" #include -#include +#include namespace { @@ -25,10 +25,10 @@ namespace constexpr auto A = 3; } - ImageProcessing::EPixelFormat ExportFormatToPixelFormat(GradientSignal::ExportFormat format) + ImageProcessingAtom::EPixelFormat ExportFormatToPixelFormat(GradientSignal::ExportFormat format) { using namespace GradientSignal; - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (format) { @@ -49,29 +49,29 @@ namespace } } - template + template struct Underlying {}; template <> - struct Underlying + struct Underlying { using type = AZ::u8; }; template <> - struct Underlying + struct Underlying { using type = AZ::u16; }; template <> - struct Underlying + struct Underlying { using type = AZ::u32; }; template <> - struct Underlying + struct Underlying { using type = float; }; @@ -167,10 +167,10 @@ namespace buffer = AZStd::move(newBuffer); } - template - void ConvertBufferType(AZStd::vector& buffer, ImageProcessing::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) + template + void ConvertBufferType(AZStd::vector& buffer, ImageProcessingAtom::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (newFormat) { @@ -195,9 +195,9 @@ namespace } } - ImageProcessing::EPixelFormat ConvertBufferType(AZStd::vector& buffer, ImageProcessing::EPixelFormat old, ImageProcessing::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) + ImageProcessingAtom::EPixelFormat ConvertBufferType(AZStd::vector& buffer, ImageProcessingAtom::EPixelFormat old, ImageProcessingAtom::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (old) { @@ -356,9 +356,9 @@ namespace mem.resize(mem.size() / channels); } - AZStd::size_t GetChannels(ImageProcessing::EPixelFormat format) + AZStd::size_t GetChannels(ImageProcessingAtom::EPixelFormat format) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (format) { @@ -379,10 +379,10 @@ namespace } template